DachengZhang commited on
Commit
95926b3
1 Parent(s): 56f2f3c

first commit

Browse files
config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "YiForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_yi.YiConfig",
7
+ "AutoModel": "modeling_yi.YiModel",
8
+ "AutoModelForCausalLM":"modeling_yi.YiForCausalLM"
9
+ },
10
+ "bos_token_id": 1,
11
+ "eos_token_id": 2,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 7168,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 20480,
16
+ "max_position_embeddings": 4096,
17
+ "model_type": "Yi",
18
+ "num_attention_heads": 56,
19
+ "num_hidden_layers": 60,
20
+ "num_key_value_heads": 8,
21
+ "pad_token_id": 0,
22
+ "rms_norm_eps": 1e-05,
23
+ "rope_theta": 5000000.0,
24
+ "tie_word_embeddings": false,
25
+ "torch_dtype": "bfloat16",
26
+ "transformers_version": "4.34.0",
27
+ "use_cache": true,
28
+ "vocab_size": 64000
29
+ }
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"text-generation"}
configuration_yi.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Yi model configuration"""
2
+ from transformers.configuration_utils import PretrainedConfig
3
+ from transformers.utils import logging
4
+
5
+ logger = logging.get_logger(__name__)
6
+
7
+ Yi_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
8
+
9
+
10
+ class YiConfig(PretrainedConfig):
11
+ r"""
12
+ This is the configuration class to store the configuration of a [`YiModel`]. It is used to instantiate an Yi
13
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
14
+ defaults will yield a similar configuration to that of the Yi model.
15
+
16
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
17
+ documentation from [`PretrainedConfig`] for more information.
18
+
19
+
20
+ Args:
21
+ vocab_size (`int`, *optional*, defaults to 64000):
22
+ Vocabulary size of the Yi model. Defines the number of different tokens that can be represented by the
23
+ `inputs_ids` passed when calling [`YiModel`]
24
+ hidden_size (`int`, *optional*, defaults to 4096):
25
+ Dimension of the hidden representations.
26
+ intermediate_size (`int`, *optional*, defaults to 11008):
27
+ Dimension of the MLP representations.
28
+ num_hidden_layers (`int`, *optional*, defaults to 32):
29
+ Number of hidden layers in the Transformer encoder.
30
+ num_attention_heads (`int`, *optional*, defaults to 32):
31
+ Number of attention heads for each attention layer in the Transformer encoder.
32
+ num_key_value_heads (`int`, *optional*):
33
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
34
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
35
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
36
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
37
+ by meanpooling all the original heads within that group. For more details checkout [this
38
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
39
+ `num_attention_heads`.
40
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
41
+ The non-linear activation function (function or string) in the decoder.
42
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
43
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
44
+ just in case (e.g., 512 or 1024 or 2048 or 4096).
45
+ initializer_range (`float`, *optional*, defaults to 0.02):
46
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
47
+ rms_norm_eps (`float`, *optional*, defaults to 1e-5):
48
+ The epsilon used by the rms normalization layers.
49
+ use_cache (`bool`, *optional*, defaults to `True`):
50
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
51
+ relevant if `config.is_decoder=True`.
52
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
53
+ Whether to tie weight embeddings
54
+ output_attentions (`bool`, *optional*, defaults to `False`):
55
+ Whether or not to output attentions.
56
+ rope_theta (`float`, *optional*, defaults to 5000000.0):
57
+ The base period of the RoPE embeddings.
58
+ Example:
59
+
60
+ ```python
61
+ >>> from transformers import YiModel, YiConfig
62
+
63
+ >>> # Initializing a Yi style configuration
64
+ >>> configuration = YiConfig()
65
+
66
+ >>> # Initializing a model from the Yi style configuration
67
+ >>> model = YiModel(configuration)
68
+
69
+ >>> # Accessing the model configuration
70
+ >>> configuration = model.config
71
+ ```"""
72
+ model_type = "Yi"
73
+ keys_to_ignore_at_inference = ["past_key_values"]
74
+
75
+ def __init__(
76
+ self,
77
+ vocab_size=64000,
78
+ hidden_size=4096,
79
+ intermediate_size=11008,
80
+ num_hidden_layers=32,
81
+ num_attention_heads=32,
82
+ num_key_value_heads=4,
83
+ hidden_act="silu",
84
+ max_position_embeddings=4096,
85
+ initializer_range=0.02,
86
+ rms_norm_eps=1e-5,
87
+ use_cache=True,
88
+ pad_token_id=0,
89
+ bos_token_id=1,
90
+ eos_token_id=2,
91
+ tie_word_embeddings=False,
92
+ output_attentions=False,
93
+ rope_theta=5000000.0,
94
+ **kwargs,
95
+ ):
96
+ self.vocab_size = vocab_size
97
+ self.max_position_embeddings = max_position_embeddings
98
+ self.hidden_size = hidden_size
99
+ self.intermediate_size = intermediate_size
100
+ self.num_hidden_layers = num_hidden_layers
101
+ self.num_attention_heads = num_attention_heads
102
+
103
+ # for backward compatibility
104
+ if num_key_value_heads is None:
105
+ num_key_value_heads = num_attention_heads
106
+
107
+ self.num_key_value_heads = num_key_value_heads
108
+ self.hidden_act = hidden_act
109
+ self.initializer_range = initializer_range
110
+ self.rms_norm_eps = rms_norm_eps
111
+ self.use_cache = use_cache
112
+ self.output_attentions = output_attentions
113
+ self.rope_theta = rope_theta
114
+
115
+ super().__init__(
116
+ pad_token_id=pad_token_id,
117
+ bos_token_id=bos_token_id,
118
+ eos_token_id=eos_token_id,
119
+ tie_word_embeddings=tie_word_embeddings,
120
+ **kwargs,
121
+ )
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "max_new_tokens": 256,
7
+ "temperature": 0.3,
8
+ "top_k": 5,
9
+ "top_p": 0.90,
10
+ "repetition_penalty": 1.05,
11
+ "do_sample": true,
12
+ "transformers_version": "4.34.0"
13
+ }
generation_utils.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ from queue import Queue
3
+
4
+ # build chat input prompt
5
+ def build_chat_input(tokenizer, messages: List[dict]):
6
+ # chat format:
7
+ # single-turn: <|startoftext|>Human: Hello!\n\nAssistant: <|endoftext|>
8
+ # multi-turn: <|startoftext|>Human: Hello!\n\nAssistant: <|endoftext|>Hi!<|endoftext|>Human: How are you?\n\nAssistant: <|endoftext|>target2<|endoftext|>
9
+
10
+ prompt = "<|startoftext|>"
11
+ for msg in messages:
12
+ role = msg["role"]
13
+ message = msg["content"]
14
+ if message is None :
15
+ continue
16
+ if role == "user":
17
+ prompt += "Human: " + message + "\n\nAssistant: <|endoftext|>"
18
+ if role == "assistant":
19
+ prompt += message + "<|endoftext|>"
20
+
21
+ input_tokens = tokenizer.encode(prompt)
22
+ return input_tokens
23
+
24
+
25
+ class TextIterStreamer:
26
+ def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False):
27
+ self.tokenizer = tokenizer
28
+ self.skip_prompt = skip_prompt
29
+ self.skip_special_tokens = skip_special_tokens
30
+ self.tokens = []
31
+ self.text_queue = Queue()
32
+ self.next_tokens_are_prompt = True
33
+
34
+ def put(self, value):
35
+ if self.skip_prompt and self.next_tokens_are_prompt:
36
+ self.next_tokens_are_prompt = False
37
+ else:
38
+ if len(value.shape) > 1:
39
+ value = value[0]
40
+ self.tokens.extend(value.tolist())
41
+ self.text_queue.put(
42
+ self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens))
43
+
44
+ def end(self):
45
+ self.text_queue.put(None)
46
+
47
+ def __iter__(self):
48
+ return self
49
+
50
+ def __next__(self):
51
+ value = self.text_queue.get()
52
+ if value is None:
53
+ raise StopIteration()
54
+ else:
55
+ return value
56
+
modeling_yi.py ADDED
@@ -0,0 +1,1055 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ PyTorch Yi model."""
2
+ import math
3
+ from typing import List, Optional, Tuple, Union
4
+
5
+ import torch.utils.checkpoint
6
+ from einops import repeat
7
+ from packaging import version
8
+ from torch import nn
9
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
10
+ from transformers.activations import ACT2FN
11
+ from transformers.modeling_outputs import (
12
+ BaseModelOutputWithPast,
13
+ CausalLMOutputWithPast,
14
+ SequenceClassifierOutputWithPast,
15
+ )
16
+ from transformers.modeling_utils import PreTrainedModel
17
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
18
+ from transformers.utils import (
19
+ add_start_docstrings,
20
+ add_start_docstrings_to_model_forward,
21
+ logging,
22
+ replace_return_docstrings,
23
+ )
24
+
25
+ from .configuration_yi import YiConfig
26
+ from .generation_utils import build_chat_input, TextIterStreamer
27
+ from transformers.generation.utils import GenerationConfig
28
+ from threading import Thread
29
+
30
+ is_flash_attn_available = True
31
+ try:
32
+ from flash_attn import flash_attn_func, __version__
33
+
34
+ assert version.parse(__version__) >= version.parse(
35
+ "2.3.0"
36
+ ), "please update your flash_attn version (>= 2.3.0)"
37
+ except ModuleNotFoundError:
38
+ is_flash_attn_available = False
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CONFIG_FOR_DOC = "YiConfig"
43
+
44
+
45
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
46
+ def _make_causal_mask(
47
+ input_ids_shape: torch.Size,
48
+ dtype: torch.dtype,
49
+ device: torch.device,
50
+ past_key_values_length: int = 0,
51
+ ):
52
+ """
53
+ Make causal mask used for bi-directional self-attention.
54
+ """
55
+ bsz, tgt_len = input_ids_shape
56
+ mask = torch.full(
57
+ (tgt_len, tgt_len),
58
+ torch.tensor(torch.finfo(dtype).min, device=device),
59
+ device=device,
60
+ )
61
+ mask_cond = torch.arange(mask.size(-1), device=device)
62
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
63
+ mask = mask.to(dtype)
64
+
65
+ if past_key_values_length > 0:
66
+ mask = torch.cat(
67
+ [
68
+ torch.zeros(
69
+ tgt_len, past_key_values_length, dtype=dtype, device=device
70
+ ),
71
+ mask,
72
+ ],
73
+ dim=-1,
74
+ )
75
+ return mask[None, None, :, :].expand(
76
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
77
+ )
78
+
79
+
80
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
81
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
82
+ """
83
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
84
+ """
85
+ bsz, src_len = mask.size()
86
+ tgt_len = tgt_len if tgt_len is not None else src_len
87
+
88
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
89
+
90
+ inverted_mask = 1.0 - expanded_mask
91
+
92
+ return inverted_mask.masked_fill(
93
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
94
+ )
95
+
96
+
97
+ class YiRMSNorm(nn.Module):
98
+ def __init__(self, hidden_size, eps=1e-5):
99
+ """
100
+ YiRMSNorm is equivalent to T5LayerNorm
101
+ """
102
+ super().__init__()
103
+ self.weight = nn.Parameter(torch.ones(hidden_size))
104
+ self.variance_epsilon = eps
105
+
106
+ def forward(self, hidden_states):
107
+ input_dtype = hidden_states.dtype
108
+ hidden_states = hidden_states.to(torch.float32)
109
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
110
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
111
+
112
+ return self.weight * hidden_states.to(input_dtype)
113
+
114
+
115
+ ALL_LAYERNORM_LAYERS.append(YiRMSNorm)
116
+
117
+
118
+ class YiRotaryEmbedding(torch.nn.Module):
119
+ def __init__(self, dim, max_position_embeddings=4096, base=5000000, device=None):
120
+ super().__init__()
121
+
122
+ self.dim = dim
123
+ self.max_position_embeddings = max_position_embeddings
124
+ self.base = base
125
+
126
+ # Build here to make `torch.jit.trace` work.
127
+ self._set_cos_sin_cache(seq_len=max_position_embeddings, device=device)
128
+
129
+ def _set_cos_sin_cache(self, seq_len, device):
130
+ self.max_seq_len_cached = seq_len
131
+ inv_freq = 1.0 / (
132
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
133
+ )
134
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
135
+ freqs = torch.einsum("i,j->ij", t, inv_freq)
136
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
137
+ emb = torch.cat((freqs, freqs), dim=-1)
138
+ self.register_buffer(
139
+ "cos_cached", emb.cos()[None, None, :, :], persistent=False
140
+ )
141
+ self.register_buffer(
142
+ "sin_cached", emb.sin()[None, None, :, :], persistent=False
143
+ )
144
+
145
+ def forward(self, x, seq_len=None):
146
+ # x: [bs, num_attention_heads, seq_len, head_size]
147
+ if seq_len > self.max_seq_len_cached:
148
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device)
149
+
150
+ return (
151
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
152
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
153
+ )
154
+
155
+
156
+ def rotate_half(x):
157
+ """Rotates half the hidden dims of the input."""
158
+ x1 = x[..., : x.shape[-1] // 2]
159
+ x2 = x[..., x.shape[-1] // 2 :]
160
+ return torch.cat((-x2, x1), dim=-1)
161
+
162
+
163
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, flash_attn_available):
164
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
165
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
166
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
167
+ expand_dim = 2 if flash_attn_available else 1
168
+ cos = cos[position_ids].unsqueeze(expand_dim) # [bs, seq_len, dim]
169
+ sin = sin[position_ids].unsqueeze(expand_dim) # [bs, seq_len, dim]
170
+ q_embed = (q * cos) + (rotate_half(q) * sin)
171
+ k_embed = (k * cos) + (rotate_half(k) * sin)
172
+ return q_embed, k_embed
173
+
174
+
175
+ class YiMLP(nn.Module):
176
+ def __init__(self, hidden_size: int, intermediate_size: int, hidden_act: str):
177
+ super().__init__()
178
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
179
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
180
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
181
+ self.act_fn = ACT2FN[hidden_act]
182
+
183
+ def forward(self, x):
184
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
185
+
186
+
187
+ class YiAttention(nn.Module):
188
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
189
+
190
+ def __init__(self, config: YiConfig):
191
+ super().__init__()
192
+ self.config = config
193
+ self.hidden_size = config.hidden_size
194
+ self.num_heads = config.num_attention_heads
195
+ self.head_dim = self.hidden_size // self.num_heads
196
+ self.num_key_value_heads = config.num_key_value_heads
197
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
198
+ self.max_position_embeddings = config.max_position_embeddings
199
+
200
+ if (self.head_dim * self.num_heads) != self.hidden_size:
201
+ raise ValueError(
202
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
203
+ f" and `num_heads`: {self.num_heads})."
204
+ )
205
+ self.q_proj = nn.Linear(
206
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
207
+ )
208
+ self.k_proj = nn.Linear(
209
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
210
+ )
211
+ self.v_proj = nn.Linear(
212
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
213
+ )
214
+ self.o_proj = nn.Linear(
215
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
216
+ )
217
+
218
+ self.rotary_emb = YiRotaryEmbedding(
219
+ self.head_dim,
220
+ max_position_embeddings=self.max_position_embeddings,
221
+ base=self.config.rope_theta,
222
+ )
223
+
224
+ def forward(
225
+ self,
226
+ hidden_states: torch.Tensor,
227
+ attention_mask: Optional[torch.Tensor] = None,
228
+ position_ids: Optional[torch.LongTensor] = None,
229
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
230
+ output_attentions: bool = False,
231
+ use_cache: bool = False,
232
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
233
+ bsz, q_len, _ = hidden_states.size()
234
+
235
+ query_states = self.q_proj(hidden_states).view(
236
+ bsz, q_len, self.num_heads, self.head_dim
237
+ )
238
+
239
+ key_states = self.k_proj(hidden_states).view(
240
+ bsz, q_len, self.num_key_value_heads, self.head_dim
241
+ )
242
+ value_states = self.v_proj(hidden_states).view(
243
+ bsz, q_len, self.num_key_value_heads, self.head_dim
244
+ )
245
+
246
+ if not is_flash_attn_available:
247
+ if self.num_key_value_groups > 1:
248
+ key_states = repeat(
249
+ key_states, f"b n h d -> b n (h {self.num_key_value_groups}) d"
250
+ )
251
+ value_states = repeat(
252
+ value_states, f"b n h d -> b n (h {self.num_key_value_groups}) d"
253
+ )
254
+
255
+ # b n h d -> b h n d
256
+ query_states = query_states.transpose(1, 2)
257
+ key_states = key_states.transpose(1, 2)
258
+ value_states = value_states.transpose(1, 2)
259
+
260
+ seq_dim = 1 if is_flash_attn_available else 2
261
+ kv_seq_len = key_states.shape[seq_dim]
262
+ if past_key_value is not None:
263
+ kv_seq_len += past_key_value[0].shape[seq_dim]
264
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
265
+ query_states, key_states = apply_rotary_pos_emb(
266
+ query_states, key_states, cos, sin, position_ids, is_flash_attn_available
267
+ )
268
+
269
+ if past_key_value is not None:
270
+ # reuse k, v, self_attention
271
+ key_states = torch.cat([past_key_value[0], key_states], dim=seq_dim)
272
+ value_states = torch.cat([past_key_value[1], value_states], dim=seq_dim)
273
+
274
+ past_key_value = (key_states, value_states) if use_cache else None
275
+
276
+ if is_flash_attn_available:
277
+ attn_output = flash_attn_func(
278
+ query_states, key_states, value_states, dropout_p=0.0, causal=True
279
+ )
280
+ else:
281
+ attn_weights = torch.matmul(
282
+ query_states, key_states.transpose(2, 3)
283
+ ) / math.sqrt(self.head_dim)
284
+
285
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
286
+ raise ValueError(
287
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
288
+ f" {attn_weights.size()}"
289
+ )
290
+
291
+ if attention_mask is not None:
292
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
293
+ raise ValueError(
294
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is"
295
+ f"{attention_mask.size()}"
296
+ )
297
+ attn_weights = attn_weights + attention_mask
298
+ dtype_min = torch.tensor(
299
+ torch.finfo(attn_weights.dtype).min,
300
+ device=attn_weights.device,
301
+ dtype=attn_weights.dtype,
302
+ )
303
+ attn_weights = torch.max(attn_weights, dtype_min)
304
+
305
+ # upcast attention to fp32
306
+ attn_weights = nn.functional.softmax(
307
+ attn_weights, dim=-1, dtype=torch.float32
308
+ ).to(query_states.dtype)
309
+ attn_output = torch.matmul(attn_weights, value_states)
310
+
311
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
312
+ raise ValueError(
313
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
314
+ f" {attn_output.size()}"
315
+ )
316
+
317
+ if not is_flash_attn_available:
318
+ attn_output = attn_output.transpose(1, 2)
319
+
320
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
321
+
322
+ attn_output = self.o_proj(attn_output)
323
+
324
+ if not output_attentions:
325
+ attn_weights = None
326
+
327
+ return attn_output, attn_weights, past_key_value
328
+
329
+
330
+ class YiDecoderLayer(nn.Module):
331
+ def __init__(self, config: YiConfig):
332
+ super().__init__()
333
+
334
+ self.hidden_size = config.hidden_size
335
+ self.self_attn = YiAttention(config=config)
336
+ self.mlp = YiMLP(
337
+ hidden_size=self.hidden_size,
338
+ intermediate_size=config.intermediate_size,
339
+ hidden_act=config.hidden_act,
340
+ )
341
+
342
+ self.ln1 = YiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
343
+ self.ln2 = YiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
344
+
345
+ def forward(
346
+ self,
347
+ hidden_states: torch.Tensor,
348
+ attention_mask: Optional[torch.Tensor] = None,
349
+ position_ids: Optional[torch.LongTensor] = None,
350
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
351
+ output_attentions: Optional[bool] = False,
352
+ use_cache: Optional[bool] = False,
353
+ ) -> Tuple[
354
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
355
+ ]:
356
+ """
357
+ Args:
358
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
359
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
360
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
361
+ output_attentions (`bool`, *optional*):
362
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
363
+ returned tensors for more detail.
364
+ use_cache (`bool`, *optional*):
365
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
366
+ (see `past_key_values`).
367
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
368
+ """
369
+
370
+ residual = hidden_states
371
+
372
+ hidden_states = self.ln1(hidden_states)
373
+
374
+ # Self Attention
375
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
376
+ hidden_states=hidden_states,
377
+ attention_mask=attention_mask,
378
+ position_ids=position_ids,
379
+ past_key_value=past_key_value,
380
+ output_attentions=output_attentions,
381
+ use_cache=use_cache,
382
+ )
383
+ hidden_states = residual + hidden_states
384
+
385
+ # Fully Connected
386
+ residual = hidden_states
387
+ hidden_states = self.ln2(hidden_states)
388
+ hidden_states = self.mlp(hidden_states)
389
+ hidden_states = residual + hidden_states
390
+
391
+ outputs = (hidden_states,)
392
+
393
+ if output_attentions:
394
+ outputs += (self_attn_weights,)
395
+
396
+ if use_cache:
397
+ outputs += (present_key_value,)
398
+
399
+ return outputs
400
+
401
+
402
+ Yi_START_DOCSTRING = r"""
403
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
404
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
405
+ etc.)
406
+
407
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
408
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
409
+ and behavior.
410
+
411
+ Parameters:
412
+ config ([`YiConfig`]):
413
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
414
+ load the weights associated with the model, only the configuration. Check out the
415
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
416
+ """
417
+
418
+
419
+ @add_start_docstrings(
420
+ "The bare Yi Model outputting raw hidden-states without any specific head on top.",
421
+ Yi_START_DOCSTRING,
422
+ )
423
+ class YiPreTrainedModel(PreTrainedModel):
424
+ config_class = YiConfig
425
+ base_model_prefix = "model"
426
+ supports_gradient_checkpointing = True
427
+ _no_split_modules = ["YiDecoderLayer"]
428
+ _skip_keys_device_placement = "past_key_values"
429
+
430
+ def _init_weights(self, module):
431
+ std = self.config.initializer_range
432
+ if isinstance(module, nn.Linear):
433
+ module.weight.data.normal_(mean=0.0, std=std)
434
+ if module.bias is not None:
435
+ module.bias.data.zero_()
436
+ elif isinstance(module, nn.Embedding):
437
+ module.weight.data.normal_(mean=0.0, std=std)
438
+ if module.padding_idx is not None:
439
+ module.weight.data[module.padding_idx].zero_()
440
+
441
+ def _set_gradient_checkpointing(self, module, value=False):
442
+ if isinstance(module, YiModel):
443
+ module.gradient_checkpointing = value
444
+
445
+
446
+ Yi_INPUTS_DOCSTRING = r"""
447
+ Args:
448
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
449
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
450
+ it.
451
+
452
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
453
+ [`PreTrainedTokenizer.__call__`] for details.
454
+
455
+ [What are input IDs?](../glossary#input-ids)
456
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
457
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
458
+
459
+ - 1 for tokens that are **not masked**,
460
+ - 0 for tokens that are **masked**.
461
+
462
+ [What are attention masks?](../glossary#attention-mask)
463
+
464
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
465
+ [`PreTrainedTokenizer.__call__`] for details.
466
+
467
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
468
+ `past_key_values`).
469
+
470
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
471
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
472
+ information on the default strategy.
473
+
474
+ - 1 indicates the head is **not masked**,
475
+ - 0 indicates the head is **masked**.
476
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
477
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
478
+ config.n_positions - 1]`.
479
+
480
+ [What are position IDs?](../glossary#position-ids)
481
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
482
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
483
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
484
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
485
+
486
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
487
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
488
+
489
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
490
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
491
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
492
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
493
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
494
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
495
+ model's internal embedding lookup matrix.
496
+ use_cache (`bool`, *optional*):
497
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
498
+ `past_key_values`).
499
+ output_attentions (`bool`, *optional*):
500
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
501
+ tensors for more detail.
502
+ output_hidden_states (`bool`, *optional*):
503
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
504
+ more detail.
505
+ return_dict (`bool`, *optional*):
506
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
507
+ """
508
+
509
+
510
+ @add_start_docstrings(
511
+ "The bare Yi Model outputting raw hidden-states without any specific head on top.",
512
+ Yi_START_DOCSTRING,
513
+ )
514
+ class YiModel(YiPreTrainedModel):
515
+ """
516
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`YiDecoderLayer`]
517
+
518
+ Args:
519
+ config: YiConfig
520
+ """
521
+
522
+ def __init__(self, config: YiConfig):
523
+ super().__init__(config)
524
+ self.padding_idx = config.pad_token_id
525
+ self.vocab_size = config.vocab_size
526
+
527
+ self.embed_tokens = nn.Embedding(
528
+ config.vocab_size, config.hidden_size, self.padding_idx
529
+ )
530
+ self.layers = nn.ModuleList(
531
+ [YiDecoderLayer(config) for _ in range(config.num_hidden_layers)]
532
+ )
533
+
534
+ self.norm = YiRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
535
+
536
+ self.gradient_checkpointing = False
537
+ # Initialize weights and apply final processing
538
+ self.post_init()
539
+
540
+ def get_input_embeddings(self):
541
+ return self.embed_tokens
542
+
543
+ def set_input_embeddings(self, value):
544
+ self.embed_tokens = value
545
+
546
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
547
+ def _prepare_decoder_attention_mask(
548
+ self, attention_mask, input_ids, inputs_embeds, past_key_values_length
549
+ ):
550
+ input_shape = (
551
+ input_ids.shape if input_ids is not None else inputs_embeds.shape[:-1]
552
+ )
553
+ # create causal mask
554
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
555
+ combined_attention_mask = None
556
+ if input_shape[-1] > 1:
557
+ combined_attention_mask = _make_causal_mask(
558
+ input_shape,
559
+ inputs_embeds.dtype,
560
+ device=inputs_embeds.device,
561
+ past_key_values_length=past_key_values_length,
562
+ )
563
+
564
+ if attention_mask is not None:
565
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
566
+ expanded_attn_mask = _expand_mask(
567
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
568
+ ).to(inputs_embeds.device)
569
+ combined_attention_mask = (
570
+ expanded_attn_mask
571
+ if combined_attention_mask is None
572
+ else expanded_attn_mask + combined_attention_mask
573
+ )
574
+
575
+ return combined_attention_mask
576
+
577
+ @add_start_docstrings_to_model_forward(Yi_INPUTS_DOCSTRING)
578
+ def forward(
579
+ self,
580
+ input_ids: torch.LongTensor = None,
581
+ attention_mask: Optional[torch.Tensor] = None,
582
+ position_ids: Optional[torch.LongTensor] = None,
583
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
584
+ inputs_embeds: Optional[torch.FloatTensor] = None,
585
+ use_cache: Optional[bool] = None,
586
+ output_attentions: Optional[bool] = None,
587
+ output_hidden_states: Optional[bool] = None,
588
+ return_dict: Optional[bool] = None,
589
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
590
+ output_attentions = (
591
+ output_attentions
592
+ if output_attentions is not None
593
+ else self.config.output_attentions
594
+ )
595
+ output_hidden_states = (
596
+ output_hidden_states
597
+ if output_hidden_states is not None
598
+ else self.config.output_hidden_states
599
+ )
600
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
601
+
602
+ return_dict = (
603
+ return_dict if return_dict is not None else self.config.use_return_dict
604
+ )
605
+
606
+ # retrieve input_ids and inputs_embeds
607
+ if input_ids is not None and inputs_embeds is not None:
608
+ raise ValueError(
609
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
610
+ )
611
+ elif input_ids is not None:
612
+ batch_size, seq_length = input_ids.shape
613
+ elif inputs_embeds is not None:
614
+ batch_size, seq_length, _ = inputs_embeds.shape
615
+ else:
616
+ raise ValueError(
617
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
618
+ )
619
+
620
+ seq_length_with_past = seq_length
621
+ past_key_values_length = 0
622
+
623
+ if past_key_values is not None:
624
+ past_key_values_length = past_key_values[0][0].shape[2]
625
+ seq_length_with_past = seq_length_with_past + past_key_values_length
626
+
627
+ if position_ids is None:
628
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
629
+ position_ids = torch.arange(
630
+ past_key_values_length,
631
+ seq_length + past_key_values_length,
632
+ dtype=torch.long,
633
+ device=device,
634
+ )
635
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
636
+ else:
637
+ position_ids = position_ids.view(-1, seq_length).long()
638
+
639
+ if inputs_embeds is None:
640
+ inputs_embeds = self.embed_tokens(input_ids)
641
+
642
+ if not is_flash_attn_available:
643
+ # embed positions
644
+ if attention_mask is None:
645
+ attention_mask = torch.ones(
646
+ (batch_size, seq_length_with_past),
647
+ dtype=torch.bool,
648
+ device=inputs_embeds.device,
649
+ )
650
+ attention_mask = self._prepare_decoder_attention_mask(
651
+ attention_mask,
652
+ input_ids,
653
+ inputs_embeds,
654
+ past_key_values_length,
655
+ )
656
+ else:
657
+ attention_mask = None
658
+
659
+ hidden_states = inputs_embeds
660
+ if self.gradient_checkpointing and self.training:
661
+ if use_cache:
662
+ logger.warning_once(
663
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
664
+ )
665
+ use_cache = False
666
+
667
+ # decoder layers
668
+ all_hidden_states = () if output_hidden_states else None
669
+ all_self_attns = () if output_attentions else None
670
+ next_decoder_cache = () if use_cache else None
671
+
672
+ for idx, decoder_layer in enumerate(self.layers):
673
+ if output_hidden_states:
674
+ all_hidden_states += (hidden_states,)
675
+
676
+ past_key_value = (
677
+ past_key_values[idx] if past_key_values is not None else None
678
+ )
679
+
680
+ if self.gradient_checkpointing and self.training:
681
+
682
+ def create_custom_forward(module):
683
+ def custom_forward(*inputs):
684
+ # None for past_key_value
685
+ return module(*inputs, past_key_value, output_attentions)
686
+
687
+ return custom_forward
688
+
689
+ layer_outputs = torch.utils.checkpoint.checkpoint(
690
+ create_custom_forward(decoder_layer),
691
+ hidden_states,
692
+ attention_mask,
693
+ position_ids,
694
+ )
695
+ else:
696
+ layer_outputs = decoder_layer(
697
+ hidden_states,
698
+ attention_mask=attention_mask,
699
+ position_ids=position_ids,
700
+ past_key_value=past_key_value,
701
+ output_attentions=output_attentions,
702
+ use_cache=use_cache,
703
+ )
704
+
705
+ hidden_states = layer_outputs[0]
706
+
707
+ if use_cache:
708
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
709
+
710
+ if output_attentions:
711
+ all_self_attns += (layer_outputs[1],)
712
+
713
+ hidden_states = self.norm(hidden_states)
714
+ # add hidden states from the last decoder layer
715
+ if output_hidden_states:
716
+ all_hidden_states += (hidden_states,)
717
+
718
+ next_cache = next_decoder_cache if use_cache else None
719
+ if not return_dict:
720
+ return tuple(
721
+ v
722
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
723
+ if v is not None
724
+ )
725
+ return BaseModelOutputWithPast(
726
+ last_hidden_state=hidden_states,
727
+ past_key_values=next_cache,
728
+ hidden_states=all_hidden_states,
729
+ attentions=all_self_attns,
730
+ )
731
+
732
+
733
+ class YiForCausalLM(YiPreTrainedModel):
734
+ _tied_weights_keys = ["lm_head.weight"]
735
+
736
+ def __init__(self, config):
737
+ super().__init__(config)
738
+ self.model = YiModel(config)
739
+
740
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
741
+
742
+ # Initialize weights and apply final processing
743
+ self.post_init()
744
+
745
+ def get_input_embeddings(self):
746
+ return self.model.embed_tokens
747
+
748
+ def set_input_embeddings(self, value):
749
+ self.model.embed_tokens = value
750
+
751
+ def get_output_embeddings(self):
752
+ return self.lm_head
753
+
754
+ def set_output_embeddings(self, new_embeddings):
755
+ self.lm_head = new_embeddings
756
+
757
+ def set_decoder(self, decoder):
758
+ self.model = decoder
759
+
760
+ def get_decoder(self):
761
+ return self.model
762
+
763
+ @add_start_docstrings_to_model_forward(Yi_INPUTS_DOCSTRING)
764
+ @replace_return_docstrings(
765
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
766
+ )
767
+ def forward(
768
+ self,
769
+ input_ids: torch.LongTensor = None,
770
+ attention_mask: Optional[torch.Tensor] = None,
771
+ position_ids: Optional[torch.LongTensor] = None,
772
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
773
+ inputs_embeds: Optional[torch.FloatTensor] = None,
774
+ labels: Optional[torch.LongTensor] = None,
775
+ use_cache: Optional[bool] = None,
776
+ output_attentions: Optional[bool] = None,
777
+ output_hidden_states: Optional[bool] = None,
778
+ return_dict: Optional[bool] = None,
779
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
780
+ r"""
781
+ Args:
782
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
783
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
784
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
785
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
786
+
787
+ Returns:
788
+
789
+ Example:
790
+
791
+ ```python
792
+ >>> from transformers import AutoTokenizer, YiForCausalLM
793
+
794
+ >>> model = YiForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
795
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
796
+
797
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
798
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
799
+
800
+ >>> # Generate
801
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
802
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
803
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
804
+ ```"""
805
+
806
+ output_attentions = (
807
+ output_attentions
808
+ if output_attentions is not None
809
+ else self.config.output_attentions
810
+ )
811
+ output_hidden_states = (
812
+ output_hidden_states
813
+ if output_hidden_states is not None
814
+ else self.config.output_hidden_states
815
+ )
816
+ return_dict = (
817
+ return_dict if return_dict is not None else self.config.use_return_dict
818
+ )
819
+
820
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
821
+ outputs = self.model(
822
+ input_ids=input_ids,
823
+ attention_mask=attention_mask,
824
+ position_ids=position_ids,
825
+ past_key_values=past_key_values,
826
+ inputs_embeds=inputs_embeds,
827
+ use_cache=use_cache,
828
+ output_attentions=output_attentions,
829
+ output_hidden_states=output_hidden_states,
830
+ return_dict=return_dict,
831
+ )
832
+
833
+ hidden_states = outputs[0]
834
+ logits = self.lm_head(hidden_states)
835
+
836
+ loss = None
837
+ if labels is not None:
838
+ # Shift so that tokens < n predict n
839
+ shift_logits = logits[..., :-1, :].contiguous()
840
+ shift_labels = labels[..., 1:].contiguous()
841
+ # Flatten the tokens
842
+ loss_fct = CrossEntropyLoss()
843
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
844
+ shift_labels = shift_labels.view(-1)
845
+ # Enable model parallelism
846
+ shift_labels = shift_labels.to(shift_logits.device)
847
+ loss = loss_fct(shift_logits, shift_labels)
848
+
849
+ if not return_dict:
850
+ output = (logits,) + outputs[1:]
851
+ return (loss,) + output if loss is not None else output
852
+
853
+ return CausalLMOutputWithPast(
854
+ loss=loss,
855
+ logits=logits,
856
+ past_key_values=outputs.past_key_values,
857
+ hidden_states=outputs.hidden_states,
858
+ attentions=outputs.attentions,
859
+ )
860
+
861
+ def chat(self, tokenizer, messages: List[dict], streaming=False,generation_config: Optional[GenerationConfig]=None):
862
+ generation_config = generation_config or self.generation_config
863
+ input_tokens = build_chat_input(tokenizer,messages)
864
+ input_ids = torch.LongTensor([input_tokens]).to(self.device)
865
+
866
+ if streaming:
867
+ streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
868
+ Thread(target=self.generate, kwargs=dict(
869
+ inputs=input_ids, streamer=streamer,
870
+ generation_config=generation_config,
871
+ )).start()
872
+ return streamer
873
+ else:
874
+ outputs = self.generate(input_ids, generation_config=generation_config)
875
+ response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)
876
+ return response
877
+
878
+ def prepare_inputs_for_generation(
879
+ self,
880
+ input_ids,
881
+ past_key_values=None,
882
+ attention_mask=None,
883
+ inputs_embeds=None,
884
+ **kwargs,
885
+ ):
886
+ if past_key_values:
887
+ input_ids = input_ids[:, -1:]
888
+
889
+ position_ids = kwargs.get("position_ids", None)
890
+ if attention_mask is not None and position_ids is None:
891
+ # create position_ids on the fly for batch generation
892
+ position_ids = attention_mask.long().cumsum(-1) - 1
893
+ position_ids.masked_fill_(attention_mask == 0, 1)
894
+ if past_key_values:
895
+ position_ids = position_ids[:, -1].unsqueeze(-1)
896
+
897
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
898
+ if inputs_embeds is not None and past_key_values is None:
899
+ model_inputs = {"inputs_embeds": inputs_embeds}
900
+ else:
901
+ model_inputs = {"input_ids": input_ids}
902
+
903
+ model_inputs.update(
904
+ {
905
+ "position_ids": position_ids,
906
+ "past_key_values": past_key_values,
907
+ "use_cache": kwargs.get("use_cache"),
908
+ "attention_mask": attention_mask,
909
+ }
910
+ )
911
+ return model_inputs
912
+
913
+ @staticmethod
914
+ def _reorder_cache(past_key_values, beam_idx):
915
+ reordered_past = ()
916
+ for layer_past in past_key_values:
917
+ reordered_past += (
918
+ tuple(
919
+ past_state.index_select(0, beam_idx.to(past_state.device))
920
+ for past_state in layer_past
921
+ ),
922
+ )
923
+ return reordered_past
924
+
925
+
926
+ @add_start_docstrings(
927
+ """
928
+ The Yi Model transformer with a sequence classification head on top (linear layer).
929
+
930
+ [`YiForSequenceClassification`] uses the last token in order to do the classification, as other causal models
931
+ (e.g. GPT-2) do.
932
+
933
+ Since it does classification on the last token, it requires to know the position of the last token. If a
934
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
935
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
936
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
937
+ each row of the batch).
938
+ """,
939
+ Yi_START_DOCSTRING,
940
+ )
941
+ class YiForSequenceClassification(YiPreTrainedModel):
942
+ def __init__(self, config):
943
+ super().__init__(config)
944
+ self.num_labels = config.num_labels
945
+ self.model = YiModel(config)
946
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
947
+
948
+ # Initialize weights and apply final processing
949
+ self.post_init()
950
+
951
+ def get_input_embeddings(self):
952
+ return self.model.embed_tokens
953
+
954
+ def set_input_embeddings(self, value):
955
+ self.model.embed_tokens = value
956
+
957
+ @add_start_docstrings_to_model_forward(Yi_INPUTS_DOCSTRING)
958
+ def forward(
959
+ self,
960
+ input_ids: torch.LongTensor = None,
961
+ attention_mask: Optional[torch.Tensor] = None,
962
+ position_ids: Optional[torch.LongTensor] = None,
963
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
964
+ inputs_embeds: Optional[torch.FloatTensor] = None,
965
+ labels: Optional[torch.LongTensor] = None,
966
+ use_cache: Optional[bool] = None,
967
+ output_attentions: Optional[bool] = None,
968
+ output_hidden_states: Optional[bool] = None,
969
+ return_dict: Optional[bool] = None,
970
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
971
+ r"""
972
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
973
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
974
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
975
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
976
+ """
977
+ return_dict = (
978
+ return_dict if return_dict is not None else self.config.use_return_dict
979
+ )
980
+
981
+ transformer_outputs = self.model(
982
+ input_ids,
983
+ attention_mask=attention_mask,
984
+ position_ids=position_ids,
985
+ past_key_values=past_key_values,
986
+ inputs_embeds=inputs_embeds,
987
+ use_cache=use_cache,
988
+ output_attentions=output_attentions,
989
+ output_hidden_states=output_hidden_states,
990
+ return_dict=return_dict,
991
+ )
992
+ hidden_states = transformer_outputs[0]
993
+ logits = self.score(hidden_states)
994
+
995
+ if input_ids is not None:
996
+ batch_size = input_ids.shape[0]
997
+ else:
998
+ batch_size = inputs_embeds.shape[0]
999
+
1000
+ if self.config.pad_token_id is None and batch_size != 1:
1001
+ raise ValueError(
1002
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1003
+ )
1004
+ if self.config.pad_token_id is None:
1005
+ sequence_lengths = -1
1006
+ else:
1007
+ if input_ids is not None:
1008
+ sequence_lengths = (
1009
+ torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1
1010
+ ).to(logits.device)
1011
+ else:
1012
+ sequence_lengths = -1
1013
+
1014
+ pooled_logits = logits[
1015
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1016
+ ]
1017
+
1018
+ loss = None
1019
+ if labels is not None:
1020
+ labels = labels.to(logits.device)
1021
+ if self.config.problem_type is None:
1022
+ if self.num_labels == 1:
1023
+ self.config.problem_type = "regression"
1024
+ elif self.num_labels > 1 and (
1025
+ labels.dtype == torch.long or labels.dtype == torch.int
1026
+ ):
1027
+ self.config.problem_type = "single_label_classification"
1028
+ else:
1029
+ self.config.problem_type = "multi_label_classification"
1030
+
1031
+ if self.config.problem_type == "regression":
1032
+ loss_fct = MSELoss()
1033
+ if self.num_labels == 1:
1034
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1035
+ else:
1036
+ loss = loss_fct(pooled_logits, labels)
1037
+ elif self.config.problem_type == "single_label_classification":
1038
+ loss_fct = CrossEntropyLoss()
1039
+ loss = loss_fct(
1040
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1041
+ )
1042
+ elif self.config.problem_type == "multi_label_classification":
1043
+ loss_fct = BCEWithLogitsLoss()
1044
+ loss = loss_fct(pooled_logits, labels)
1045
+ if not return_dict:
1046
+ output = (pooled_logits,) + transformer_outputs[1:]
1047
+ return ((loss,) + output) if loss is not None else output
1048
+
1049
+ return SequenceClassifierOutputWithPast(
1050
+ loss=loss,
1051
+ logits=pooled_logits,
1052
+ past_key_values=transformer_outputs.past_key_values,
1053
+ hidden_states=transformer_outputs.hidden_states,
1054
+ attentions=transformer_outputs.attentions,
1055
+ )
pytorch_model-00001-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5fbf8b9f4763318d67a98722aa411f94b8429817c78411a3fdb0603fca5b5f0f
3
+ size 9975359126
pytorch_model-00002-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99f9a7748c3a8defa74b9e565a4048927a3a15e32e990d7ca70a72a7722b29f3
3
+ size 9909328186
pytorch_model-00003-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:363b4bcadaef5d9f639e41974b5e21f55b230bcd5545ce3603bdbea249237e57
3
+ size 9747818814
pytorch_model-00004-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6243cf0eec1e981975711bee96666ad0cde244a2cfbed8c5fe6d511454145c16
3
+ size 9747848138
pytorch_model-00005-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:678c75b46d0807600a2073827c244fb1fe6cf659223cb3a0439d953e0f5ae592
3
+ size 9747848198
pytorch_model-00006-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c88e2650844d8761d879e0a761159ab8432479dd1f23e4457ab56910d313bc4
3
+ size 9938689066
pytorch_model-00007-of-00007.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d9a0b74f568ef030626194d61e5d60c02a8b402d36b049f20017bb4a503c276
3
+ size 9711130536
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 68777834496
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00007-of-00007.bin",
7
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00007.bin",
8
+ "model.layers.0.ln1.weight": "pytorch_model-00001-of-00007.bin",
9
+ "model.layers.0.ln2.weight": "pytorch_model-00001-of-00007.bin",
10
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
11
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
12
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
13
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
14
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
15
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
16
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
17
+ "model.layers.1.ln1.weight": "pytorch_model-00001-of-00007.bin",
18
+ "model.layers.1.ln2.weight": "pytorch_model-00001-of-00007.bin",
19
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
20
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
21
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
22
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
23
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
24
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
25
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
26
+ "model.layers.10.ln1.weight": "pytorch_model-00002-of-00007.bin",
27
+ "model.layers.10.ln2.weight": "pytorch_model-00002-of-00007.bin",
28
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
29
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
30
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
31
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
32
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
33
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
34
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
35
+ "model.layers.11.ln1.weight": "pytorch_model-00002-of-00007.bin",
36
+ "model.layers.11.ln2.weight": "pytorch_model-00002-of-00007.bin",
37
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
38
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
39
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
40
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
41
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
42
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
43
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
44
+ "model.layers.12.ln1.weight": "pytorch_model-00002-of-00007.bin",
45
+ "model.layers.12.ln2.weight": "pytorch_model-00002-of-00007.bin",
46
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
47
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
48
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
49
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
50
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
51
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
52
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
53
+ "model.layers.13.ln1.weight": "pytorch_model-00002-of-00007.bin",
54
+ "model.layers.13.ln2.weight": "pytorch_model-00002-of-00007.bin",
55
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
56
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
57
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
58
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
59
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
60
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
61
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
62
+ "model.layers.14.ln1.weight": "pytorch_model-00002-of-00007.bin",
63
+ "model.layers.14.ln2.weight": "pytorch_model-00002-of-00007.bin",
64
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
65
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
66
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
67
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
68
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
69
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
70
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
71
+ "model.layers.15.ln1.weight": "pytorch_model-00002-of-00007.bin",
72
+ "model.layers.15.ln2.weight": "pytorch_model-00002-of-00007.bin",
73
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
74
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
75
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
76
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
77
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
78
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
79
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
80
+ "model.layers.16.ln1.weight": "pytorch_model-00002-of-00007.bin",
81
+ "model.layers.16.ln2.weight": "pytorch_model-00002-of-00007.bin",
82
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
83
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
84
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
85
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
86
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
87
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
88
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
89
+ "model.layers.17.ln1.weight": "pytorch_model-00003-of-00007.bin",
90
+ "model.layers.17.ln2.weight": "pytorch_model-00003-of-00007.bin",
91
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
92
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
93
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
94
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
95
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
96
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
97
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
98
+ "model.layers.18.ln1.weight": "pytorch_model-00003-of-00007.bin",
99
+ "model.layers.18.ln2.weight": "pytorch_model-00003-of-00007.bin",
100
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
101
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
102
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
103
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
104
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
105
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
106
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
107
+ "model.layers.19.ln1.weight": "pytorch_model-00003-of-00007.bin",
108
+ "model.layers.19.ln2.weight": "pytorch_model-00003-of-00007.bin",
109
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
110
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
111
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
112
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
113
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
114
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
115
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
116
+ "model.layers.2.ln1.weight": "pytorch_model-00001-of-00007.bin",
117
+ "model.layers.2.ln2.weight": "pytorch_model-00001-of-00007.bin",
118
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
119
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
120
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
121
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
122
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
123
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
124
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
125
+ "model.layers.20.ln1.weight": "pytorch_model-00003-of-00007.bin",
126
+ "model.layers.20.ln2.weight": "pytorch_model-00003-of-00007.bin",
127
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
128
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
129
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
130
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
131
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
132
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
133
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
134
+ "model.layers.21.ln1.weight": "pytorch_model-00003-of-00007.bin",
135
+ "model.layers.21.ln2.weight": "pytorch_model-00003-of-00007.bin",
136
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
137
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
138
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
139
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
140
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
141
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
142
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
143
+ "model.layers.22.ln1.weight": "pytorch_model-00003-of-00007.bin",
144
+ "model.layers.22.ln2.weight": "pytorch_model-00003-of-00007.bin",
145
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
146
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
147
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
148
+ "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
149
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
150
+ "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
151
+ "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
152
+ "model.layers.23.ln1.weight": "pytorch_model-00003-of-00007.bin",
153
+ "model.layers.23.ln2.weight": "pytorch_model-00003-of-00007.bin",
154
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
155
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
156
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
157
+ "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
158
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
159
+ "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
160
+ "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
161
+ "model.layers.24.ln1.weight": "pytorch_model-00003-of-00007.bin",
162
+ "model.layers.24.ln2.weight": "pytorch_model-00003-of-00007.bin",
163
+ "model.layers.24.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
164
+ "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
165
+ "model.layers.24.mlp.up_proj.weight": "pytorch_model-00003-of-00007.bin",
166
+ "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
167
+ "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
168
+ "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
169
+ "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
170
+ "model.layers.25.ln1.weight": "pytorch_model-00004-of-00007.bin",
171
+ "model.layers.25.ln2.weight": "pytorch_model-00004-of-00007.bin",
172
+ "model.layers.25.mlp.down_proj.weight": "pytorch_model-00003-of-00007.bin",
173
+ "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00003-of-00007.bin",
174
+ "model.layers.25.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
175
+ "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00003-of-00007.bin",
176
+ "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00003-of-00007.bin",
177
+ "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00003-of-00007.bin",
178
+ "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00003-of-00007.bin",
179
+ "model.layers.26.ln1.weight": "pytorch_model-00004-of-00007.bin",
180
+ "model.layers.26.ln2.weight": "pytorch_model-00004-of-00007.bin",
181
+ "model.layers.26.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
182
+ "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
183
+ "model.layers.26.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
184
+ "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
185
+ "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
186
+ "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
187
+ "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
188
+ "model.layers.27.ln1.weight": "pytorch_model-00004-of-00007.bin",
189
+ "model.layers.27.ln2.weight": "pytorch_model-00004-of-00007.bin",
190
+ "model.layers.27.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
191
+ "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
192
+ "model.layers.27.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
193
+ "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
194
+ "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
195
+ "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
196
+ "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
197
+ "model.layers.28.ln1.weight": "pytorch_model-00004-of-00007.bin",
198
+ "model.layers.28.ln2.weight": "pytorch_model-00004-of-00007.bin",
199
+ "model.layers.28.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
200
+ "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
201
+ "model.layers.28.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
202
+ "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
203
+ "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
204
+ "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
205
+ "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
206
+ "model.layers.29.ln1.weight": "pytorch_model-00004-of-00007.bin",
207
+ "model.layers.29.ln2.weight": "pytorch_model-00004-of-00007.bin",
208
+ "model.layers.29.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
209
+ "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
210
+ "model.layers.29.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
211
+ "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
212
+ "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
213
+ "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
214
+ "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
215
+ "model.layers.3.ln1.weight": "pytorch_model-00001-of-00007.bin",
216
+ "model.layers.3.ln2.weight": "pytorch_model-00001-of-00007.bin",
217
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
218
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
219
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
220
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
221
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
222
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
223
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
224
+ "model.layers.30.ln1.weight": "pytorch_model-00004-of-00007.bin",
225
+ "model.layers.30.ln2.weight": "pytorch_model-00004-of-00007.bin",
226
+ "model.layers.30.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
227
+ "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
228
+ "model.layers.30.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
229
+ "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
230
+ "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
231
+ "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
232
+ "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
233
+ "model.layers.31.ln1.weight": "pytorch_model-00004-of-00007.bin",
234
+ "model.layers.31.ln2.weight": "pytorch_model-00004-of-00007.bin",
235
+ "model.layers.31.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
236
+ "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
237
+ "model.layers.31.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
238
+ "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
239
+ "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
240
+ "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
241
+ "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
242
+ "model.layers.32.ln1.weight": "pytorch_model-00004-of-00007.bin",
243
+ "model.layers.32.ln2.weight": "pytorch_model-00004-of-00007.bin",
244
+ "model.layers.32.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
245
+ "model.layers.32.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
246
+ "model.layers.32.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
247
+ "model.layers.32.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
248
+ "model.layers.32.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
249
+ "model.layers.32.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
250
+ "model.layers.32.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
251
+ "model.layers.33.ln1.weight": "pytorch_model-00004-of-00007.bin",
252
+ "model.layers.33.ln2.weight": "pytorch_model-00004-of-00007.bin",
253
+ "model.layers.33.mlp.down_proj.weight": "pytorch_model-00004-of-00007.bin",
254
+ "model.layers.33.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
255
+ "model.layers.33.mlp.up_proj.weight": "pytorch_model-00004-of-00007.bin",
256
+ "model.layers.33.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
257
+ "model.layers.33.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
258
+ "model.layers.33.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
259
+ "model.layers.33.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
260
+ "model.layers.34.ln1.weight": "pytorch_model-00005-of-00007.bin",
261
+ "model.layers.34.ln2.weight": "pytorch_model-00005-of-00007.bin",
262
+ "model.layers.34.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
263
+ "model.layers.34.mlp.gate_proj.weight": "pytorch_model-00004-of-00007.bin",
264
+ "model.layers.34.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
265
+ "model.layers.34.self_attn.k_proj.weight": "pytorch_model-00004-of-00007.bin",
266
+ "model.layers.34.self_attn.o_proj.weight": "pytorch_model-00004-of-00007.bin",
267
+ "model.layers.34.self_attn.q_proj.weight": "pytorch_model-00004-of-00007.bin",
268
+ "model.layers.34.self_attn.v_proj.weight": "pytorch_model-00004-of-00007.bin",
269
+ "model.layers.35.ln1.weight": "pytorch_model-00005-of-00007.bin",
270
+ "model.layers.35.ln2.weight": "pytorch_model-00005-of-00007.bin",
271
+ "model.layers.35.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
272
+ "model.layers.35.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
273
+ "model.layers.35.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
274
+ "model.layers.35.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
275
+ "model.layers.35.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
276
+ "model.layers.35.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
277
+ "model.layers.35.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
278
+ "model.layers.36.ln1.weight": "pytorch_model-00005-of-00007.bin",
279
+ "model.layers.36.ln2.weight": "pytorch_model-00005-of-00007.bin",
280
+ "model.layers.36.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
281
+ "model.layers.36.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
282
+ "model.layers.36.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
283
+ "model.layers.36.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
284
+ "model.layers.36.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
285
+ "model.layers.36.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
286
+ "model.layers.36.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
287
+ "model.layers.37.ln1.weight": "pytorch_model-00005-of-00007.bin",
288
+ "model.layers.37.ln2.weight": "pytorch_model-00005-of-00007.bin",
289
+ "model.layers.37.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
290
+ "model.layers.37.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
291
+ "model.layers.37.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
292
+ "model.layers.37.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
293
+ "model.layers.37.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
294
+ "model.layers.37.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
295
+ "model.layers.37.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
296
+ "model.layers.38.ln1.weight": "pytorch_model-00005-of-00007.bin",
297
+ "model.layers.38.ln2.weight": "pytorch_model-00005-of-00007.bin",
298
+ "model.layers.38.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
299
+ "model.layers.38.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
300
+ "model.layers.38.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
301
+ "model.layers.38.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
302
+ "model.layers.38.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
303
+ "model.layers.38.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
304
+ "model.layers.38.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
305
+ "model.layers.39.ln1.weight": "pytorch_model-00005-of-00007.bin",
306
+ "model.layers.39.ln2.weight": "pytorch_model-00005-of-00007.bin",
307
+ "model.layers.39.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
308
+ "model.layers.39.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
309
+ "model.layers.39.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
310
+ "model.layers.39.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
311
+ "model.layers.39.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
312
+ "model.layers.39.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
313
+ "model.layers.39.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
314
+ "model.layers.4.ln1.weight": "pytorch_model-00001-of-00007.bin",
315
+ "model.layers.4.ln2.weight": "pytorch_model-00001-of-00007.bin",
316
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
317
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
318
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
319
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
320
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
321
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
322
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
323
+ "model.layers.40.ln1.weight": "pytorch_model-00005-of-00007.bin",
324
+ "model.layers.40.ln2.weight": "pytorch_model-00005-of-00007.bin",
325
+ "model.layers.40.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
326
+ "model.layers.40.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
327
+ "model.layers.40.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
328
+ "model.layers.40.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
329
+ "model.layers.40.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
330
+ "model.layers.40.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
331
+ "model.layers.40.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
332
+ "model.layers.41.ln1.weight": "pytorch_model-00005-of-00007.bin",
333
+ "model.layers.41.ln2.weight": "pytorch_model-00005-of-00007.bin",
334
+ "model.layers.41.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
335
+ "model.layers.41.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
336
+ "model.layers.41.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
337
+ "model.layers.41.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
338
+ "model.layers.41.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
339
+ "model.layers.41.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
340
+ "model.layers.41.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
341
+ "model.layers.42.ln1.weight": "pytorch_model-00005-of-00007.bin",
342
+ "model.layers.42.ln2.weight": "pytorch_model-00005-of-00007.bin",
343
+ "model.layers.42.mlp.down_proj.weight": "pytorch_model-00005-of-00007.bin",
344
+ "model.layers.42.mlp.gate_proj.weight": "pytorch_model-00005-of-00007.bin",
345
+ "model.layers.42.mlp.up_proj.weight": "pytorch_model-00005-of-00007.bin",
346
+ "model.layers.42.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
347
+ "model.layers.42.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
348
+ "model.layers.42.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
349
+ "model.layers.42.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
350
+ "model.layers.43.ln1.weight": "pytorch_model-00006-of-00007.bin",
351
+ "model.layers.43.ln2.weight": "pytorch_model-00006-of-00007.bin",
352
+ "model.layers.43.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
353
+ "model.layers.43.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
354
+ "model.layers.43.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
355
+ "model.layers.43.self_attn.k_proj.weight": "pytorch_model-00005-of-00007.bin",
356
+ "model.layers.43.self_attn.o_proj.weight": "pytorch_model-00005-of-00007.bin",
357
+ "model.layers.43.self_attn.q_proj.weight": "pytorch_model-00005-of-00007.bin",
358
+ "model.layers.43.self_attn.v_proj.weight": "pytorch_model-00005-of-00007.bin",
359
+ "model.layers.44.ln1.weight": "pytorch_model-00006-of-00007.bin",
360
+ "model.layers.44.ln2.weight": "pytorch_model-00006-of-00007.bin",
361
+ "model.layers.44.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
362
+ "model.layers.44.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
363
+ "model.layers.44.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
364
+ "model.layers.44.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
365
+ "model.layers.44.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
366
+ "model.layers.44.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
367
+ "model.layers.44.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
368
+ "model.layers.45.ln1.weight": "pytorch_model-00006-of-00007.bin",
369
+ "model.layers.45.ln2.weight": "pytorch_model-00006-of-00007.bin",
370
+ "model.layers.45.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
371
+ "model.layers.45.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
372
+ "model.layers.45.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
373
+ "model.layers.45.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
374
+ "model.layers.45.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
375
+ "model.layers.45.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
376
+ "model.layers.45.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
377
+ "model.layers.46.ln1.weight": "pytorch_model-00006-of-00007.bin",
378
+ "model.layers.46.ln2.weight": "pytorch_model-00006-of-00007.bin",
379
+ "model.layers.46.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
380
+ "model.layers.46.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
381
+ "model.layers.46.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
382
+ "model.layers.46.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
383
+ "model.layers.46.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
384
+ "model.layers.46.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
385
+ "model.layers.46.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
386
+ "model.layers.47.ln1.weight": "pytorch_model-00006-of-00007.bin",
387
+ "model.layers.47.ln2.weight": "pytorch_model-00006-of-00007.bin",
388
+ "model.layers.47.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
389
+ "model.layers.47.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
390
+ "model.layers.47.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
391
+ "model.layers.47.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
392
+ "model.layers.47.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
393
+ "model.layers.47.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
394
+ "model.layers.47.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
395
+ "model.layers.48.ln1.weight": "pytorch_model-00006-of-00007.bin",
396
+ "model.layers.48.ln2.weight": "pytorch_model-00006-of-00007.bin",
397
+ "model.layers.48.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
398
+ "model.layers.48.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
399
+ "model.layers.48.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
400
+ "model.layers.48.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
401
+ "model.layers.48.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
402
+ "model.layers.48.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
403
+ "model.layers.48.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
404
+ "model.layers.49.ln1.weight": "pytorch_model-00006-of-00007.bin",
405
+ "model.layers.49.ln2.weight": "pytorch_model-00006-of-00007.bin",
406
+ "model.layers.49.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
407
+ "model.layers.49.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
408
+ "model.layers.49.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
409
+ "model.layers.49.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
410
+ "model.layers.49.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
411
+ "model.layers.49.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
412
+ "model.layers.49.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
413
+ "model.layers.5.ln1.weight": "pytorch_model-00001-of-00007.bin",
414
+ "model.layers.5.ln2.weight": "pytorch_model-00001-of-00007.bin",
415
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
416
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
417
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
418
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
419
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
420
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
421
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
422
+ "model.layers.50.ln1.weight": "pytorch_model-00006-of-00007.bin",
423
+ "model.layers.50.ln2.weight": "pytorch_model-00006-of-00007.bin",
424
+ "model.layers.50.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
425
+ "model.layers.50.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
426
+ "model.layers.50.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
427
+ "model.layers.50.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
428
+ "model.layers.50.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
429
+ "model.layers.50.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
430
+ "model.layers.50.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
431
+ "model.layers.51.ln1.weight": "pytorch_model-00006-of-00007.bin",
432
+ "model.layers.51.ln2.weight": "pytorch_model-00006-of-00007.bin",
433
+ "model.layers.51.mlp.down_proj.weight": "pytorch_model-00006-of-00007.bin",
434
+ "model.layers.51.mlp.gate_proj.weight": "pytorch_model-00006-of-00007.bin",
435
+ "model.layers.51.mlp.up_proj.weight": "pytorch_model-00006-of-00007.bin",
436
+ "model.layers.51.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
437
+ "model.layers.51.self_attn.o_proj.weight": "pytorch_model-00006-of-00007.bin",
438
+ "model.layers.51.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
439
+ "model.layers.51.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
440
+ "model.layers.52.ln1.weight": "pytorch_model-00007-of-00007.bin",
441
+ "model.layers.52.ln2.weight": "pytorch_model-00007-of-00007.bin",
442
+ "model.layers.52.mlp.down_proj.weight": "pytorch_model-00007-of-00007.bin",
443
+ "model.layers.52.mlp.gate_proj.weight": "pytorch_model-00007-of-00007.bin",
444
+ "model.layers.52.mlp.up_proj.weight": "pytorch_model-00007-of-00007.bin",
445
+ "model.layers.52.self_attn.k_proj.weight": "pytorch_model-00006-of-00007.bin",
446
+ "model.layers.52.self_attn.o_proj.weight": "pytorch_model-00007-of-00007.bin",
447
+ "model.layers.52.self_attn.q_proj.weight": "pytorch_model-00006-of-00007.bin",
448
+ "model.layers.52.self_attn.v_proj.weight": "pytorch_model-00006-of-00007.bin",
449
+ "model.layers.53.ln1.weight": "pytorch_model-00007-of-00007.bin",
450
+ "model.layers.53.ln2.weight": "pytorch_model-00007-of-00007.bin",
451
+ "model.layers.53.mlp.down_proj.weight": "pytorch_model-00007-of-00007.bin",
452
+ "model.layers.53.mlp.gate_proj.weight": "pytorch_model-00007-of-00007.bin",
453
+ "model.layers.53.mlp.up_proj.weight": "pytorch_model-00007-of-00007.bin",
454
+ "model.layers.53.self_attn.k_proj.weight": "pytorch_model-00007-of-00007.bin",
455
+ "model.layers.53.self_attn.o_proj.weight": "pytorch_model-00007-of-00007.bin",
456
+ "model.layers.53.self_attn.q_proj.weight": "pytorch_model-00007-of-00007.bin",
457
+ "model.layers.53.self_attn.v_proj.weight": "pytorch_model-00007-of-00007.bin",
458
+ "model.layers.54.ln1.weight": "pytorch_model-00007-of-00007.bin",
459
+ "model.layers.54.ln2.weight": "pytorch_model-00007-of-00007.bin",
460
+ "model.layers.54.mlp.down_proj.weight": "pytorch_model-00007-of-00007.bin",
461
+ "model.layers.54.mlp.gate_proj.weight": "pytorch_model-00007-of-00007.bin",
462
+ "model.layers.54.mlp.up_proj.weight": "pytorch_model-00007-of-00007.bin",
463
+ "model.layers.54.self_attn.k_proj.weight": "pytorch_model-00007-of-00007.bin",
464
+ "model.layers.54.self_attn.o_proj.weight": "pytorch_model-00007-of-00007.bin",
465
+ "model.layers.54.self_attn.q_proj.weight": "pytorch_model-00007-of-00007.bin",
466
+ "model.layers.54.self_attn.v_proj.weight": "pytorch_model-00007-of-00007.bin",
467
+ "model.layers.55.ln1.weight": "pytorch_model-00007-of-00007.bin",
468
+ "model.layers.55.ln2.weight": "pytorch_model-00007-of-00007.bin",
469
+ "model.layers.55.mlp.down_proj.weight": "pytorch_model-00007-of-00007.bin",
470
+ "model.layers.55.mlp.gate_proj.weight": "pytorch_model-00007-of-00007.bin",
471
+ "model.layers.55.mlp.up_proj.weight": "pytorch_model-00007-of-00007.bin",
472
+ "model.layers.55.self_attn.k_proj.weight": "pytorch_model-00007-of-00007.bin",
473
+ "model.layers.55.self_attn.o_proj.weight": "pytorch_model-00007-of-00007.bin",
474
+ "model.layers.55.self_attn.q_proj.weight": "pytorch_model-00007-of-00007.bin",
475
+ "model.layers.55.self_attn.v_proj.weight": "pytorch_model-00007-of-00007.bin",
476
+ "model.layers.56.ln1.weight": "pytorch_model-00007-of-00007.bin",
477
+ "model.layers.56.ln2.weight": "pytorch_model-00007-of-00007.bin",
478
+ "model.layers.56.mlp.down_proj.weight": "pytorch_model-00007-of-00007.bin",
479
+ "model.layers.56.mlp.gate_proj.weight": "pytorch_model-00007-of-00007.bin",
480
+ "model.layers.56.mlp.up_proj.weight": "pytorch_model-00007-of-00007.bin",
481
+ "model.layers.56.self_attn.k_proj.weight": "pytorch_model-00007-of-00007.bin",
482
+ "model.layers.56.self_attn.o_proj.weight": "pytorch_model-00007-of-00007.bin",
483
+ "model.layers.56.self_attn.q_proj.weight": "pytorch_model-00007-of-00007.bin",
484
+ "model.layers.56.self_attn.v_proj.weight": "pytorch_model-00007-of-00007.bin",
485
+ "model.layers.57.ln1.weight": "pytorch_model-00007-of-00007.bin",
486
+ "model.layers.57.ln2.weight": "pytorch_model-00007-of-00007.bin",
487
+ "model.layers.57.mlp.down_proj.weight": "pytorch_model-00007-of-00007.bin",
488
+ "model.layers.57.mlp.gate_proj.weight": "pytorch_model-00007-of-00007.bin",
489
+ "model.layers.57.mlp.up_proj.weight": "pytorch_model-00007-of-00007.bin",
490
+ "model.layers.57.self_attn.k_proj.weight": "pytorch_model-00007-of-00007.bin",
491
+ "model.layers.57.self_attn.o_proj.weight": "pytorch_model-00007-of-00007.bin",
492
+ "model.layers.57.self_attn.q_proj.weight": "pytorch_model-00007-of-00007.bin",
493
+ "model.layers.57.self_attn.v_proj.weight": "pytorch_model-00007-of-00007.bin",
494
+ "model.layers.58.ln1.weight": "pytorch_model-00007-of-00007.bin",
495
+ "model.layers.58.ln2.weight": "pytorch_model-00007-of-00007.bin",
496
+ "model.layers.58.mlp.down_proj.weight": "pytorch_model-00007-of-00007.bin",
497
+ "model.layers.58.mlp.gate_proj.weight": "pytorch_model-00007-of-00007.bin",
498
+ "model.layers.58.mlp.up_proj.weight": "pytorch_model-00007-of-00007.bin",
499
+ "model.layers.58.self_attn.k_proj.weight": "pytorch_model-00007-of-00007.bin",
500
+ "model.layers.58.self_attn.o_proj.weight": "pytorch_model-00007-of-00007.bin",
501
+ "model.layers.58.self_attn.q_proj.weight": "pytorch_model-00007-of-00007.bin",
502
+ "model.layers.58.self_attn.v_proj.weight": "pytorch_model-00007-of-00007.bin",
503
+ "model.layers.59.ln1.weight": "pytorch_model-00007-of-00007.bin",
504
+ "model.layers.59.ln2.weight": "pytorch_model-00007-of-00007.bin",
505
+ "model.layers.59.mlp.down_proj.weight": "pytorch_model-00007-of-00007.bin",
506
+ "model.layers.59.mlp.gate_proj.weight": "pytorch_model-00007-of-00007.bin",
507
+ "model.layers.59.mlp.up_proj.weight": "pytorch_model-00007-of-00007.bin",
508
+ "model.layers.59.self_attn.k_proj.weight": "pytorch_model-00007-of-00007.bin",
509
+ "model.layers.59.self_attn.o_proj.weight": "pytorch_model-00007-of-00007.bin",
510
+ "model.layers.59.self_attn.q_proj.weight": "pytorch_model-00007-of-00007.bin",
511
+ "model.layers.59.self_attn.v_proj.weight": "pytorch_model-00007-of-00007.bin",
512
+ "model.layers.6.ln1.weight": "pytorch_model-00001-of-00007.bin",
513
+ "model.layers.6.ln2.weight": "pytorch_model-00001-of-00007.bin",
514
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
515
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
516
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
517
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
518
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
519
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
520
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
521
+ "model.layers.7.ln1.weight": "pytorch_model-00001-of-00007.bin",
522
+ "model.layers.7.ln2.weight": "pytorch_model-00001-of-00007.bin",
523
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00007.bin",
524
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00007.bin",
525
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00007.bin",
526
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
527
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00007.bin",
528
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
529
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
530
+ "model.layers.8.ln1.weight": "pytorch_model-00002-of-00007.bin",
531
+ "model.layers.8.ln2.weight": "pytorch_model-00002-of-00007.bin",
532
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
533
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
534
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
535
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00007.bin",
536
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
537
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00007.bin",
538
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00007.bin",
539
+ "model.layers.9.ln1.weight": "pytorch_model-00002-of-00007.bin",
540
+ "model.layers.9.ln2.weight": "pytorch_model-00002-of-00007.bin",
541
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00002-of-00007.bin",
542
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00002-of-00007.bin",
543
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00002-of-00007.bin",
544
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00002-of-00007.bin",
545
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00002-of-00007.bin",
546
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00002-of-00007.bin",
547
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00002-of-00007.bin",
548
+ "model.norm.weight": "pytorch_model-00007-of-00007.bin"
549
+ }
550
+ }
tokenization_yi.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from shutil import copyfile
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ import sentencepiece as spm
6
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
7
+ from transformers.utils import logging
8
+
9
+ logger = logging.get_logger(__name__)
10
+
11
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
12
+
13
+ PRETRAINED_VOCAB_FILES_MAP = {
14
+ "vocab_file": {},
15
+ "tokenizer_file": {},
16
+ }
17
+ PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
18
+
19
+
20
+ class YiTokenizer(PreTrainedTokenizer):
21
+ """
22
+ Construct a Yi tokenizer. Based on byte-level Byte-Pair-Encoding.
23
+
24
+ Args:
25
+ vocab_file (`str`):
26
+ Path to the vocabulary file.
27
+ """
28
+
29
+ vocab_files_names = VOCAB_FILES_NAMES
30
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
31
+ max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
32
+ model_input_names = ["input_ids", "attention_mask"]
33
+
34
+ def __init__(
35
+ self,
36
+ vocab_file,
37
+ unk_token="<unk>",
38
+ bos_token="<|startoftext|>",
39
+ eos_token="<|endoftext|>",
40
+ pad_token="<unk>",
41
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
42
+ add_bos_token=True,
43
+ add_eos_token=False,
44
+ clean_up_tokenization_spaces=False,
45
+ **kwargs,
46
+ ):
47
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
48
+ bos_token = (
49
+ AddedToken(bos_token, lstrip=False, rstrip=False)
50
+ if isinstance(bos_token, str)
51
+ else bos_token
52
+ )
53
+ eos_token = (
54
+ AddedToken(eos_token, lstrip=False, rstrip=False)
55
+ if isinstance(eos_token, str)
56
+ else eos_token
57
+ )
58
+ unk_token = (
59
+ AddedToken(unk_token, lstrip=False, rstrip=False)
60
+ if isinstance(unk_token, str)
61
+ else unk_token
62
+ )
63
+ pad_token = (
64
+ AddedToken(pad_token, lstrip=False, rstrip=False)
65
+ if isinstance(pad_token, str)
66
+ else pad_token
67
+ )
68
+ self.vocab_file = vocab_file
69
+ self.add_bos_token = add_bos_token
70
+ self.add_eos_token = add_eos_token
71
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
72
+ self.sp_model.Load(vocab_file)
73
+ super().__init__(
74
+ bos_token=bos_token,
75
+ eos_token=eos_token,
76
+ unk_token=unk_token,
77
+ pad_token=pad_token,
78
+ add_bos_token=add_bos_token,
79
+ add_eos_token=add_eos_token,
80
+ sp_model_kwargs=self.sp_model_kwargs,
81
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
82
+ **kwargs,
83
+ )
84
+
85
+ def __getstate__(self):
86
+ state = self.__dict__.copy()
87
+ state["sp_model"] = None
88
+ return state
89
+
90
+ def __setstate__(self, d):
91
+ self.__dict__ = d
92
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
93
+ self.sp_model.Load(self.vocab_file)
94
+
95
+ @property
96
+ def vocab_size(self):
97
+ """Returns vocab size"""
98
+ return self.sp_model.get_piece_size()
99
+
100
+ def get_vocab(self):
101
+ """Returns vocab as a dict"""
102
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
103
+ vocab.update(self.added_tokens_encoder)
104
+ return vocab
105
+
106
+ def _tokenize(self, text):
107
+ """Returns a tokenized string."""
108
+ return self.sp_model.encode(text, out_type=str)
109
+
110
+ def _convert_token_to_id(self, token):
111
+ """Converts a token (str) in an id using the vocab."""
112
+ return self.sp_model.piece_to_id(token)
113
+
114
+ def _convert_id_to_token(self, index):
115
+ """Converts an index (integer) in a token (str) using the vocab."""
116
+ token = self.sp_model.IdToPiece(index)
117
+ return token
118
+
119
+ def convert_tokens_to_string(self, tokens):
120
+ """Converts a sequence of tokens (string) in a single string."""
121
+ current_sub_tokens = []
122
+ out_string = ""
123
+ prev_is_special = False
124
+ for i, token in enumerate(tokens):
125
+ # make sure that special tokens are not decoded using sentencepiece model
126
+ if token in self.all_special_tokens:
127
+ if not prev_is_special and i != 0:
128
+ out_string += " "
129
+ out_string += self.sp_model.decode(current_sub_tokens) + token
130
+ prev_is_special = True
131
+ current_sub_tokens = []
132
+ else:
133
+ current_sub_tokens.append(token)
134
+ prev_is_special = False
135
+ out_string += self.sp_model.decode(current_sub_tokens)
136
+ return out_string
137
+
138
+ def save_vocabulary(
139
+ self, save_directory, filename_prefix: Optional[str] = None
140
+ ) -> Tuple[str]:
141
+ """
142
+ Save the vocabulary and special tokens file to a directory.
143
+
144
+ Args:
145
+ save_directory (`str`):
146
+ The directory in which to save the vocabulary.
147
+
148
+ Returns:
149
+ `Tuple(str)`: Paths to the files saved.
150
+ """
151
+ if not os.path.isdir(save_directory):
152
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
153
+ return
154
+ out_vocab_file = os.path.join(
155
+ save_directory,
156
+ (filename_prefix + "-" if filename_prefix else "")
157
+ + VOCAB_FILES_NAMES["vocab_file"],
158
+ )
159
+
160
+ if os.path.abspath(self.vocab_file) != os.path.abspath(
161
+ out_vocab_file
162
+ ) and os.path.isfile(self.vocab_file):
163
+ copyfile(self.vocab_file, out_vocab_file)
164
+ elif not os.path.isfile(self.vocab_file):
165
+ with open(out_vocab_file, "wb") as fi:
166
+ content_spiece_model = self.sp_model.serialized_model_proto()
167
+ fi.write(content_spiece_model)
168
+
169
+ return (out_vocab_file,)
170
+
171
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
172
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
173
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
174
+
175
+ output = bos_token_id + token_ids_0 + eos_token_id
176
+
177
+ if token_ids_1 is not None:
178
+ output = output + bos_token_id + token_ids_1 + eos_token_id
179
+
180
+ return output
181
+
182
+ def get_special_tokens_mask(
183
+ self,
184
+ token_ids_0: List[int],
185
+ token_ids_1: Optional[List[int]] = None,
186
+ already_has_special_tokens: bool = False,
187
+ ) -> List[int]:
188
+ """
189
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
190
+ special tokens using the tokenizer `prepare_for_model` method.
191
+
192
+ Args:
193
+ token_ids_0 (`List[int]`):
194
+ List of IDs.
195
+ token_ids_1 (`List[int]`, *optional*):
196
+ Optional second list of IDs for sequence pairs.
197
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
198
+ Whether or not the token list is already formatted with special tokens for the model.
199
+
200
+ Returns:
201
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
202
+ """
203
+ if already_has_special_tokens:
204
+ return super().get_special_tokens_mask(
205
+ token_ids_0=token_ids_0,
206
+ token_ids_1=token_ids_1,
207
+ already_has_special_tokens=True,
208
+ )
209
+
210
+ bos_token_id = [1] if self.add_bos_token else []
211
+ eos_token_id = [1] if self.add_eos_token else []
212
+
213
+ if token_ids_1 is None:
214
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
215
+ return (
216
+ bos_token_id
217
+ + ([0] * len(token_ids_0))
218
+ + eos_token_id
219
+ + bos_token_id
220
+ + ([0] * len(token_ids_1))
221
+ + eos_token_id
222
+ )
223
+
224
+ def create_token_type_ids_from_sequences(
225
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
226
+ ) -> List[int]:
227
+ """
228
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
229
+ sequence pair mask has the following format:
230
+
231
+ ```
232
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
233
+ | first sequence | second sequence |
234
+ ```
235
+
236
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
237
+
238
+ Args:
239
+ token_ids_0 (`List[int]`):
240
+ List of ids.
241
+ token_ids_1 (`List[int]`, *optional*):
242
+ Optional second list of IDs for sequence pairs.
243
+
244
+ Returns:
245
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
246
+ """
247
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
248
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
249
+
250
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
251
+
252
+ if token_ids_1 is not None:
253
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
254
+
255
+ return output
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:386c49cf943d71aa110361135338c50e38beeff0a66593480421f37b319e1a39
3
+ size 1033105
tokenizer_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": ["tokenization_yi.YiTokenizer", null]
4
+ },
5
+ "add_bos_token": false,
6
+ "add_eos_token": false,
7
+ "model_max_length": 4096,
8
+ "tokenizer_class": "YiTokenizer"
9
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e2279e36e673c0a04fcd4bca602006295cf4895fc79b7a02bee217ea28b0550
3
+ size 6776
zero_to_fp32.py ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage == 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dicts.append(torch.load(f, map_location=device))
147
+
148
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
149
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
150
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
151
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
152
+
153
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
154
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
155
+ # use the max of the partition_count to get the dp world_size.
156
+
157
+ if type(world_size) is list:
158
+ world_size = max(world_size)
159
+
160
+ if world_size != total_files:
161
+ raise ValueError(
162
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
163
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
164
+ )
165
+
166
+ # the groups are named differently in each stage
167
+ if zero_stage == 2:
168
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
169
+ elif zero_stage == 3:
170
+ fp32_groups_key = FP32_FLAT_GROUPS
171
+ else:
172
+ raise ValueError(f"unknown zero stage {zero_stage}")
173
+
174
+ if zero_stage == 2:
175
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
176
+ elif zero_stage == 3:
177
+ # if there is more than one param group, there will be multiple flattened tensors - one
178
+ # flattened tensor per group - for simplicity merge them into a single tensor
179
+ #
180
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
181
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
182
+
183
+ fp32_flat_groups = [
184
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
185
+ ]
186
+
187
+ return zero_stage, world_size, fp32_flat_groups
188
+
189
+
190
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir):
191
+ """
192
+ Returns fp32 state_dict reconstructed from ds checkpoint
193
+
194
+ Args:
195
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
196
+
197
+ """
198
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
199
+
200
+ optim_files = get_optim_files(ds_checkpoint_dir)
201
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
202
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
203
+
204
+ model_files = get_model_state_files(ds_checkpoint_dir)
205
+
206
+ zero_model_states = parse_model_states(model_files)
207
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
208
+
209
+ if zero_stage == 2:
210
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states)
211
+ elif zero_stage == 3:
212
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states)
213
+
214
+
215
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
216
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
217
+ return
218
+
219
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
220
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
221
+
222
+ if debug:
223
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
224
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
225
+
226
+ wanted_params = len(frozen_param_shapes)
227
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
228
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
229
+ print(f'Frozen params: Have {avail_numel} numels to process.')
230
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
231
+
232
+ total_params = 0
233
+ total_numel = 0
234
+ for name, shape in frozen_param_shapes.items():
235
+ total_params += 1
236
+ unpartitioned_numel = shape.numel()
237
+ total_numel += unpartitioned_numel
238
+
239
+ state_dict[name] = frozen_param_fragments[name]
240
+
241
+ if debug:
242
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
243
+
244
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
245
+
246
+
247
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
248
+ param_shapes = zero_model_states[0].param_shapes
249
+
250
+ # Reconstruction protocol:
251
+ #
252
+ # XXX: document this
253
+
254
+ if debug:
255
+ for i in range(world_size):
256
+ for j in range(len(fp32_flat_groups[0])):
257
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
258
+
259
+ # XXX: memory usage doubles here (zero2)
260
+ num_param_groups = len(fp32_flat_groups[0])
261
+ merged_single_partition_of_fp32_groups = []
262
+ for i in range(num_param_groups):
263
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
264
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
265
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
266
+ avail_numel = sum(
267
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
268
+
269
+ if debug:
270
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
271
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
272
+ # not asserting if there is a mismatch due to possible padding
273
+ print(f"Have {avail_numel} numels to process.")
274
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
275
+
276
+ # params
277
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
278
+ # out-of-core computing solution
279
+ total_numel = 0
280
+ total_params = 0
281
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
282
+ offset = 0
283
+ avail_numel = full_single_fp32_vector.numel()
284
+ for name, shape in shapes.items():
285
+
286
+ unpartitioned_numel = shape.numel()
287
+ total_numel += unpartitioned_numel
288
+ total_params += 1
289
+
290
+ if debug:
291
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
292
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
293
+ offset += unpartitioned_numel
294
+
295
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
296
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
297
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
298
+ # live optimizer object, so we are checking that the numbers are within the right range
299
+ align_to = 2 * world_size
300
+
301
+ def zero2_align(x):
302
+ return align_to * math.ceil(x / align_to)
303
+
304
+ if debug:
305
+ print(f"original offset={offset}, avail_numel={avail_numel}")
306
+
307
+ offset = zero2_align(offset)
308
+ avail_numel = zero2_align(avail_numel)
309
+
310
+ if debug:
311
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
312
+
313
+ # Sanity check
314
+ if offset != avail_numel:
315
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
316
+
317
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
318
+
319
+
320
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states):
321
+ state_dict = OrderedDict()
322
+
323
+ # buffers
324
+ buffers = zero_model_states[0].buffers
325
+ state_dict.update(buffers)
326
+ if debug:
327
+ print(f"added {len(buffers)} buffers")
328
+
329
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
330
+
331
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
332
+
333
+ # recover shared parameters
334
+ for pair in zero_model_states[0].shared_params:
335
+ if pair[1] in state_dict:
336
+ state_dict[pair[0]] = state_dict[pair[1]]
337
+
338
+ return state_dict
339
+
340
+
341
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
342
+ remainder = unpartitioned_numel % world_size
343
+ padding_numel = (world_size - remainder) if remainder else 0
344
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
345
+ return partitioned_numel, padding_numel
346
+
347
+
348
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
349
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
350
+ return
351
+
352
+ if debug:
353
+ for i in range(world_size):
354
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
355
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
356
+
357
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
358
+ wanted_params = len(frozen_param_shapes)
359
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
360
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
361
+ print(f'Frozen params: Have {avail_numel} numels to process.')
362
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
363
+
364
+ total_params = 0
365
+ total_numel = 0
366
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
367
+ total_params += 1
368
+ unpartitioned_numel = shape.numel()
369
+ total_numel += unpartitioned_numel
370
+
371
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
372
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
373
+
374
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
375
+
376
+ if debug:
377
+ print(
378
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
379
+ )
380
+
381
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
382
+
383
+
384
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
385
+ param_shapes = zero_model_states[0].param_shapes
386
+ avail_numel = fp32_flat_groups[0].numel() * world_size
387
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
388
+ # param, re-consolidating each param, while dealing with padding if any
389
+
390
+ # merge list of dicts, preserving order
391
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
392
+
393
+ if debug:
394
+ for i in range(world_size):
395
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
396
+
397
+ wanted_params = len(param_shapes)
398
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
399
+ # not asserting if there is a mismatch due to possible padding
400
+ avail_numel = fp32_flat_groups[0].numel() * world_size
401
+ print(f"Trainable params: Have {avail_numel} numels to process.")
402
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
403
+
404
+ # params
405
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
406
+ # out-of-core computing solution
407
+ offset = 0
408
+ total_numel = 0
409
+ total_params = 0
410
+ for name, shape in param_shapes.items():
411
+
412
+ unpartitioned_numel = shape.numel()
413
+ total_numel += unpartitioned_numel
414
+ total_params += 1
415
+
416
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
417
+
418
+ if debug:
419
+ print(
420
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
421
+ )
422
+
423
+ # XXX: memory usage doubles here
424
+ state_dict[name] = torch.cat(
425
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
426
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
427
+ offset += partitioned_numel
428
+
429
+ offset *= world_size
430
+
431
+ # Sanity check
432
+ if offset != avail_numel:
433
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
434
+
435
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
436
+
437
+
438
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states):
439
+ state_dict = OrderedDict()
440
+
441
+ # buffers
442
+ buffers = zero_model_states[0].buffers
443
+ state_dict.update(buffers)
444
+ if debug:
445
+ print(f"added {len(buffers)} buffers")
446
+
447
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
448
+
449
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
450
+
451
+ # recover shared parameters
452
+ for pair in zero_model_states[0].shared_params:
453
+ if pair[1] in state_dict:
454
+ state_dict[pair[0]] = state_dict[pair[1]]
455
+
456
+ return state_dict
457
+
458
+
459
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None):
460
+ """
461
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
462
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
463
+ via a model hub.
464
+
465
+ Args:
466
+ - ``checkpoint_dir``: path to the desired checkpoint folder
467
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
468
+
469
+ Returns:
470
+ - pytorch ``state_dict``
471
+
472
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
473
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
474
+ the checkpoint.
475
+
476
+ A typical usage might be ::
477
+
478
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
479
+ # do the training and checkpoint saving
480
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
481
+ model = model.cpu() # move to cpu
482
+ model.load_state_dict(state_dict)
483
+ # submit to model hub or save the model to share with others
484
+
485
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
486
+ application. i.e. you will need to re-initialize the deepspeed engine, since
487
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
488
+
489
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
490
+
491
+ """
492
+ if tag is None:
493
+ latest_path = os.path.join(checkpoint_dir, 'latest')
494
+ if os.path.isfile(latest_path):
495
+ with open(latest_path, 'r') as fd:
496
+ tag = fd.read().strip()
497
+ else:
498
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
499
+
500
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
501
+
502
+ if not os.path.isdir(ds_checkpoint_dir):
503
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
504
+
505
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir)
506
+
507
+
508
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None):
509
+ """
510
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
511
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
512
+
513
+ Args:
514
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
515
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
516
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
517
+ """
518
+
519
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
520
+ print(f"Saving fp32 state dict to {output_file}")
521
+ torch.save(state_dict, output_file)
522
+
523
+
524
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
525
+ """
526
+ 1. Put the provided model to cpu
527
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
528
+ 3. Load it into the provided model
529
+
530
+ Args:
531
+ - ``model``: the model object to update
532
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
533
+ - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
534
+
535
+ Returns:
536
+ - ``model`: modified model
537
+
538
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
539
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
540
+ conveniently placed for you in the checkpoint folder.
541
+
542
+ A typical usage might be ::
543
+
544
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
545
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
546
+ # submit to model hub or save the model to share with others
547
+
548
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
549
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
550
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
551
+
552
+ """
553
+ logger.info(f"Extracting fp32 weights")
554
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
555
+
556
+ logger.info(f"Overwriting model with fp32 weights")
557
+ model = model.cpu()
558
+ model.load_state_dict(state_dict, strict=False)
559
+
560
+ return model
561
+
562
+
563
+ if __name__ == "__main__":
564
+
565
+ parser = argparse.ArgumentParser()
566
+ parser.add_argument("checkpoint_dir",
567
+ type=str,
568
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
569
+ parser.add_argument(
570
+ "output_file",
571
+ type=str,
572
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
573
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
574
+ args = parser.parse_args()
575
+
576
+ debug = args.debug
577
+
578
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file)