jeffra tomaarsen HF staff commited on
Commit
f4ca790
1 Parent(s): 7fb7fdc

Add Arctic modeling/config/tokenization files (#3)

Browse files

- Add Arctic modeling/config/tokenization files (2af13d229ef34519e40d05fcadb390e0e25c0a2f)
- Update AutoTokenizer path (ecca7ac97dd6c7365a5c65f61868101d7c624659)
- Revert extraneous tokenizer config changes (f9281b708c4e07b2348d2f7d71a9816d32eca8a4)


Co-authored-by: Tom Aarsen <tomaarsen@users.noreply.huggingface.co>

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