katuni4ka commited on
Commit
bc0dc25
1 Parent(s): 4e3615b

Upload 7 files

Browse files
config.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/home/ea/work/snowflake",
3
+ "architectures": [
4
+ "ArcticForCausalLM"
5
+ ],
6
+ "attention_dropout": 0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_arctic.ArcticConfig",
9
+ "AutoModel": "modeling_arctic.ArcticModel",
10
+ "AutoModelForCausalLM": "modeling_arctic.ArcticForCausalLM",
11
+ "AutoModelForSequenceClassification": "modeling_arctic.ArcticForSequenceClassification"
12
+ },
13
+ "bos_token_id": 1,
14
+ "enable_expert_tensor_parallelism": false,
15
+ "enc_index": [
16
+ 0,
17
+ 1,
18
+ 2,
19
+ 3
20
+ ],
21
+ "eos_token_id": 2,
22
+ "hidden_act": "silu",
23
+ "hidden_size": 32,
24
+ "initializer_range": 0.02,
25
+ "intermediate_size": 16,
26
+ "max_position_embeddings": 128,
27
+ "max_sequence_length": 128,
28
+ "model_type": "arctic",
29
+ "moe_eval_capacity_factor": 1,
30
+ "moe_layer_frequency": 1,
31
+ "moe_min_capacity": 0,
32
+ "moe_token_dropping": true,
33
+ "moe_train_capacity_factor": 1,
34
+ "num_attention_heads": 4,
35
+ "num_experts_per_tok": 2,
36
+ "num_hidden_layers": 4,
37
+ "num_key_value_heads": 4,
38
+ "num_local_experts": 4,
39
+ "parallel_attn_mlp_res": true,
40
+ "quantization": null,
41
+ "rms_norm_eps": 1e-05,
42
+ "rope_theta": 10000,
43
+ "router_aux_loss_coef": 0.001,
44
+ "sliding_window": null,
45
+ "tie_word_embeddings": false,
46
+ "torch_dtype": "float32",
47
+ "transformers_version": "4.40.2",
48
+ "use_cache": true,
49
+ "use_residual": true,
50
+ "vocab_size": 32000
51
+ }
configuration_arctic.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Snowflake AI and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """ Arctic model configuration"""
15
+
16
+ from dataclasses import asdict, dataclass
17
+ from typing import Any, Dict
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ ARCTIC_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "arctic": "https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/main/config.json",
27
+ }
28
+
29
+
30
+ @dataclass
31
+ class ArcticLoraConfig:
32
+ lora_r: int = 64
33
+ lora_alpha: float = 16
34
+ shard_base_weights: bool = False
35
+
36
+
37
+ @dataclass
38
+ class ArcticQuantizationConfig:
39
+ q_bits: int = 8
40
+ rounding: str = "nearest"
41
+ mantissa_bits: int = 3
42
+ group_size: int = 512
43
+
44
+
45
+ class ArcticConfig(PretrainedConfig):
46
+ r"""
47
+ This is the configuration class to store the configuration of a [`ArcticModel`]. It is used to instantiate an
48
+ Arctic model according to the specified arguments, defining the model architecture. Instantiating a configuration
49
+ with the defaults will yield a similar configuration to that of the #TODO(rsamdani): add what model has the default config..
50
+
51
+
52
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
53
+ documentation from [`PretrainedConfig`] for more information.
54
+
55
+
56
+ Args:
57
+ vocab_size (`int`, *optional*, defaults to 32000):
58
+ Vocabulary size of the Arctic model. Defines the number of different tokens that can be represented by the
59
+ `inputs_ids` passed when calling [`ArcticModel`]
60
+ hidden_size (`int`, *optional*, defaults to 4096):
61
+ Dimension of the hidden representations.
62
+ intermediate_size (`int`, *optional*, defaults to 14336):
63
+ Dimension of the MLP representations.
64
+ num_hidden_layers (`int`, *optional*, defaults to 32):
65
+ Number of hidden layers in the Transformer encoder.
66
+ num_attention_heads (`int`, *optional*, defaults to 32):
67
+ Number of attention heads for each attention layer in the Transformer encoder.
68
+ num_key_value_heads (`int`, *optional*, defaults to 8):
69
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
70
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
71
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
72
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
73
+ by meanpooling all the original heads within that group. For more details checkout [this
74
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
75
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
76
+ The non-linear activation function (function or string) in the decoder.
77
+ max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
78
+ The maximum sequence length that this model might ever be used with. Arctic's sliding window attention
79
+ allows sequence of up to 4096*32 tokens.
80
+ initializer_range (`float`, *optional*, defaults to 0.02):
81
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
82
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
83
+ The epsilon used by the rms normalization layers.
84
+ use_cache (`bool`, *optional*, defaults to `True`):
85
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
86
+ relevant if `config.is_decoder=True`.
87
+ pad_token_id (`int`, *optional*):
88
+ The id of the padding token.
89
+ bos_token_id (`int`, *optional*, defaults to 1):
90
+ The id of the "beginning-of-sequence" token.
91
+ eos_token_id (`int`, *optional*, defaults to 2):
92
+ The id of the "end-of-sequence" token.
93
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
94
+ Whether the model's input and output word embeddings should be tied.
95
+ rope_theta (`float`, *optional*, defaults to 1000000.0):
96
+ The base period of the RoPE embeddings.
97
+ sliding_window (`int`, *optional*):
98
+ Sliding window attention window size. If not specified, will default to `4096`.
99
+ attention_dropout (`float`, *optional*, defaults to 0.0):
100
+ The dropout ratio for the attention probabilities.
101
+ num_experts_per_tok (`int`, *optional*, defaults to 2):
102
+ The number of experts to root per-token, can be also interpreted as the `top-p` routing
103
+ parameter
104
+ num_local_experts (`int`, *optional*, defaults to 8):
105
+ Number of experts per Sparse MLP layer.
106
+ router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
107
+ The aux loss factor for the total loss.
108
+
109
+ ```python
110
+ >>> from transformers import ArcticModel, ArcticConfig
111
+
112
+ >>> # Initializing a Arctic 7B style configuration TODO(rsamdani): verify which model does the default configuration correspond to.
113
+ >>> configuration = ArcticConfig()
114
+
115
+ >>> # Initializing a model from the Arctic 7B style configuration
116
+ >>> model = ArcticModel(configuration)
117
+
118
+ >>> # Accessing the model configuration
119
+ >>> configuration = model.config
120
+ ```"""
121
+
122
+ model_type = "arctic"
123
+ keys_to_ignore_at_inference = ["past_key_values"]
124
+
125
+ def __init__(
126
+ self,
127
+ vocab_size=32000,
128
+ hidden_size=4096,
129
+ intermediate_size=14336,
130
+ num_hidden_layers=32,
131
+ num_attention_heads=32,
132
+ num_key_value_heads=None,
133
+ hidden_act="silu",
134
+ max_position_embeddings=4096,
135
+ initializer_range=0.02,
136
+ rms_norm_eps=1e-5,
137
+ use_cache=True,
138
+ pad_token_id=None,
139
+ bos_token_id=1,
140
+ eos_token_id=2,
141
+ tie_word_embeddings=False,
142
+ rope_theta=1e6,
143
+ sliding_window=None,
144
+ attention_dropout=0.0,
145
+ num_experts_per_tok=1,
146
+ num_local_experts=8,
147
+ router_aux_loss_coef=0.001,
148
+ moe_layer_frequency=2,
149
+ parallel_attn_mlp_res=False,
150
+ moe_train_capacity_factor=1,
151
+ moe_eval_capacity_factor=1,
152
+ enable_expert_tensor_parallelism=False,
153
+ moe_min_capacity=0,
154
+ moe_token_dropping=True,
155
+ quantization=None,
156
+ **kwargs,
157
+ ):
158
+ self.vocab_size = vocab_size
159
+ self.max_position_embeddings = max_position_embeddings
160
+ self.hidden_size = hidden_size
161
+ self.intermediate_size = intermediate_size
162
+ self.num_hidden_layers = num_hidden_layers
163
+ self.num_attention_heads = num_attention_heads
164
+ self.sliding_window = sliding_window
165
+
166
+ # for backward compatibility
167
+ if num_key_value_heads is None:
168
+ num_key_value_heads = num_attention_heads
169
+
170
+ self.num_key_value_heads = num_key_value_heads
171
+ self.hidden_act = hidden_act
172
+ self.initializer_range = initializer_range
173
+ self.rms_norm_eps = rms_norm_eps
174
+ self.use_cache = use_cache
175
+ self.rope_theta = rope_theta
176
+ self.attention_dropout = attention_dropout
177
+
178
+ self.num_experts_per_tok = num_experts_per_tok
179
+ self.num_local_experts = num_local_experts
180
+ self.router_aux_loss_coef = router_aux_loss_coef
181
+ self.moe_layer_frequency = moe_layer_frequency
182
+ self.moe_train_capacity_factor = moe_train_capacity_factor
183
+ self.moe_eval_capacity_factor = moe_eval_capacity_factor
184
+ self.enable_expert_tensor_parallelism = enable_expert_tensor_parallelism
185
+ self.moe_min_capacity = moe_min_capacity
186
+ self.moe_token_dropping = moe_token_dropping
187
+ self.parallel_attn_mlp_res = parallel_attn_mlp_res
188
+ if isinstance(quantization, dict):
189
+ self.quantization = ArcticQuantizationConfig(**quantization)
190
+ else:
191
+ self.quantization = quantization
192
+
193
+ super().__init__(
194
+ pad_token_id=pad_token_id,
195
+ bos_token_id=bos_token_id,
196
+ eos_token_id=eos_token_id,
197
+ tie_word_embeddings=tie_word_embeddings,
198
+ **kwargs,
199
+ )
200
+
201
+ @classmethod
202
+ def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "ArcticConfig":
203
+ result = super().from_dict(config_dict, **kwargs)
204
+ if isinstance(result, tuple):
205
+ config = result[0]
206
+ else:
207
+ config = result
208
+ if isinstance(config.quantization, dict):
209
+ config.quantization = ArcticQuantizationConfig(**config.quantization)
210
+ return result
211
+
212
+ def to_dict(self) -> Dict[str, Any]:
213
+ ret = super().to_dict()
214
+ if isinstance(ret["quantization"], ArcticQuantizationConfig):
215
+ ret["quantization"] = asdict(ret["quantization"])
216
+ return ret
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.40.2"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ee85809149657d0f1e06765c2efb7543112ac470f5100f01f43e90b08d54b36
3
+ size 8419384
modeling_arctic.py ADDED
@@ -0,0 +1,1949 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Arctic model."""
21
+ import copy
22
+ import inspect
23
+ import time
24
+ import math
25
+ import warnings
26
+ import re
27
+ from typing import List, Optional, Tuple, Union
28
+
29
+ #import deepspeed
30
+ import torch
31
+ import torch.nn.functional as F
32
+ import torch.utils.checkpoint
33
+ from torch import nn
34
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
35
+
36
+ from transformers.activations import ACT2FN
37
+ from transformers.cache_utils import Cache, DynamicCache
38
+ from transformers.modeling_attn_mask_utils import (
39
+ _prepare_4d_causal_attention_mask,
40
+ _prepare_4d_causal_attention_mask_for_sdpa,
41
+ )
42
+ from transformers.modeling_outputs import (
43
+ MoeCausalLMOutputWithPast,
44
+ MoeModelOutputWithPast,
45
+ SequenceClassifierOutputWithPast,
46
+ )
47
+ from transformers.modeling_utils import PreTrainedModel
48
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_13
49
+ from transformers.utils import (
50
+ add_start_docstrings,
51
+ add_start_docstrings_to_model_forward,
52
+ is_flash_attn_2_available,
53
+ is_flash_attn_greater_or_equal_2_10,
54
+ logging,
55
+ replace_return_docstrings,
56
+ )
57
+ from transformers.utils.import_utils import is_torch_fx_available
58
+ from .configuration_arctic import ArcticConfig
59
+ from transformers.integrations.deepspeed import is_deepspeed_available
60
+ from transformers.utils.versions import require_version
61
+
62
+ try:
63
+ if is_deepspeed_available():
64
+ from deepspeed.moe.layer import MoE
65
+ # Note that below will crash if there is an available deepspeed that does not have ds_linear.
66
+ try:
67
+ import deepspeed.linear as ds_linear
68
+ except Exception:
69
+ pass
70
+ else:
71
+ MoE = None
72
+ except:
73
+ MoE = None
74
+
75
+ try:
76
+ if is_flash_attn_2_available():
77
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
78
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
79
+
80
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
81
+ except:
82
+ pass
83
+
84
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
85
+ # It means that the function will not be traced through and simply appear as a node in the graph.
86
+ if is_torch_fx_available():
87
+ if not is_torch_greater_or_equal_than_1_13:
88
+ import torch.fx
89
+
90
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
91
+
92
+
93
+ logger = logging.get_logger(__name__)
94
+
95
+ _CONFIG_FOR_DOC = "ArcticConfig"
96
+ USE_DEEPSPEED_MOE_ARG = "use_deepspeed_moe_implementation"
97
+ MOE_EXPERT_PARALLEL_SIZE_ARG = "moe_expert_parallel_size"
98
+ DEEPSPEED_QUANTIZATION_CONFIG = "deepspeed_quantization"
99
+ DEEPSPEED_LORA_CONFIG = "deepspeed_lora"
100
+ QUANTIZATION_CONFIG = "ds_quantization_config"
101
+
102
+ # REQUIRED_DEEPSPEED_VERSION = "deepspeed>0.14.5"
103
+ # def is_deepspeed_valid_and_available(raise_error=False, error_msg=""):
104
+ # available_and_valid = True
105
+ # if not is_deepspeed_available():
106
+ # available_and_valid = False
107
+ # if raise_error:
108
+ # raise ValueError(f"DeepSpeed is required for this feature, {error_msg}")
109
+ # else:
110
+
111
+ # return available_and_valid
112
+
113
+ def load_balancing_loss_func(
114
+ gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=4, attention_mask: Optional[torch.Tensor] = None
115
+ ) -> float:
116
+ r"""
117
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
118
+
119
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
120
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
121
+ experts is too unbalanced.
122
+
123
+ Args:
124
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
125
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
126
+ shape [batch_size X sequence_length, num_experts].
127
+ attention_mask (`torch.Tensor`, None):
128
+ The attention_mask used in forward function
129
+ shape [batch_size X sequence_length] if not None.
130
+ num_experts (`int`, *optional*):
131
+ Number of experts
132
+
133
+ Returns:
134
+ The auxiliary loss.
135
+ """
136
+ if gate_logits is None or not isinstance(gate_logits, tuple):
137
+ return 0
138
+
139
+ if isinstance(gate_logits, tuple):
140
+ compute_device = gate_logits[0].device
141
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
142
+
143
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
144
+
145
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
146
+
147
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
148
+
149
+ if attention_mask is None:
150
+ # Compute the percentage of tokens routed to each experts
151
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
152
+
153
+ # Compute the average probability of routing to these experts
154
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
155
+ else:
156
+ batch_size, sequence_length = attention_mask.shape
157
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
158
+
159
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
160
+ expert_attention_mask = (
161
+ attention_mask[None, :, :, None, None]
162
+ .expand((num_hidden_layers, batch_size, sequence_length, 2, num_experts))
163
+ .reshape(-1, 2, num_experts)
164
+ .to(compute_device)
165
+ )
166
+
167
+ # Compute the percentage of tokens routed to each experts
168
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
169
+ expert_attention_mask, dim=0
170
+ )
171
+
172
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
173
+ router_per_expert_attention_mask = (
174
+ attention_mask[None, :, :, None]
175
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
176
+ .reshape(-1, num_experts)
177
+ .to(compute_device)
178
+ )
179
+
180
+ # Compute the average probability of routing to these experts
181
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
182
+ router_per_expert_attention_mask, dim=0
183
+ )
184
+
185
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
186
+ return overall_loss * num_experts
187
+
188
+
189
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
190
+ def _get_unpad_data(attention_mask):
191
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
192
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
193
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
194
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
195
+ return (
196
+ indices,
197
+ cu_seqlens,
198
+ max_seqlen_in_batch,
199
+ )
200
+
201
+
202
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Arctic
203
+ class ArcticRMSNorm(nn.Module):
204
+ def __init__(self, hidden_size, eps=1e-6):
205
+ """
206
+ ArcticRMSNorm is equivalent to T5LayerNorm
207
+ """
208
+ super().__init__()
209
+ self.weight = nn.Parameter(torch.ones(hidden_size))
210
+ self.variance_epsilon = eps
211
+
212
+ def forward(self, hidden_states):
213
+ input_dtype = hidden_states.dtype
214
+ hidden_states = hidden_states.to(torch.float32)
215
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
216
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
217
+ return self.weight * hidden_states.to(input_dtype)
218
+
219
+
220
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Arctic
221
+ class ArcticRotaryEmbedding(nn.Module):
222
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
223
+ super().__init__()
224
+
225
+ self.dim = dim
226
+ self.max_position_embeddings = max_position_embeddings
227
+ self.base = base
228
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
229
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
230
+
231
+ # Build here to make `torch.jit.trace` work.
232
+ self._set_cos_sin_cache(
233
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
234
+ )
235
+
236
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
237
+ self.max_seq_len_cached = seq_len
238
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
239
+
240
+ freqs = torch.outer(t, self.inv_freq)
241
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
242
+ emb = torch.cat((freqs, freqs), dim=-1)
243
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
244
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
245
+
246
+ def forward(self, x, seq_len=None):
247
+ # x: [bs, num_attention_heads, seq_len, head_size]
248
+ if seq_len > self.max_seq_len_cached:
249
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
250
+
251
+ return (
252
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
253
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
254
+ )
255
+
256
+
257
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
258
+ def rotate_half(x):
259
+ """Rotates half the hidden dims of the input."""
260
+ x1 = x[..., : x.shape[-1] // 2]
261
+ x2 = x[..., x.shape[-1] // 2 :]
262
+ return torch.cat((-x2, x1), dim=-1)
263
+
264
+
265
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
266
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
267
+ """Applies Rotary Position Embedding to the query and key tensors.
268
+
269
+ Args:
270
+ q (`torch.Tensor`): The query tensor.
271
+ k (`torch.Tensor`): The key tensor.
272
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
273
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
274
+ position_ids (`torch.Tensor`):
275
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
276
+ used to pass offsetted position ids when working with a KV-cache.
277
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
278
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
279
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
280
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
281
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
282
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
283
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
284
+ Returns:
285
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
286
+ """
287
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
288
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
289
+ q_embed = (q * cos) + (rotate_half(q) * sin)
290
+ k_embed = (k * cos) + (rotate_half(k) * sin)
291
+ return q_embed, k_embed
292
+
293
+
294
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
295
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
296
+ """
297
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
298
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
299
+ """
300
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
301
+ if n_rep == 1:
302
+ return hidden_states
303
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
304
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
305
+
306
+
307
+ # Copied from transformers.models.mistral.modeling_mistral.MistralAttention with Mistral->Arctic
308
+ class ArcticAttention(nn.Module):
309
+ """
310
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
311
+ and "Generating Long Sequences with Sparse Transformers".
312
+ """
313
+
314
+ def __init__(self, config: ArcticConfig, layer_idx: Optional[int] = None, **kwargs):
315
+ super().__init__()
316
+ self.config = config
317
+ self.layer_idx = layer_idx
318
+ if layer_idx is None:
319
+ logger.warning_once(
320
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
321
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
322
+ "when creating this class."
323
+ )
324
+
325
+ self.hidden_size = config.hidden_size
326
+ self.num_heads = config.num_attention_heads
327
+ self.head_dim = self.hidden_size // self.num_heads
328
+ self.num_key_value_heads = config.num_key_value_heads
329
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
330
+ self.max_position_embeddings = config.max_position_embeddings
331
+ self.rope_theta = config.rope_theta
332
+ self.is_causal = True
333
+ self.attention_dropout = config.attention_dropout
334
+ self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG]
335
+ if (self.head_dim * self.num_heads) != self.hidden_size:
336
+ raise ValueError(
337
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
338
+ f" and `num_heads`: {self.num_heads})."
339
+ )
340
+
341
+ deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG)
342
+ deepspeed_lora_config = kwargs.get(DEEPSPEED_LORA_CONFIG)
343
+ quantization_config = kwargs.get(QUANTIZATION_CONFIG, None)
344
+
345
+ self.q_proj = get_arctic_linear(self.hidden_size, self.num_heads * self.head_dim, bias=False,
346
+ use_deepspeed_implementation=self.use_deepspeed_implementation,
347
+ ds_optimized_lora_config=deepspeed_lora_config,
348
+ ds_optimized_quantization_config=quantization_config,
349
+ ds_optimized_base_weight_sharding=True,
350
+ dtype=torch.bfloat16)
351
+ self.k_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False,
352
+ use_deepspeed_implementation=self.use_deepspeed_implementation,
353
+ ds_optimized_lora_config=deepspeed_lora_config,
354
+ ds_optimized_quantization_config=quantization_config,
355
+ ds_optimized_base_weight_sharding=True,
356
+ dtype=torch.bfloat16)
357
+ self.v_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False,
358
+ use_deepspeed_implementation=self.use_deepspeed_implementation,
359
+ ds_optimized_lora_config=deepspeed_lora_config,
360
+ ds_optimized_quantization_config=quantization_config,
361
+ ds_optimized_base_weight_sharding=True,
362
+ dtype=torch.bfloat16)
363
+ self.o_proj = get_arctic_linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False,
364
+ use_deepspeed_implementation=self.use_deepspeed_implementation,
365
+ ds_optimized_lora_config=deepspeed_lora_config,
366
+ ds_optimized_quantization_config=quantization_config,
367
+ ds_optimized_base_weight_sharding=True,
368
+ dtype=torch.bfloat16)
369
+
370
+ self.rotary_emb = ArcticRotaryEmbedding(
371
+ self.head_dim,
372
+ max_position_embeddings=self.max_position_embeddings,
373
+ base=self.rope_theta,
374
+ )
375
+
376
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
377
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
378
+
379
+ def forward(
380
+ self,
381
+ hidden_states: torch.Tensor,
382
+ attention_mask: Optional[torch.Tensor] = None,
383
+ position_ids: Optional[torch.LongTensor] = None,
384
+ past_key_value: Optional[Cache] = None,
385
+ output_attentions: bool = False,
386
+ use_cache: bool = False,
387
+ **kwargs,
388
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
389
+ if "padding_mask" in kwargs:
390
+ warnings.warn(
391
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
392
+ )
393
+ bsz, q_len, _ = hidden_states.size()
394
+
395
+ query_states = self.q_proj(hidden_states)
396
+ key_states = self.k_proj(hidden_states)
397
+ value_states = self.v_proj(hidden_states)
398
+
399
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
400
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
401
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
402
+
403
+ kv_seq_len = key_states.shape[-2]
404
+ if past_key_value is not None:
405
+ if self.layer_idx is None:
406
+ raise ValueError(
407
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
408
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
409
+ "with a layer index."
410
+ )
411
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
412
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
413
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
414
+
415
+ if past_key_value is not None:
416
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
417
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
418
+
419
+ # repeat k/v heads if n_kv_heads < n_heads
420
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
421
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
422
+
423
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
424
+
425
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
426
+ raise ValueError(
427
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
428
+ f" {attn_weights.size()}"
429
+ )
430
+
431
+ if attention_mask is not None:
432
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
433
+ raise ValueError(
434
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
435
+ )
436
+
437
+ attn_weights = attn_weights + attention_mask
438
+
439
+ # upcast attention to fp32
440
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
441
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
442
+ attn_output = torch.matmul(attn_weights, value_states)
443
+
444
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
445
+ raise ValueError(
446
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
447
+ f" {attn_output.size()}"
448
+ )
449
+
450
+ attn_output = attn_output.transpose(1, 2).contiguous()
451
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
452
+
453
+ attn_output = self.o_proj(attn_output)
454
+
455
+ if not output_attentions:
456
+ attn_weights = None
457
+
458
+ return attn_output, attn_weights, past_key_value
459
+
460
+
461
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Arctic
462
+ class ArcticFlashAttention2(ArcticAttention):
463
+ """
464
+ Arctic flash attention module. This module inherits from `ArcticAttention` as the weights of the module stays
465
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
466
+ flash attention and deal with padding tokens in case the input contains any of them.
467
+ """
468
+
469
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
470
+ def __init__(self, *args, **kwargs):
471
+ super().__init__(*args, **kwargs)
472
+
473
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
474
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
475
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
476
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
477
+
478
+ def forward(
479
+ self,
480
+ hidden_states: torch.Tensor,
481
+ attention_mask: Optional[torch.Tensor] = None,
482
+ position_ids: Optional[torch.LongTensor] = None,
483
+ past_key_value: Optional[Cache] = None,
484
+ output_attentions: bool = False,
485
+ use_cache: bool = False,
486
+ **kwargs,
487
+ ):
488
+ if "padding_mask" in kwargs:
489
+ warnings.warn(
490
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
491
+ )
492
+
493
+ # overwrite attention_mask with padding_mask
494
+ attention_mask = kwargs.pop("padding_mask")
495
+ bsz, q_len, _ = hidden_states.size()
496
+
497
+ query_states = self.q_proj(hidden_states)
498
+ key_states = self.k_proj(hidden_states)
499
+ value_states = self.v_proj(hidden_states)
500
+
501
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
502
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
503
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
504
+
505
+ kv_seq_len = key_states.shape[-2]
506
+ if past_key_value is not None:
507
+ if self.layer_idx is None:
508
+ raise ValueError(
509
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
510
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
511
+ "with a layer index."
512
+ )
513
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
514
+
515
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
516
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
517
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
518
+
519
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
520
+
521
+ use_sliding_windows = (
522
+ _flash_supports_window_size
523
+ and getattr(self.config, "sliding_window", None) is not None
524
+ and kv_seq_len > self.config.sliding_window
525
+ )
526
+
527
+ if not _flash_supports_window_size:
528
+ logger.warning_once(
529
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
530
+ " make sure to upgrade flash-attn library."
531
+ )
532
+
533
+ if past_key_value is not None:
534
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
535
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
536
+ if (
537
+ getattr(self.config, "sliding_window", None) is not None
538
+ and kv_seq_len > self.config.sliding_window
539
+ and cache_has_contents
540
+ ):
541
+ slicing_tokens = 1 - self.config.sliding_window
542
+
543
+ past_key = past_key_value[self.layer_idx][0]
544
+ past_value = past_key_value[self.layer_idx][1]
545
+
546
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
547
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
548
+
549
+ if past_key.shape[-2] != self.config.sliding_window - 1:
550
+ raise ValueError(
551
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
552
+ f" {past_key.shape}"
553
+ )
554
+
555
+ if attention_mask is not None:
556
+ attention_mask = attention_mask[:, slicing_tokens:]
557
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
558
+
559
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
560
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
561
+
562
+ # repeat k/v heads if n_kv_heads < n_heads
563
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
564
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
565
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
566
+
567
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
568
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
569
+ # cast them back in float16 just to be sure everything works as expected.
570
+ input_dtype = query_states.dtype
571
+ if input_dtype == torch.float32:
572
+ if torch.is_autocast_enabled():
573
+ target_dtype = torch.get_autocast_gpu_dtype()
574
+ # Handle the case where the model is quantized
575
+ elif hasattr(self.config, "_pre_quantization_dtype"):
576
+ target_dtype = self.config._pre_quantization_dtype
577
+ else:
578
+ target_dtype = self.q_proj.weight.dtype
579
+
580
+ logger.warning_once(
581
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
582
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
583
+ f" {target_dtype}."
584
+ )
585
+
586
+ query_states = query_states.to(target_dtype)
587
+ key_states = key_states.to(target_dtype)
588
+ value_states = value_states.to(target_dtype)
589
+
590
+ # Reashape to the expected shape for Flash Attention
591
+ query_states = query_states.transpose(1, 2)
592
+ key_states = key_states.transpose(1, 2)
593
+ value_states = value_states.transpose(1, 2)
594
+
595
+ attn_output = self._flash_attention_forward(
596
+ query_states,
597
+ key_states,
598
+ value_states,
599
+ attention_mask,
600
+ q_len,
601
+ dropout=dropout_rate,
602
+ use_sliding_windows=use_sliding_windows,
603
+ )
604
+
605
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
606
+ attn_output = self.o_proj(attn_output)
607
+
608
+ if not output_attentions:
609
+ attn_weights = None
610
+
611
+ return attn_output, attn_weights, past_key_value
612
+
613
+ def _flash_attention_forward(
614
+ self,
615
+ query_states,
616
+ key_states,
617
+ value_states,
618
+ attention_mask,
619
+ query_length,
620
+ dropout=0.0,
621
+ softmax_scale=None,
622
+ use_sliding_windows=False,
623
+ ):
624
+ """
625
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
626
+ first unpad the input, then computes the attention scores and pad the final attention scores.
627
+
628
+ Args:
629
+ query_states (`torch.Tensor`):
630
+ Input query states to be passed to Flash Attention API
631
+ key_states (`torch.Tensor`):
632
+ Input key states to be passed to Flash Attention API
633
+ value_states (`torch.Tensor`):
634
+ Input value states to be passed to Flash Attention API
635
+ attention_mask (`torch.Tensor`):
636
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
637
+ position of padding tokens and 1 for the position of non-padding tokens.
638
+ dropout (`int`, *optional*):
639
+ Attention dropout
640
+ softmax_scale (`float`, *optional*):
641
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
642
+ use_sliding_windows (`bool`, *optional*):
643
+ Whether to activate sliding window attention.
644
+ """
645
+ if not self._flash_attn_uses_top_left_mask:
646
+ causal = self.is_causal
647
+ else:
648
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
649
+ causal = self.is_causal and query_length != 1
650
+
651
+ # Contains at least one padding token in the sequence
652
+ if attention_mask is not None:
653
+ batch_size = query_states.shape[0]
654
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
655
+ query_states, key_states, value_states, attention_mask, query_length
656
+ )
657
+
658
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
659
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
660
+
661
+ if not use_sliding_windows:
662
+ attn_output_unpad = flash_attn_varlen_func(
663
+ query_states,
664
+ key_states,
665
+ value_states,
666
+ cu_seqlens_q=cu_seqlens_q,
667
+ cu_seqlens_k=cu_seqlens_k,
668
+ max_seqlen_q=max_seqlen_in_batch_q,
669
+ max_seqlen_k=max_seqlen_in_batch_k,
670
+ dropout_p=dropout,
671
+ softmax_scale=softmax_scale,
672
+ causal=causal,
673
+ )
674
+ else:
675
+ attn_output_unpad = flash_attn_varlen_func(
676
+ query_states,
677
+ key_states,
678
+ value_states,
679
+ cu_seqlens_q=cu_seqlens_q,
680
+ cu_seqlens_k=cu_seqlens_k,
681
+ max_seqlen_q=max_seqlen_in_batch_q,
682
+ max_seqlen_k=max_seqlen_in_batch_k,
683
+ dropout_p=dropout,
684
+ softmax_scale=softmax_scale,
685
+ causal=causal,
686
+ window_size=(self.config.sliding_window, self.config.sliding_window),
687
+ )
688
+
689
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
690
+ else:
691
+ if not use_sliding_windows:
692
+ attn_output = flash_attn_func(
693
+ query_states,
694
+ key_states,
695
+ value_states,
696
+ dropout,
697
+ softmax_scale=softmax_scale,
698
+ causal=causal,
699
+ )
700
+ else:
701
+ attn_output = flash_attn_func(
702
+ query_states,
703
+ key_states,
704
+ value_states,
705
+ dropout,
706
+ softmax_scale=softmax_scale,
707
+ causal=causal,
708
+ window_size=(self.config.sliding_window, self.config.sliding_window),
709
+ )
710
+
711
+ return attn_output
712
+
713
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
714
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
715
+
716
+ # On the first iteration we need to properly re-create the padding mask
717
+ # by slicing it on the proper place
718
+ if kv_seq_len != attention_mask.shape[-1]:
719
+ attention_mask_num_tokens = attention_mask.shape[-1]
720
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
721
+
722
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
723
+
724
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
725
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
726
+
727
+ if query_length == kv_seq_len:
728
+ query_layer = index_first_axis(
729
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
730
+ )
731
+ cu_seqlens_q = cu_seqlens_k
732
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
733
+ indices_q = indices_k
734
+ elif query_length == 1:
735
+ max_seqlen_in_batch_q = 1
736
+ cu_seqlens_q = torch.arange(
737
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
738
+ ) # There is a memcpy here, that is very bad.
739
+ indices_q = cu_seqlens_q[:-1]
740
+ query_layer = query_layer.squeeze(1)
741
+ else:
742
+ # The -q_len: slice assumes left padding.
743
+ attention_mask = attention_mask[:, -query_length:]
744
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
745
+
746
+ return (
747
+ query_layer,
748
+ key_layer,
749
+ value_layer,
750
+ indices_q,
751
+ (cu_seqlens_q, cu_seqlens_k),
752
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
753
+ )
754
+
755
+ def get_arctic_linear(input_dim,
756
+ output_dim,
757
+ bias=False,
758
+ use_deepspeed_implementation=False,
759
+ ds_optimized_lora_config=None,
760
+ ds_optimized_quantization_config=None,
761
+ ds_optimized_base_weight_sharding=False,
762
+ dtype=torch.bfloat16):
763
+ """Can return deepspeed optimized linear if available.
764
+ Args:
765
+ input_dim, output_dim, bias, dtype: self explanatory (same as from nn.Linear)
766
+ ds_optimized_lora_config: config of type ds_linear.LoRAConfig that contains lora specific parameter if we want to add lora to this layer.
767
+ ds_optimized_quantization_config: config of type ds_linear.QuantizationConfig.
768
+ ds_optimized_base_weight_sharding: bool. If true, the base weight for lora (provided ds_optimized_lora_config is not None) will be sharded across all available gpus
769
+ in a tensor parallel way.
770
+ """
771
+ if is_deepspeed_available():
772
+ if ds_optimized_lora_config is not None:
773
+ ds_optimized_lora_config: ds_linear.LoRAConfig = copy.deepcopy(ds_optimized_lora_config)
774
+ ds_optimized_lora_config.base_weight_sharding = torch.distributed.get_world_size() if ds_optimized_base_weight_sharding else 1
775
+ return ds_linear.OptimizedLinear(input_dim, output_dim, bias, ds_optimized_lora_config, ds_optimized_quantization_config, dtype=dtype)
776
+ return nn.Linear(input_dim, output_dim, bias=bias, dtype=dtype)
777
+
778
+
779
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Arctic
780
+ class ArcticSdpaAttention(ArcticAttention):
781
+ """
782
+ Arctic attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
783
+ `ArcticAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
784
+ SDPA API.
785
+ """
786
+
787
+ # Adapted from ArcticAttention.forward
788
+ def forward(
789
+ self,
790
+ hidden_states: torch.Tensor,
791
+ attention_mask: Optional[torch.Tensor] = None,
792
+ position_ids: Optional[torch.LongTensor] = None,
793
+ past_key_value: Optional[Cache] = None,
794
+ output_attentions: bool = False,
795
+ use_cache: bool = False,
796
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
797
+ if output_attentions:
798
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
799
+ logger.warning_once(
800
+ "ArcticModel is using ArcticSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
801
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
802
+ )
803
+ return super().forward(
804
+ hidden_states=hidden_states,
805
+ attention_mask=attention_mask,
806
+ position_ids=position_ids,
807
+ past_key_value=past_key_value,
808
+ output_attentions=output_attentions,
809
+ use_cache=use_cache,
810
+ )
811
+
812
+ bsz, q_len, _ = hidden_states.size()
813
+
814
+ query_states = self.q_proj(hidden_states)
815
+ key_states = self.k_proj(hidden_states)
816
+ value_states = self.v_proj(hidden_states)
817
+
818
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
819
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
820
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
821
+
822
+ kv_seq_len = key_states.shape[-2]
823
+ if past_key_value is not None:
824
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
825
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
826
+
827
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
828
+
829
+ if past_key_value is not None:
830
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
831
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
832
+
833
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
834
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
835
+
836
+ if attention_mask is not None:
837
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
838
+ raise ValueError(
839
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
840
+ )
841
+
842
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
843
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
844
+ if query_states.device.type == "cuda" and attention_mask is not None:
845
+ query_states = query_states.contiguous()
846
+ key_states = key_states.contiguous()
847
+ value_states = value_states.contiguous()
848
+
849
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
850
+ query_states,
851
+ key_states,
852
+ value_states,
853
+ attn_mask=attention_mask,
854
+ dropout_p=self.attention_dropout if self.training else 0.0,
855
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
856
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
857
+ )
858
+
859
+ attn_output = attn_output.transpose(1, 2).contiguous()
860
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
861
+
862
+ attn_output = self.o_proj(attn_output)
863
+
864
+ return attn_output, None, past_key_value
865
+
866
+
867
+ MIXTRAL_ATTENTION_CLASSES = {
868
+ "eager": ArcticAttention,
869
+ "flash_attention_2": ArcticFlashAttention2,
870
+ "sdpa": ArcticSdpaAttention,
871
+ }
872
+
873
+
874
+ class ArcticMLP(nn.Module):
875
+ def __init__(self, config: ArcticConfig,
876
+ use_deepspeed_implementation=False,
877
+ ds_optimized_lora_config=None,
878
+ ds_optimized_quantization_config=None,
879
+ shard_base_weights_if_doing_lora=False,
880
+ is_residual_mlp=False):
881
+ """MLP class for Arctic supporting vanilla linear layers as well as some deepspeed optimizations.
882
+
883
+ ds_optimized_lora_config: config of type ds_linear.LoRAConfig that contains lora specific parameter if we want to add lora to this layer.
884
+ ds_optimized_quantization_config: config of type ds_linear.QuantizationConfig.
885
+ ds_optimized_base_weight_sharding: bool. If true, the base weight for lora (provided ds_optimized_lora_config is not None) will be sharded across all available gpus
886
+ in a tensor parallel way.
887
+ is_residual_mlp: bool. If true, this is MLP inside arctic residual layer which has ffn_dim the same as full intermediate_size.
888
+ """
889
+ super(ArcticMLP, self).__init__()
890
+ self.hidden_dim = config.hidden_size
891
+ self.ffn_dim = config.intermediate_size if not is_residual_mlp else self.hidden_dim
892
+ self.w1 = get_arctic_linear(self.hidden_dim, self.ffn_dim, False,
893
+ use_deepspeed_implementation=use_deepspeed_implementation,
894
+ ds_optimized_lora_config=ds_optimized_lora_config,
895
+ ds_optimized_quantization_config=ds_optimized_quantization_config,
896
+ ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora,
897
+ dtype=torch.bfloat16)
898
+ self.w2 = get_arctic_linear(self.ffn_dim, self.hidden_dim, False,
899
+ use_deepspeed_implementation=use_deepspeed_implementation,
900
+ ds_optimized_lora_config=ds_optimized_lora_config,
901
+ ds_optimized_quantization_config=ds_optimized_quantization_config,
902
+ ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora,
903
+ dtype=torch.bfloat16)
904
+ self.w3 = get_arctic_linear(self.hidden_dim, self.ffn_dim, False,
905
+ use_deepspeed_implementation=use_deepspeed_implementation,
906
+ ds_optimized_lora_config=ds_optimized_lora_config,
907
+ ds_optimized_quantization_config=ds_optimized_quantization_config,
908
+ ds_optimized_base_weight_sharding=shard_base_weights_if_doing_lora,
909
+ dtype=torch.bfloat16)
910
+ self.act_fn = ACT2FN[config.hidden_act]
911
+
912
+ def forward(self, hidden_states):
913
+ current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
914
+ current_hidden_states = self.w2(current_hidden_states)
915
+ return current_hidden_states
916
+
917
+
918
+ class ArcticMoE(nn.Module):
919
+ def __init__(self, config: ArcticConfig, layer_id: int, **kwargs):
920
+ super(ArcticMoE, self).__init__()
921
+
922
+ self.hidden_dim = config.hidden_size
923
+ self.num_experts = config.num_local_experts
924
+ self.layer_id = layer_id
925
+ self.top_k = config.num_experts_per_tok
926
+ self.is_moe_layer = (layer_id+1) % config.moe_layer_frequency == 0
927
+
928
+ self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG]
929
+ if self.use_deepspeed_implementation and MoE is None:
930
+ raise ValueError("Deepspeed is not installed")
931
+ quantization_config = kwargs.get(QUANTIZATION_CONFIG, None)
932
+ deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG)
933
+ if not self.is_moe_layer: # dense, not MoE
934
+ self.mlp = ArcticMLP(config,
935
+ use_deepspeed_implementation=self.use_deepspeed_implementation,
936
+ ds_optimized_quantization_config=quantization_config,
937
+ ds_optimized_lora_config=deepspeed_lora,
938
+ shard_base_weights_if_doing_lora=True)
939
+ else:
940
+ if self.use_deepspeed_implementation: # DeepSpeed's MoE
941
+ moe_expert_parallel_size = kwargs.get(MOE_EXPERT_PARALLEL_SIZE_ARG, 1)
942
+ self.mlp = MoE(self.hidden_dim,
943
+ # base weight sharding false for all deepspeed moe calls because it is already sharded
944
+ ArcticMLP(config,
945
+ use_deepspeed_implementation=True,
946
+ ds_optimized_quantization_config=quantization_config,
947
+ ds_optimized_lora_config=deepspeed_lora,
948
+ shard_base_weights_if_doing_lora=False),
949
+ num_experts=config.num_local_experts,
950
+ ep_size=moe_expert_parallel_size,
951
+ k=config.num_experts_per_tok,
952
+ use_residual=False,
953
+ capacity_factor=config.moe_train_capacity_factor,
954
+ eval_capacity_factor=config.moe_eval_capacity_factor,
955
+ enable_expert_tensor_parallelism=config.enable_expert_tensor_parallelism,
956
+ min_capacity=config.moe_min_capacity,
957
+ drop_tokens=config.moe_token_dropping
958
+ )
959
+ else:
960
+ # "local" MoE implementation
961
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
962
+ self.experts = nn.ModuleList([ArcticMLP(config,
963
+ use_deepspeed_implementation=self.use_deepspeed_implementation,
964
+ ds_optimized_quantization_config=quantization_config,
965
+ ds_optimized_lora_config=deepspeed_lora,
966
+ shard_base_weights_if_doing_lora=True) for i in range(self.num_experts)])
967
+
968
+ # if torch.distributed.get_rank() == 0:
969
+ # deepspeed.runtime.utils.see_memory_usage("", force=True)
970
+
971
+
972
+ # Similar in behavior to transformers.models.mixtral.modeling_mixtral.MixtralSparseMoeBlock.forward but more efficient.
973
+ def _moe_foreward(self, hidden_states: torch.Tensor) -> torch.Tensor:
974
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
975
+ hidden_states = hidden_states.view(-1, hidden_dim)
976
+ # router_logits: (batch * sequence_length, n_experts)
977
+ router_logits = self.gate(hidden_states)
978
+
979
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
980
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
981
+ if self.top_k > 1:
982
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
983
+ # we cast back to the input dtype
984
+
985
+ final_hidden_states = torch.zeros(
986
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
987
+ )
988
+
989
+ # Matching between experts, tokens, and their top-k rank. For every i,
990
+ # expert_idx[i] is the rank topk_idx[i] expert for token_idx[i].
991
+ expert_idx, token_idx, topk_idx = torch.where(
992
+ selected_experts == torch.arange(
993
+ self.num_experts,
994
+ device=selected_experts.device,
995
+ ).view((self.num_experts, 1, 1))
996
+ )
997
+
998
+ # Split into one chunk per expert.
999
+ bincount = torch.bincount(expert_idx, minlength=self.num_experts).tolist()
1000
+ token_idx = token_idx.split(bincount)
1001
+ topk_idx = topk_idx.split(bincount)
1002
+
1003
+ # Loop over all available experts in the model and perform the computation on each expert
1004
+ for expert_layer, top_x, idx in zip(self.experts, token_idx, topk_idx):
1005
+ #if top_x.shape[0] == 0:
1006
+ # continue
1007
+
1008
+ # in torch it is faster to index using lists than torch tensors
1009
+ top_x_list = top_x.tolist()
1010
+ idx_list = idx.tolist()
1011
+
1012
+ # Index the correct hidden states and compute the expert hidden state for
1013
+ # the current expert. We need to make sure to multiply the output hidden
1014
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
1015
+ current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim)
1016
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x_list, idx_list, None]
1017
+
1018
+ # However `index_add_` only support torch tensors for indexing so we'll use
1019
+ # the `top_x` tensor here.
1020
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
1021
+ # torch.distributed.barrier()
1022
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
1023
+ return final_hidden_states, load_balancing_loss_func((router_logits, ), self.num_experts, self.top_k) # ZY: let's directly output the loss to align what we have in ds
1024
+
1025
+ def forward(self, hidden_states: torch.Tensor):
1026
+ if self.is_moe_layer:
1027
+ if self.use_deepspeed_implementation:
1028
+ # deepspeed returns a tuple including output, gate loss, and expert count.
1029
+ hidden_states, moe_loss, _ = self.mlp(hidden_states)
1030
+ return hidden_states, moe_loss
1031
+ else:
1032
+ return self._moe_foreward(hidden_states)
1033
+ else:
1034
+ return self.mlp(hidden_states), torch.tensor(0.0, device=hidden_states.device, dtype=hidden_states.dtype)
1035
+
1036
+
1037
+ class ArcticDecoderLayer(nn.Module):
1038
+ def __init__(self, config: ArcticConfig, layer_idx: int, **kwargs):
1039
+ super().__init__()
1040
+ self.layer_idx = layer_idx
1041
+ self.hidden_size = config.hidden_size
1042
+ self.self_attn = MIXTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx, **kwargs)
1043
+ self.block_sparse_moe = ArcticMoE(config, layer_id=layer_idx, **kwargs)
1044
+ self.input_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1045
+ self.post_attention_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1046
+ self.use_deepspeed_implementation = USE_DEEPSPEED_MOE_ARG in kwargs and kwargs[USE_DEEPSPEED_MOE_ARG]
1047
+
1048
+ self.parallel_attn_mlp_res = config.parallel_attn_mlp_res and self.block_sparse_moe.is_moe_layer # add residual only when it is moe layer
1049
+ deepspeed_quantization = kwargs.get(DEEPSPEED_QUANTIZATION_CONFIG)
1050
+ deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG)
1051
+ if self.parallel_attn_mlp_res:
1052
+ self.residual_layernorm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1053
+ self.residual_mlp = ArcticMLP(config,
1054
+ use_deepspeed_implementation=self.use_deepspeed_implementation,
1055
+ is_residual_mlp=True,
1056
+ ds_optimized_quantization_config=deepspeed_quantization,
1057
+ ds_optimized_lora_config=deepspeed_lora,
1058
+ shard_base_weights_if_doing_lora=True) # for the residual layer. always shard the base weight if doing deepspeed lora.
1059
+
1060
+ def forward(
1061
+ self,
1062
+ hidden_states: torch.Tensor,
1063
+ attention_mask: Optional[torch.Tensor] = None,
1064
+ position_ids: Optional[torch.LongTensor] = None,
1065
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1066
+ output_attentions: Optional[bool] = False,
1067
+ use_cache: Optional[bool] = False,
1068
+ **kwargs,
1069
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1070
+ if "padding_mask" in kwargs:
1071
+ warnings.warn(
1072
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1073
+ )
1074
+ """
1075
+ Args:
1076
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1077
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
1078
+ `(batch, sequence_length)` where padding elements are indicated by 0.
1079
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1080
+ output_attentions (`bool`, *optional*):
1081
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1082
+ returned tensors for more detail.
1083
+ use_cache (`bool`, *optional*):
1084
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1085
+ (see `past_key_values`).
1086
+ """
1087
+
1088
+ residual_input = hidden_states
1089
+
1090
+ hidden_states = self.input_layernorm(hidden_states)
1091
+
1092
+ # Self Attention
1093
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1094
+ hidden_states=hidden_states,
1095
+ attention_mask=attention_mask,
1096
+ position_ids=position_ids,
1097
+ past_key_value=past_key_value,
1098
+ output_attentions=output_attentions,
1099
+ use_cache=use_cache,
1100
+ )
1101
+ hidden_states = residual_input + hidden_states
1102
+
1103
+ residual_attn = hidden_states
1104
+
1105
+ if self.parallel_attn_mlp_res:
1106
+ # Note the architecture here is that the MOE layers reads the **pre-attention** input while there is a "normal" transformer residual part.
1107
+ # This is to achieve better parallelization.
1108
+
1109
+ # residual mlp part
1110
+
1111
+ hidden_states = self.residual_layernorm(hidden_states)
1112
+ hidden_states = self.residual_mlp(hidden_states)
1113
+ residual_residual = residual_attn + hidden_states
1114
+ # parallel mlp moe part
1115
+ hidden_states = self.post_attention_layernorm(residual_input) # parallel attn mlp has the same input
1116
+ hidden_states, gate_loss = self.block_sparse_moe(hidden_states)
1117
+ hidden_states = residual_residual + hidden_states
1118
+ else:
1119
+ hidden_states = self.post_attention_layernorm(hidden_states)
1120
+ hidden_states, gate_loss = self.block_sparse_moe(hidden_states)
1121
+ hidden_states = residual_attn + hidden_states
1122
+
1123
+ outputs = (hidden_states,)
1124
+
1125
+ if output_attentions:
1126
+ outputs += (self_attn_weights,)
1127
+
1128
+ if use_cache:
1129
+ outputs += (present_key_value,)
1130
+
1131
+ outputs += (gate_loss,)
1132
+
1133
+ return outputs
1134
+
1135
+
1136
+ ARCTIC_START_DOCSTRING = r"""
1137
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1138
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1139
+ etc.)
1140
+
1141
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1142
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1143
+ and behavior.
1144
+
1145
+ Parameters:
1146
+ config ([`ArcticConfig`]):
1147
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1148
+ load the weights associated with the model, only the configuration. Check out the
1149
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1150
+ """
1151
+
1152
+
1153
+ @add_start_docstrings(
1154
+ "The bare Arctic Model outputting raw hidden-states without any specific head on top.",
1155
+ ARCTIC_START_DOCSTRING,
1156
+ )
1157
+ # Copied from transformers.models.mistral.modeling_mistral.MistralPreTrainedModel with Mistral->Arctic
1158
+ class ArcticPreTrainedModel(PreTrainedModel):
1159
+ config_class = ArcticConfig
1160
+ base_model_prefix = "model"
1161
+ supports_gradient_checkpointing = True
1162
+ _no_split_modules = ["ArcticDecoderLayer"]
1163
+ _skip_keys_device_placement = "past_key_values"
1164
+ _supports_flash_attn_2 = True
1165
+ _supports_sdpa = True
1166
+ _supports_cache_class = True
1167
+
1168
+ def _init_weights(self, module):
1169
+ std = self.config.initializer_range
1170
+ # if is_deepspeed_available():
1171
+ # # TODO(rajhans): remove this once ds has init for quantizedlinear.
1172
+ # try:
1173
+ # from deepspeed.linear.quantization import QuantizedLinear, QuantizedParameter
1174
+ # if isinstance(module, QuantizedLinear):
1175
+ # weights = module.weight.dequantized()
1176
+ # weights.normal_(mean=0.0, std=std)
1177
+ # if module.bias is not None:
1178
+ # module.bias.data.zero_()
1179
+ # module.weight = QuantizedParameter(weights)
1180
+ # module.weight.to(dtype=torch.bfloat16, device=weights.device)
1181
+ # el
1182
+ if isinstance(module, nn.Linear):
1183
+ module.weight.data.normal_(mean=0.0, std=std)
1184
+ if module.bias is not None:
1185
+ module.bias.data.zero_()
1186
+ elif isinstance(module, nn.Embedding):
1187
+ module.weight.data.normal_(mean=0.0, std=std)
1188
+ if module.padding_idx is not None:
1189
+ module.weight.data[module.padding_idx].zero_()
1190
+
1191
+ MIXTRAL_INPUTS_DOCSTRING = r"""
1192
+ Args:
1193
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1194
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1195
+ it.
1196
+
1197
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1198
+ [`PreTrainedTokenizer.__call__`] for details.
1199
+
1200
+ [What are input IDs?](../glossary#input-ids)
1201
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1202
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1203
+
1204
+ - 1 for tokens that are **not masked**,
1205
+ - 0 for tokens that are **masked**.
1206
+
1207
+ [What are attention masks?](../glossary#attention-mask)
1208
+
1209
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1210
+ [`PreTrainedTokenizer.__call__`] for details.
1211
+
1212
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
1213
+ `past_key_values`).
1214
+
1215
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1216
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1217
+ information on the default strategy.
1218
+
1219
+ - 1 indicates the head is **not masked**,
1220
+ - 0 indicates the head is **masked**.
1221
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1222
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1223
+ config.n_positions - 1]`.
1224
+
1225
+ [What are position IDs?](../glossary#position-ids)
1226
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1227
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
1228
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
1229
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1230
+
1231
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1232
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1233
+
1234
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
1235
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
1236
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1237
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1238
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1239
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1240
+ model's internal embedding lookup matrix.
1241
+ use_cache (`bool`, *optional*):
1242
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1243
+ `past_key_values`).
1244
+ output_attentions (`bool`, *optional*):
1245
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1246
+ tensors for more detail.
1247
+ output_hidden_states (`bool`, *optional*):
1248
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1249
+ more detail.
1250
+ return_dict (`bool`, *optional*):
1251
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1252
+ """
1253
+
1254
+
1255
+ @add_start_docstrings(
1256
+ "The bare Arctic Model outputting raw hidden-states without any specific head on top.",
1257
+ ARCTIC_START_DOCSTRING,
1258
+ )
1259
+ # Copied from transformers.models.mistral.modeling_mistral.MistralModel with MISTRAL->MIXTRAL,Mistral->Arctic
1260
+ class ArcticModel(ArcticPreTrainedModel):
1261
+ """
1262
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ArcticDecoderLayer`]
1263
+
1264
+ Args:
1265
+ config: ArcticConfig
1266
+ """
1267
+
1268
+ def __init__(self, config: ArcticConfig, **kwargs):
1269
+ super().__init__(config)
1270
+ self.padding_idx = config.pad_token_id
1271
+ self.vocab_size = config.vocab_size
1272
+
1273
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1274
+ self.layers = nn.ModuleList(
1275
+ [ArcticDecoderLayer(config, layer_idx, **kwargs) for layer_idx in range(config.num_hidden_layers)]
1276
+ )
1277
+ self._attn_implementation = config._attn_implementation
1278
+ self.norm = ArcticRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1279
+
1280
+ self.gradient_checkpointing = False
1281
+ # Initialize weights and apply final processing
1282
+ self.post_init()
1283
+
1284
+ def get_input_embeddings(self):
1285
+ return self.embed_tokens
1286
+
1287
+ def set_input_embeddings(self, value):
1288
+ self.embed_tokens = value
1289
+
1290
+ # Ignore copy
1291
+ @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
1292
+ def forward(
1293
+ self,
1294
+ input_ids: torch.LongTensor = None,
1295
+ attention_mask: Optional[torch.Tensor] = None,
1296
+ position_ids: Optional[torch.LongTensor] = None,
1297
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1298
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1299
+ use_cache: Optional[bool] = None,
1300
+ output_attentions: Optional[bool] = None,
1301
+ output_hidden_states: Optional[bool] = None,
1302
+ return_dict: Optional[bool] = None,
1303
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1304
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1305
+ output_hidden_states = (
1306
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1307
+ )
1308
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1309
+
1310
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1311
+
1312
+ # retrieve input_ids and inputs_embeds
1313
+ if input_ids is not None and inputs_embeds is not None:
1314
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1315
+ elif input_ids is not None:
1316
+ batch_size, seq_length = input_ids.shape
1317
+ elif inputs_embeds is not None:
1318
+ batch_size, seq_length, _ = inputs_embeds.shape
1319
+ else:
1320
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1321
+
1322
+ past_key_values_length = 0
1323
+
1324
+ if self.gradient_checkpointing and self.training:
1325
+ if use_cache:
1326
+ logger.warning_once(
1327
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1328
+ )
1329
+ use_cache = False
1330
+
1331
+ if use_cache:
1332
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1333
+ if use_legacy_cache:
1334
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1335
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1336
+
1337
+ if position_ids is None:
1338
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1339
+ position_ids = torch.arange(
1340
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1341
+ )
1342
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1343
+ else:
1344
+ position_ids = position_ids.view(-1, seq_length).long()
1345
+
1346
+ if inputs_embeds is None:
1347
+ inputs_embeds = self.embed_tokens(input_ids)
1348
+
1349
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1350
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1351
+ if is_padding_right:
1352
+ raise ValueError(
1353
+ "You are attempting to perform batched generation with padding_side='right'"
1354
+ " this may lead to unexpected behaviour for Flash Attention version of Arctic. Make sure to "
1355
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1356
+ )
1357
+
1358
+ if self._attn_implementation == "flash_attention_2":
1359
+ # 2d mask is passed through the layers
1360
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1361
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1362
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1363
+ # the manual implementation that requires a 4D causal mask in all cases.
1364
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1365
+ attention_mask,
1366
+ (batch_size, seq_length),
1367
+ inputs_embeds,
1368
+ past_key_values_length,
1369
+ )
1370
+ else:
1371
+ # 4d mask is passed through the layers
1372
+ attention_mask = _prepare_4d_causal_attention_mask(
1373
+ attention_mask,
1374
+ (batch_size, seq_length),
1375
+ inputs_embeds,
1376
+ past_key_values_length,
1377
+ sliding_window=self.config.sliding_window,
1378
+ )
1379
+
1380
+ hidden_states = inputs_embeds
1381
+
1382
+ # decoder layers
1383
+ all_hidden_states = () if output_hidden_states else None
1384
+ all_self_attns = () if output_attentions else None
1385
+ all_router_losses = ()
1386
+ next_decoder_cache = None
1387
+
1388
+ for i, decoder_layer in enumerate(self.layers):
1389
+ if output_hidden_states:
1390
+ all_hidden_states += (hidden_states,)
1391
+
1392
+ if self.gradient_checkpointing and self.training:
1393
+ layer_outputs = self._gradient_checkpointing_func(
1394
+ decoder_layer.__call__,
1395
+ hidden_states,
1396
+ attention_mask,
1397
+ position_ids,
1398
+ past_key_values,
1399
+ output_attentions,
1400
+ use_cache,
1401
+ )
1402
+ else:
1403
+ layer_outputs = decoder_layer(
1404
+ hidden_states,
1405
+ attention_mask=attention_mask,
1406
+ position_ids=position_ids,
1407
+ past_key_value=past_key_values,
1408
+ output_attentions=output_attentions,
1409
+ use_cache=use_cache,
1410
+ )
1411
+
1412
+ hidden_states = layer_outputs[0]
1413
+
1414
+ if use_cache:
1415
+ if hasattr(layer_outputs[2 if output_attentions else 1], 'to_legacy_cache'):
1416
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1417
+ else:
1418
+ if next_decoder_cache is None:
1419
+ next_decoder_cache = [layer_outputs[2 if output_attentions else 1]]
1420
+ else:
1421
+ next_decoder_cache.append(layer_outputs[2 if output_attentions else 1])
1422
+
1423
+ if output_attentions:
1424
+ all_self_attns += (layer_outputs[1],)
1425
+
1426
+ all_router_losses += (layer_outputs[-1],)
1427
+ hidden_states = self.norm(hidden_states)
1428
+
1429
+ # add hidden states from the last decoder layer
1430
+ if output_hidden_states:
1431
+ all_hidden_states += (hidden_states,)
1432
+
1433
+ next_cache = None
1434
+ if use_cache:
1435
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache and hasattr(next_decoder_cache, 'to_legacy_cache') else next_decoder_cache
1436
+ torch.cuda.empty_cache()
1437
+
1438
+ if not return_dict:
1439
+ return tuple(
1440
+ v
1441
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_losses]
1442
+ if v is not None
1443
+ )
1444
+ return MoeModelOutputWithPast(
1445
+ last_hidden_state=hidden_states,
1446
+ past_key_values=next_cache,
1447
+ hidden_states=all_hidden_states,
1448
+ attentions=all_self_attns,
1449
+ router_logits=all_router_losses,
1450
+ )
1451
+
1452
+ class ArcticForCausalLM(ArcticPreTrainedModel):
1453
+ # TODO(jeffra): update _keys_to_ignore_on_load_unexpected with expert keys not relevant for this rank
1454
+ _keys_to_ignore_on_load_unexpected = [r"model\.layers\.\d+\.block_sparse_moe\.experts\.\d+\.w\d+\.weight"
1455
+ r"model\.layers\.\d+\.block_sparse_moe\.gate\.weight"]
1456
+ _keys_to_ignore_on_load_missing = [r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.experts\.deepspeed_experts\.\d+\.w\d+\.weight",
1457
+ r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.gate\.wg\.weight"]
1458
+ _tied_weights_keys = []#["lm_head.weight"]
1459
+
1460
+ def __init__(self, config, **kwargs):
1461
+ super().__init__(config)
1462
+ self.model = ArcticModel(config, **kwargs)
1463
+ self.vocab_size = config.vocab_size
1464
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1465
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1466
+ self.num_experts = config.num_local_experts
1467
+ self.num_experts_per_tok = config.num_experts_per_tok
1468
+ self.use_deepspeed_moe = kwargs.get(USE_DEEPSPEED_MOE_ARG, False)
1469
+ self.moe_expert_parallel_size = kwargs.get(MOE_EXPERT_PARALLEL_SIZE_ARG, 1)
1470
+ self.is_deepspeed_lora = kwargs.get(DEEPSPEED_LORA_CONFIG) is not None
1471
+ self.gradient_checkpointing = True
1472
+ # self.shard_base_weights_if_doing_lora = kwargs.get("shard_base_weights_if_doing_lora", False)
1473
+ # Initialize weights and apply final processing
1474
+ self.post_init()
1475
+
1476
+ def get_input_embeddings(self):
1477
+ return self.model.embed_tokens
1478
+
1479
+ def set_input_embeddings(self, value):
1480
+ self.model.embed_tokens = value
1481
+
1482
+ def get_output_embeddings(self):
1483
+ return self.lm_head
1484
+
1485
+ def set_output_embeddings(self, new_embeddings):
1486
+ self.lm_head = new_embeddings
1487
+
1488
+ def set_decoder(self, decoder):
1489
+ self.model = decoder
1490
+
1491
+ def get_decoder(self):
1492
+ return self.model
1493
+
1494
+
1495
+ def _expert_number_from_param_name(self, param_name):
1496
+ # example param_name: model.layers.1.block_sparse_moe.experts.10.w1.weight
1497
+ pattern = r'experts\.(\d+)\.'
1498
+ m = re.search(pattern, param_name)
1499
+ if m:
1500
+ return int(m[1])
1501
+ else:
1502
+ return None
1503
+
1504
+ def state_dict(self, *args, **kwargs):
1505
+ state_dict = super().state_dict(*args, **kwargs)
1506
+
1507
+ if not self.use_deepspeed_moe:
1508
+ return state_dict
1509
+
1510
+ # when trying to construct the deepspeed checkpoint we don't want to gather everything
1511
+ if not getattr(self, '_gather_expert_params', False):
1512
+ return state_dict
1513
+
1514
+ rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0
1515
+ world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1
1516
+
1517
+ # non-lora experts
1518
+ pattern = r"model\.layers\.\d+\.block_sparse_moe\.mlp\.deepspeed_moe\.experts\.deepspeed_experts\.\d+\.w\d+\.weight"
1519
+ expert_params = [s for s in state_dict.keys() if re.search(pattern, s)]
1520
+
1521
+ for param_name in expert_params:
1522
+ param_tensor = state_dict[param_name].to('cuda')
1523
+ output = [torch.zeros_like(param_tensor) for _ in range(world_size)]
1524
+ torch.distributed.gather(param_tensor, gather_list=output if rank == 0 else None, dst=0, group=None)
1525
+ # rename from local rank to global rank
1526
+ for gather_rank, gather_param in enumerate(output):
1527
+ experts_per_rank = self.num_experts // self.moe_expert_parallel_size
1528
+ new_expert_number = gather_rank * experts_per_rank + self._expert_number_from_param_name(param_name)
1529
+ new_param_name = re.sub(r'(experts\.)(\d+)(\.)', rf'\g<1>{new_expert_number}\3', param_name)
1530
+ state_dict[new_param_name] = gather_param
1531
+ if rank == 0:
1532
+ print(f"adding to state_dict and renaming: {param_name} -> {new_param_name}")
1533
+
1534
+ # Handle custom LoRA implementation
1535
+ # TODO(rajhans): the part below is untested and shows up when doing lora training. Should not affect inference.
1536
+ if self.is_deepspeed_lora:
1537
+ for param_name in list(state_dict.keys()): # Use list to avoid RuntimeError due to changing size during iteration
1538
+ if param_name.endswith("base_weight"):
1539
+ base_weight = state_dict[param_name].to('cuda')
1540
+
1541
+ # If the base weight is sharded, gather weights from multiple ranks and concatenate
1542
+ # except if the weights are from deespeed_moe which is not sharded (due to EP).
1543
+ if self.shard_base_weights_if_doing_lora and 'deepspeed_moe.experts.deepspeed_experts' not in param_name:
1544
+ gathered_weights = [torch.zeros_like(base_weight,
1545
+ device=base_weight.device, dtype=base_weight.dtype) for _ in range(world_size)]
1546
+ torch.distributed.gather(base_weight, gather_list=gathered_weights if rank == 0 else None, dst=0, group=None)
1547
+ base_weight = torch.cat(gathered_weights, dim=1)
1548
+
1549
+
1550
+ ## The part below is useful if we want to output HF transformer path weights, but commenting it for now
1551
+ # Merge the LoRA weights into the base weights
1552
+ # lora_weight_1 = state_dict.get(param_name.replace("base_weight", "lora_weight_1.weight"))
1553
+ # lora_weight_2 = state_dict.get(param_name.replace("base_weight", "lora_weight_2.weight"))
1554
+ # if lora_weight_1 is not None and lora_weight_2 is not None:
1555
+ # lora_weights = torch.matmul(lora_weight_2, lora_weight_1)
1556
+ # base_weight += lora_weights
1557
+ # else:
1558
+ # raise ValueError
1559
+
1560
+ # # Rename the base weight to weight
1561
+ # new_param_name = param_name.replace("base_weight", "weight")
1562
+ # state_dict[new_param_name] = base_weight
1563
+
1564
+ # Remove the base weight from the state dict
1565
+ # del state_dict[param_name]
1566
+ return state_dict
1567
+
1568
+
1569
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
1570
+ if not self.use_deepspeed_moe:
1571
+ return super()._load_from_state_dict(
1572
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
1573
+ )
1574
+
1575
+ world_size = torch.distributed.get_world_size() if torch.distributed.is_initialized() else 1
1576
+ #TODO(jeffra): currently assumes fine-tuning only on one node, fix for world_size != ep size
1577
+ if self.moe_expert_parallel_size > 1:
1578
+ assert self.moe_expert_parallel_size == world_size, \
1579
+ f"currently only support expert parallel size equal to world size but {self.moe_expert_parallel_size=} and {world_size=}"
1580
+
1581
+ rank = torch.distributed.get_rank() if torch.distributed.is_initialized() else 0
1582
+ num_local_experts = self.num_experts // self.moe_expert_parallel_size
1583
+ local_expert_range = range(num_local_experts * rank, num_local_experts * rank + num_local_experts)
1584
+
1585
+ # no deepspeed
1586
+ # model.layers.1.block_sparse_moe.experts.10.w1.weight
1587
+ # model.layers.1.block_sparse_moe.gate.weight
1588
+ # w. deepspeed
1589
+ # model.layers.1.block_sparse_moe.mlp.deepspeed_moe.gate.wg.weight
1590
+ # model.layers.1.block_sparse_moe.mlp.deepspeed_moe.experts.deepspeed_experts.10.w1.weight
1591
+
1592
+ gate_pattern = r'model\.layers\.\d+\.block_sparse_moe\.gate\.weight'
1593
+
1594
+ expert_params_to_keep = []
1595
+ expert_params_to_remove = []
1596
+ gate_params = []
1597
+ for param_name in state_dict.keys():
1598
+ expert_number = self._expert_number_from_param_name(param_name)
1599
+ if expert_number is not None:
1600
+ if expert_number in local_expert_range:
1601
+ expert_params_to_keep.append(param_name)
1602
+ else:
1603
+ expert_params_to_remove.append(param_name)
1604
+ elif re.search(gate_pattern, param_name):
1605
+ gate_params.append(param_name)
1606
+
1607
+ # drop all experts in the state_dict that we don't need locally
1608
+ for param_name in expert_params_to_remove:
1609
+ print(f'{rank=} dropping {param_name}')
1610
+ del state_dict[param_name]
1611
+
1612
+ # rename remaining experts to align with the local config
1613
+ for param_name in expert_params_to_keep:
1614
+ # adjust expert number wrt expert parallelism
1615
+ new_expert_number = self._expert_number_from_param_name(param_name) % num_local_experts
1616
+ new_param_name = re.sub(r'(experts\.)(\d+)(\.)', rf'\g<1>{new_expert_number}\3', param_name)
1617
+
1618
+ # use deepspeed moe param path
1619
+ split_param_name = new_param_name.split('.')
1620
+ idx = split_param_name.index('experts')
1621
+ ds_moe_path = "mlp.deepspeed_moe.experts.deepspeed_experts".split('.')
1622
+ new_param_name = split_param_name[0:idx] + ds_moe_path + split_param_name[idx+1:]
1623
+ new_param_name = ".".join(new_param_name)
1624
+
1625
+ print(f'Deepspeed {rank=}, renaming {param_name} -> {new_param_name}')
1626
+ state_dict[new_param_name] = state_dict.pop(param_name)
1627
+
1628
+ # rename gate params
1629
+ ds_suffix = "mlp.deepspeed_moe.gate.wg.weight".split('.')
1630
+ for param_name in gate_params:
1631
+ new_param_name = '.'.join(param_name.split('.')[:4] + ds_suffix)
1632
+ print(f'Gating: {rank=}, renaming {param_name} -> {new_param_name}')
1633
+ state_dict[new_param_name] = state_dict.pop(param_name)
1634
+
1635
+ # If deepspeed lora is enabled, then we need to rename weight to base_weight.
1636
+ # Furthermore, if the base_weight is sharded, we need to shard each weight and select the slice of local rank.
1637
+ if self.is_deepspeed_lora:
1638
+ local_state_dict = self.state_dict()
1639
+ for param_name in local_state_dict:
1640
+ if not param_name.endswith("base_weight"):
1641
+ continue
1642
+
1643
+ incoming_param_name = param_name.replace("base_weight", "weight")
1644
+ if incoming_param_name not in state_dict:
1645
+ continue
1646
+
1647
+ incoming_param = state_dict[incoming_param_name]
1648
+
1649
+ shape_local = local_state_dict[param_name].shape
1650
+ shape_incoming = incoming_param.shape
1651
+ if 'deepspeed_moe' in incoming_param_name:
1652
+ assert shape_local == shape_incoming, "deepspeed moe weights are never sharded"
1653
+ else:
1654
+ assert shape_incoming[1] == shape_local[1] * world_size, "weights should be sharded equally across world size"
1655
+ incoming_param = incoming_param[:, rank*shape_local[1]: (rank+1)*shape_local[1]]
1656
+ print(f'Deepspeed lora: {rank=}, renaming {incoming_param_name} -> {param_name}')
1657
+ state_dict[param_name] = incoming_param
1658
+ del state_dict[incoming_param_name]
1659
+
1660
+ return super()._load_from_state_dict(
1661
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
1662
+ )
1663
+
1664
+ @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
1665
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1666
+ # Ignore copy
1667
+ def forward(
1668
+ self,
1669
+ input_ids: torch.LongTensor = None,
1670
+ attention_mask: Optional[torch.Tensor] = None,
1671
+ position_ids: Optional[torch.LongTensor] = None,
1672
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1673
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1674
+ labels: Optional[torch.LongTensor] = None,
1675
+ use_cache: Optional[bool] = None,
1676
+ output_attentions: Optional[bool] = None,
1677
+ output_hidden_states: Optional[bool] = None,
1678
+ return_dict: Optional[bool] = None,
1679
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1680
+ r"""
1681
+ Args:
1682
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1683
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1684
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1685
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1686
+
1687
+ Returns:
1688
+
1689
+ Example:
1690
+
1691
+ ```python
1692
+ >>> from transformers import AutoTokenizer, ArcticForCausalLM
1693
+
1694
+ >>> model = ArcticForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1695
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1696
+
1697
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1698
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1699
+
1700
+ >>> # Generate
1701
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1702
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1703
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1704
+ ```"""
1705
+
1706
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1707
+
1708
+ output_hidden_states = (
1709
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1710
+ )
1711
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1712
+
1713
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1714
+ outputs = self.model(
1715
+ input_ids=input_ids,
1716
+ attention_mask=attention_mask,
1717
+ position_ids=position_ids,
1718
+ past_key_values=past_key_values,
1719
+ inputs_embeds=inputs_embeds,
1720
+ use_cache=use_cache,
1721
+ output_attentions=output_attentions,
1722
+ output_hidden_states=output_hidden_states,
1723
+ return_dict=return_dict,
1724
+ )
1725
+ hidden_states = outputs[0]
1726
+ logits = self.lm_head(hidden_states)
1727
+ logits = logits.float()
1728
+
1729
+ loss = None
1730
+ if labels is not None:
1731
+ # Shift so that tokens < n predict n
1732
+ shift_logits = logits[..., :-1, :].contiguous()
1733
+ shift_labels = labels[..., 1:].contiguous()
1734
+ # Flatten the tokens
1735
+ loss_fct = CrossEntropyLoss()
1736
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1737
+ shift_labels = shift_labels.view(-1)
1738
+ # Enable model parallelism
1739
+ shift_labels = shift_labels.to(shift_logits.device)
1740
+ loss = loss_fct(shift_logits, shift_labels)
1741
+
1742
+ # Move to same device for model parallelism.
1743
+ aux_loss = sum([out.to(logits.device) for out in outputs[-1]])
1744
+ if labels is not None:
1745
+ loss += self.router_aux_loss_coef * aux_loss
1746
+
1747
+ if not return_dict:
1748
+ output = (logits,) + outputs[1:]
1749
+ # torch.distributed.barrier()
1750
+ return (loss,) + output if loss is not None else output
1751
+
1752
+ return MoeCausalLMOutputWithPast(
1753
+ loss=loss,
1754
+ aux_loss=aux_loss,
1755
+ logits=logits,
1756
+ past_key_values=outputs.past_key_values,
1757
+ hidden_states=outputs.hidden_states,
1758
+ attentions=outputs.attentions,
1759
+ )
1760
+
1761
+ def prepare_inputs_for_generation(
1762
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1763
+ ):
1764
+ # Omit tokens covered by past_key_values
1765
+ if past_key_values is not None:
1766
+ if isinstance(past_key_values, Cache):
1767
+ cache_length = past_key_values.get_seq_length()
1768
+ past_length = past_key_values.seen_tokens
1769
+ max_cache_length = past_key_values.get_max_length()
1770
+ else:
1771
+ cache_length = past_length = past_key_values[0][0].shape[2]
1772
+ max_cache_length = None
1773
+
1774
+ # Keep only the unprocessed tokens:
1775
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1776
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1777
+ # input)
1778
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1779
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1780
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1781
+ # input_ids based on the past_length.
1782
+ elif past_length < input_ids.shape[1]:
1783
+ input_ids = input_ids[:, past_length:]
1784
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1785
+
1786
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1787
+ if (
1788
+ max_cache_length is not None
1789
+ and attention_mask is not None
1790
+ and cache_length + input_ids.shape[1] > max_cache_length
1791
+ ):
1792
+ attention_mask = attention_mask[:, -max_cache_length:]
1793
+
1794
+ position_ids = kwargs.get("position_ids", None)
1795
+ if attention_mask is not None and position_ids is None:
1796
+ # create position_ids on the fly for batch generation
1797
+ position_ids = attention_mask.long().cumsum(-1) - 1
1798
+ position_ids.masked_fill_(attention_mask == 0, 1)
1799
+ if past_key_values:
1800
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1801
+
1802
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1803
+ if inputs_embeds is not None and past_key_values is None:
1804
+ model_inputs = {"inputs_embeds": inputs_embeds}
1805
+ else:
1806
+ model_inputs = {"input_ids": input_ids}
1807
+
1808
+ model_inputs.update(
1809
+ {
1810
+ "position_ids": position_ids,
1811
+ "past_key_values": past_key_values,
1812
+ "use_cache": kwargs.get("use_cache"),
1813
+ "attention_mask": attention_mask,
1814
+ }
1815
+ )
1816
+ return model_inputs
1817
+
1818
+ @staticmethod
1819
+ def _reorder_cache(past_key_values, beam_idx):
1820
+ reordered_past = ()
1821
+ for layer_past in past_key_values:
1822
+ reordered_past += (
1823
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1824
+ )
1825
+ return reordered_past
1826
+
1827
+
1828
+ @add_start_docstrings(
1829
+ """
1830
+ The Arctic Model transformer with a sequence classification head on top (linear layer).
1831
+
1832
+ [`ArcticForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1833
+ (e.g. GPT-2) do.
1834
+
1835
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1836
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1837
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1838
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1839
+ each row of the batch).
1840
+ """,
1841
+ ARCTIC_START_DOCSTRING,
1842
+ )
1843
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Arctic, LLAMA->MIXTRAL
1844
+ class ArcticForSequenceClassification(ArcticPreTrainedModel):
1845
+ def __init__(self, config):
1846
+ super().__init__(config)
1847
+ self.num_labels = config.num_labels
1848
+ self.model = ArcticModel(config)
1849
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1850
+
1851
+ # Initialize weights and apply final processing
1852
+ self.post_init()
1853
+
1854
+ def get_input_embeddings(self):
1855
+ return self.model.embed_tokens
1856
+
1857
+ def set_input_embeddings(self, value):
1858
+ self.model.embed_tokens = value
1859
+
1860
+ @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
1861
+ def forward(
1862
+ self,
1863
+ input_ids: torch.LongTensor = None,
1864
+ attention_mask: Optional[torch.Tensor] = None,
1865
+ position_ids: Optional[torch.LongTensor] = None,
1866
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1867
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1868
+ labels: Optional[torch.LongTensor] = None,
1869
+ use_cache: Optional[bool] = None,
1870
+ output_attentions: Optional[bool] = None,
1871
+ output_hidden_states: Optional[bool] = None,
1872
+ return_dict: Optional[bool] = None,
1873
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1874
+ r"""
1875
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1876
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1877
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1878
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1879
+ """
1880
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1881
+
1882
+ transformer_outputs = self.model(
1883
+ input_ids,
1884
+ attention_mask=attention_mask,
1885
+ position_ids=position_ids,
1886
+ past_key_values=past_key_values,
1887
+ inputs_embeds=inputs_embeds,
1888
+ use_cache=use_cache,
1889
+ output_attentions=output_attentions,
1890
+ output_hidden_states=output_hidden_states,
1891
+ return_dict=return_dict,
1892
+ )
1893
+ hidden_states = transformer_outputs[0]
1894
+ logits = self.score(hidden_states)
1895
+
1896
+ if input_ids is not None:
1897
+ batch_size = input_ids.shape[0]
1898
+ else:
1899
+ batch_size = inputs_embeds.shape[0]
1900
+
1901
+ if self.config.pad_token_id is None and batch_size != 1:
1902
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1903
+ if self.config.pad_token_id is None:
1904
+ sequence_lengths = -1
1905
+ else:
1906
+ if input_ids is not None:
1907
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1908
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1909
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1910
+ sequence_lengths = sequence_lengths.to(logits.device)
1911
+ else:
1912
+ sequence_lengths = -1
1913
+
1914
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1915
+
1916
+ loss = None
1917
+ if labels is not None:
1918
+ labels = labels.to(logits.device)
1919
+ if self.config.problem_type is None:
1920
+ if self.num_labels == 1:
1921
+ self.config.problem_type = "regression"
1922
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1923
+ self.config.problem_type = "single_label_classification"
1924
+ else:
1925
+ self.config.problem_type = "multi_label_classification"
1926
+
1927
+ if self.config.problem_type == "regression":
1928
+ loss_fct = MSELoss()
1929
+ if self.num_labels == 1:
1930
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1931
+ else:
1932
+ loss = loss_fct(pooled_logits, labels)
1933
+ elif self.config.problem_type == "single_label_classification":
1934
+ loss_fct = CrossEntropyLoss()
1935
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1936
+ elif self.config.problem_type == "multi_label_classification":
1937
+ loss_fct = BCEWithLogitsLoss()
1938
+ loss = loss_fct(pooled_logits, labels)
1939
+ if not return_dict:
1940
+ output = (pooled_logits,) + transformer_outputs[1:]
1941
+ return ((loss,) + output) if loss is not None else output
1942
+
1943
+ return SequenceClassifierOutputWithPast(
1944
+ loss=loss,
1945
+ logits=pooled_logits,
1946
+ past_key_values=transformer_outputs.past_key_values,
1947
+ hidden_states=transformer_outputs.hidden_states,
1948
+ attentions=transformer_outputs.attentions,
1949
+ )
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": true,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": true,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
+ },
30
+ "auto_map": {
31
+ "AutoTokenizer": ["tokenization_arctic.ArcticTokenizer", null]
32
+ },
33
+ "bos_token": "<s>",
34
+ "clean_up_tokenization_spaces": false,
35
+ "eos_token": "</s>",
36
+ "model_max_length": 4096,
37
+ "pad_token": null,
38
+ "sp_model_kwargs": {},
39
+ "tokenizer_class": "ArcticTokenizer",
40
+ "unk_token": "<unk>",
41
+ "use_default_system_prompt": false
42
+ }