Text Generation
Transformers
PyTorch
English
Chinese
llama
custom_code
GeneZC commited on
Commit
86bf66c
1 Parent(s): 4313419

Upload 6 files

Browse files
config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "MiniMix-2/4x3B",
3
+ "architectures": [
4
+ "MinimixForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoModelForCausalLM": "modeling_minimix.MinimixForCausalLM"
8
+ },
9
+ "num_experts": 4,
10
+ "bos_token_id": 1,
11
+ "eos_token_id": 2,
12
+ "hidden_act": "silu",
13
+ "hidden_size": 3072,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 8192,
16
+ "max_position_embeddings": 4096,
17
+ "model_type": "llama",
18
+ "num_attention_heads": 24,
19
+ "num_hidden_layers": 24,
20
+ "num_key_value_heads": 24,
21
+ "pad_token_id": 0,
22
+ "pretraining_tp": 1,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_scaling": null,
25
+ "rope_theta": 10000.0,
26
+ "tie_word_embeddings": false,
27
+ "torch_dtype": "float16",
28
+ "transformers_version": "4.33.2",
29
+ "use_cache": true,
30
+ "vocab_size": 49216
31
+ }
modeling_minimix.py ADDED
@@ -0,0 +1,1484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI 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 MiniMix model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import CrossEntropyLoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from transformers.models.llama.configuration_llama import LlamaConfig
52
+
53
+
54
+ if is_flash_attn_2_available():
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+
59
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
60
+ # It means that the function will not be traced through and simply appear as a node in the graph.
61
+ if is_torch_fx_available():
62
+ if not is_torch_greater_or_equal_than_1_13:
63
+ import torch.fx
64
+
65
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
66
+
67
+
68
+ logger = logging.get_logger(__name__)
69
+
70
+ _CONFIG_FOR_DOC = "LlamaConfig"
71
+
72
+
73
+ def _get_unpad_data(attention_mask):
74
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
75
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
76
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
77
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
78
+ return (
79
+ indices,
80
+ cu_seqlens,
81
+ max_seqlen_in_batch,
82
+ )
83
+
84
+
85
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
86
+ warnings.warn(
87
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
88
+ )
89
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
90
+
91
+
92
+ def _make_causal_mask(
93
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
94
+ ):
95
+ warnings.warn(
96
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
97
+ )
98
+ return AttentionMaskConverter._make_causal_mask(
99
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
100
+ )
101
+
102
+
103
+ class MinimixRMSNorm(nn.Module):
104
+ def __init__(self, hidden_size, eps=1e-6):
105
+ """
106
+ MinimixRMSNorm is equivalent to T5LayerNorm
107
+ """
108
+ super().__init__()
109
+ self.weight = nn.Parameter(torch.ones(hidden_size))
110
+ self.variance_epsilon = eps
111
+
112
+ def forward(self, hidden_states):
113
+ input_dtype = hidden_states.dtype
114
+ hidden_states = hidden_states.to(torch.float32)
115
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
116
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
117
+ return self.weight * hidden_states.to(input_dtype)
118
+
119
+
120
+ ALL_LAYERNORM_LAYERS.append(MinimixRMSNorm)
121
+
122
+
123
+ class MinimixRotaryEmbedding(nn.Module):
124
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
125
+ super().__init__()
126
+
127
+ self.dim = dim
128
+ self.max_position_embeddings = max_position_embeddings
129
+ self.base = base
130
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
131
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
132
+
133
+ # Build here to make `torch.jit.trace` work.
134
+ self._set_cos_sin_cache(
135
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
136
+ )
137
+
138
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
139
+ self.max_seq_len_cached = seq_len
140
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
141
+
142
+ freqs = torch.outer(t, self.inv_freq)
143
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
146
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
147
+
148
+ def forward(self, x, seq_len=None):
149
+ # x: [bs, num_attention_heads, seq_len, head_size]
150
+ if seq_len > self.max_seq_len_cached:
151
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
152
+
153
+ return (
154
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
155
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
156
+ )
157
+
158
+
159
+ class MinimixLinearScalingRotaryEmbedding(MinimixRotaryEmbedding):
160
+ """MinimixRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
161
+
162
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
163
+ self.scaling_factor = scaling_factor
164
+ super().__init__(dim, max_position_embeddings, base, device)
165
+
166
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
167
+ self.max_seq_len_cached = seq_len
168
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
169
+ t = t / self.scaling_factor
170
+
171
+ freqs = torch.outer(t, self.inv_freq)
172
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
173
+ emb = torch.cat((freqs, freqs), dim=-1)
174
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
175
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
176
+
177
+
178
+ class MinimixDynamicNTKScalingRotaryEmbedding(MinimixRotaryEmbedding):
179
+ """MinimixRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
180
+
181
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
182
+ self.scaling_factor = scaling_factor
183
+ super().__init__(dim, max_position_embeddings, base, device)
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+
188
+ if seq_len > self.max_position_embeddings:
189
+ base = self.base * (
190
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
191
+ ) ** (self.dim / (self.dim - 2))
192
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
193
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
194
+
195
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
196
+
197
+ freqs = torch.outer(t, self.inv_freq)
198
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
199
+ emb = torch.cat((freqs, freqs), dim=-1)
200
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
201
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
202
+
203
+
204
+ def rotate_half(x):
205
+ """Rotates half the hidden dims of the input."""
206
+ x1 = x[..., : x.shape[-1] // 2]
207
+ x2 = x[..., x.shape[-1] // 2 :]
208
+ return torch.cat((-x2, x1), dim=-1)
209
+
210
+
211
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
212
+ """Applies Rotary Position Embedding to the query and key tensors.
213
+
214
+ Args:
215
+ q (`torch.Tensor`): The query tensor.
216
+ k (`torch.Tensor`): The key tensor.
217
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
218
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
219
+ position_ids (`torch.Tensor`):
220
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
221
+ used to pass offsetted position ids when working with a KV-cache.
222
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
223
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
224
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
225
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
226
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
227
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
228
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
229
+ Returns:
230
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
231
+ """
232
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
233
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
234
+ q_embed = (q * cos) + (rotate_half(q) * sin)
235
+ k_embed = (k * cos) + (rotate_half(k) * sin)
236
+ return q_embed, k_embed
237
+
238
+
239
+ class MinimixMLP(nn.Module):
240
+ def __init__(self, config):
241
+ super().__init__()
242
+ self.config = config
243
+ self.hidden_size = config.hidden_size
244
+ self.intermediate_size = config.intermediate_size
245
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
246
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
247
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
248
+ self.act_fn = ACT2FN[config.hidden_act]
249
+
250
+ def forward(self, x):
251
+ if self.config.pretraining_tp > 1:
252
+ slice = self.intermediate_size // self.config.pretraining_tp
253
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
254
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
255
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
256
+
257
+ gate_proj = torch.cat(
258
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
259
+ )
260
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
261
+
262
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
263
+ down_proj = [
264
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
265
+ ]
266
+ down_proj = sum(down_proj)
267
+ else:
268
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
269
+
270
+ return down_proj
271
+
272
+
273
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
274
+ """
275
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
276
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
277
+ """
278
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
279
+ if n_rep == 1:
280
+ return hidden_states
281
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
282
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
283
+
284
+
285
+ class MinimixAttention(nn.Module):
286
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
287
+
288
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
289
+ super().__init__()
290
+ self.config = config
291
+ self.layer_idx = layer_idx
292
+ if layer_idx is None:
293
+ logger.warning_once(
294
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
295
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
296
+ "when creating this class."
297
+ )
298
+
299
+ self.attention_dropout = config.attention_dropout
300
+ self.hidden_size = config.hidden_size
301
+ self.num_heads = config.num_attention_heads
302
+ self.head_dim = self.hidden_size // self.num_heads
303
+ self.num_key_value_heads = config.num_key_value_heads
304
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
305
+ self.max_position_embeddings = config.max_position_embeddings
306
+ self.rope_theta = config.rope_theta
307
+ self.is_causal = True
308
+
309
+ if (self.head_dim * self.num_heads) != self.hidden_size:
310
+ raise ValueError(
311
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
312
+ f" and `num_heads`: {self.num_heads})."
313
+ )
314
+
315
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
316
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
317
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
318
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
319
+ self._init_rope()
320
+
321
+ def _init_rope(self):
322
+ if self.config.rope_scaling is None:
323
+ self.rotary_emb = MinimixRotaryEmbedding(
324
+ self.head_dim,
325
+ max_position_embeddings=self.max_position_embeddings,
326
+ base=self.rope_theta,
327
+ )
328
+ else:
329
+ scaling_type = self.config.rope_scaling["type"]
330
+ scaling_factor = self.config.rope_scaling["factor"]
331
+ if scaling_type == "linear":
332
+ self.rotary_emb = MinimixLinearScalingRotaryEmbedding(
333
+ self.head_dim,
334
+ max_position_embeddings=self.max_position_embeddings,
335
+ scaling_factor=scaling_factor,
336
+ base=self.rope_theta,
337
+ )
338
+ elif scaling_type == "dynamic":
339
+ self.rotary_emb = MinimixDynamicNTKScalingRotaryEmbedding(
340
+ self.head_dim,
341
+ max_position_embeddings=self.max_position_embeddings,
342
+ scaling_factor=scaling_factor,
343
+ base=self.rope_theta,
344
+ )
345
+ else:
346
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
347
+
348
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
349
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
350
+
351
+ def forward(
352
+ self,
353
+ hidden_states: torch.Tensor,
354
+ attention_mask: Optional[torch.Tensor] = None,
355
+ position_ids: Optional[torch.LongTensor] = None,
356
+ past_key_value: Optional[Cache] = None,
357
+ output_attentions: bool = False,
358
+ use_cache: bool = False,
359
+ **kwargs,
360
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
361
+ if "padding_mask" in kwargs:
362
+ warnings.warn(
363
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
364
+ )
365
+
366
+ bsz, q_len, _ = hidden_states.size()
367
+
368
+ if self.config.pretraining_tp > 1:
369
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
370
+ query_slices = self.q_proj.weight.split(
371
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
372
+ )
373
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
374
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
375
+
376
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
377
+ query_states = torch.cat(query_states, dim=-1)
378
+
379
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
380
+ key_states = torch.cat(key_states, dim=-1)
381
+
382
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
383
+ value_states = torch.cat(value_states, dim=-1)
384
+
385
+ else:
386
+ query_states = self.q_proj(hidden_states)
387
+ key_states = self.k_proj(hidden_states)
388
+ value_states = self.v_proj(hidden_states)
389
+
390
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
391
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
392
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
393
+
394
+ kv_seq_len = key_states.shape[-2]
395
+ if past_key_value is not None:
396
+ if self.layer_idx is None:
397
+ raise ValueError(
398
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
399
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
400
+ "with a layer index."
401
+ )
402
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
403
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
404
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
405
+
406
+ if past_key_value is not None:
407
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
408
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
409
+
410
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
411
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
412
+
413
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
414
+
415
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
416
+ raise ValueError(
417
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
418
+ f" {attn_weights.size()}"
419
+ )
420
+
421
+ if attention_mask is not None:
422
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
423
+ raise ValueError(
424
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
425
+ )
426
+ attn_weights = attn_weights + attention_mask
427
+
428
+ # upcast attention to fp32
429
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
430
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
431
+ attn_output = torch.matmul(attn_weights, value_states)
432
+
433
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
434
+ raise ValueError(
435
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
436
+ f" {attn_output.size()}"
437
+ )
438
+
439
+ attn_output = attn_output.transpose(1, 2).contiguous()
440
+
441
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
442
+
443
+ if self.config.pretraining_tp > 1:
444
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
445
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
446
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
447
+ else:
448
+ attn_output = self.o_proj(attn_output)
449
+
450
+ if not output_attentions:
451
+ attn_weights = None
452
+
453
+ return attn_output, attn_weights, past_key_value
454
+
455
+
456
+ class MinimixFlashAttention2(MinimixAttention):
457
+ """
458
+ Minimix flash attention module. This module inherits from `MinimixAttention` 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
+ def __init__(self, *args, **kwargs):
464
+ super().__init__(*args, **kwargs)
465
+
466
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
467
+ # 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.
468
+ # 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).
469
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
470
+
471
+ def forward(
472
+ self,
473
+ hidden_states: torch.Tensor,
474
+ attention_mask: Optional[torch.LongTensor] = None,
475
+ position_ids: Optional[torch.LongTensor] = None,
476
+ past_key_value: Optional[Cache] = None,
477
+ output_attentions: bool = False,
478
+ use_cache: bool = False,
479
+ **kwargs,
480
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
481
+ # MinimixFlashAttention2 attention does not support output_attentions
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
+
490
+ output_attentions = False
491
+
492
+ bsz, q_len, _ = hidden_states.size()
493
+
494
+ query_states = self.q_proj(hidden_states)
495
+ key_states = self.k_proj(hidden_states)
496
+ value_states = self.v_proj(hidden_states)
497
+
498
+ # Flash attention requires the input to have the shape
499
+ # batch_size x seq_length x head_dim x hidden_dim
500
+ # therefore we just need to keep the original shape
501
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
502
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
503
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
504
+
505
+ kv_seq_len = key_states.shape[-2]
506
+ if past_key_value is not None:
507
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
508
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
509
+
510
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
511
+
512
+ if past_key_value is not None:
513
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
514
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
515
+
516
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
517
+ # to be able to avoid many of these transpose/reshape/view.
518
+ query_states = query_states.transpose(1, 2)
519
+ key_states = key_states.transpose(1, 2)
520
+ value_states = value_states.transpose(1, 2)
521
+
522
+ dropout_rate = self.attention_dropout if self.training else 0.0
523
+
524
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
525
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
526
+ # cast them back in the correct dtype just to be sure everything works as expected.
527
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
528
+ # in fp32. (MinimixRMSNorm handles it correctly)
529
+
530
+ input_dtype = query_states.dtype
531
+ if input_dtype == torch.float32:
532
+ # Handle the case where the model is quantized
533
+ if hasattr(self.config, "_pre_quantization_dtype"):
534
+ target_dtype = self.config._pre_quantization_dtype
535
+ else:
536
+ target_dtype = self.q_proj.weight.dtype
537
+
538
+ logger.warning_once(
539
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
540
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
541
+ f" {target_dtype}."
542
+ )
543
+
544
+ query_states = query_states.to(target_dtype)
545
+ key_states = key_states.to(target_dtype)
546
+ value_states = value_states.to(target_dtype)
547
+
548
+ attn_output = self._flash_attention_forward(
549
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
550
+ )
551
+
552
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
553
+ attn_output = self.o_proj(attn_output)
554
+
555
+ if not output_attentions:
556
+ attn_weights = None
557
+
558
+ return attn_output, attn_weights, past_key_value
559
+
560
+ def _flash_attention_forward(
561
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
562
+ ):
563
+ """
564
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
565
+ first unpad the input, then computes the attention scores and pad the final attention scores.
566
+
567
+ Args:
568
+ query_states (`torch.Tensor`):
569
+ Input query states to be passed to Flash Attention API
570
+ key_states (`torch.Tensor`):
571
+ Input key states to be passed to Flash Attention API
572
+ value_states (`torch.Tensor`):
573
+ Input value states to be passed to Flash Attention API
574
+ attention_mask (`torch.Tensor`):
575
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
576
+ position of padding tokens and 1 for the position of non-padding tokens.
577
+ dropout (`int`, *optional*):
578
+ Attention dropout
579
+ softmax_scale (`float`, *optional*):
580
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
581
+ """
582
+ if not self._flash_attn_uses_top_left_mask:
583
+ causal = self.is_causal
584
+ else:
585
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in MinimixFlashAttention2 __init__.
586
+ causal = self.is_causal and query_length != 1
587
+
588
+ # Contains at least one padding token in the sequence
589
+ if attention_mask is not None:
590
+ batch_size = query_states.shape[0]
591
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
592
+ query_states, key_states, value_states, attention_mask, query_length
593
+ )
594
+
595
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
596
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
597
+
598
+ attn_output_unpad = flash_attn_varlen_func(
599
+ query_states,
600
+ key_states,
601
+ value_states,
602
+ cu_seqlens_q=cu_seqlens_q,
603
+ cu_seqlens_k=cu_seqlens_k,
604
+ max_seqlen_q=max_seqlen_in_batch_q,
605
+ max_seqlen_k=max_seqlen_in_batch_k,
606
+ dropout_p=dropout,
607
+ softmax_scale=softmax_scale,
608
+ causal=causal,
609
+ )
610
+
611
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
612
+ else:
613
+ attn_output = flash_attn_func(
614
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
615
+ )
616
+
617
+ return attn_output
618
+
619
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
620
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
621
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
622
+
623
+ key_layer = index_first_axis(
624
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
625
+ )
626
+ value_layer = index_first_axis(
627
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
628
+ )
629
+ if query_length == kv_seq_len:
630
+ query_layer = index_first_axis(
631
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
632
+ )
633
+ cu_seqlens_q = cu_seqlens_k
634
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
635
+ indices_q = indices_k
636
+ elif query_length == 1:
637
+ max_seqlen_in_batch_q = 1
638
+ cu_seqlens_q = torch.arange(
639
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
640
+ ) # There is a memcpy here, that is very bad.
641
+ indices_q = cu_seqlens_q[:-1]
642
+ query_layer = query_layer.squeeze(1)
643
+ else:
644
+ # The -q_len: slice assumes left padding.
645
+ attention_mask = attention_mask[:, -query_length:]
646
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
647
+
648
+ return (
649
+ query_layer,
650
+ key_layer,
651
+ value_layer,
652
+ indices_q,
653
+ (cu_seqlens_q, cu_seqlens_k),
654
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
655
+ )
656
+
657
+
658
+ class MinimixSdpaAttention(MinimixAttention):
659
+ """
660
+ Minimix attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
661
+ `MinimixAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
662
+ SDPA API.
663
+ """
664
+
665
+ # Adapted from MinimixAttention.forward
666
+ def forward(
667
+ self,
668
+ hidden_states: torch.Tensor,
669
+ attention_mask: Optional[torch.Tensor] = None,
670
+ position_ids: Optional[torch.LongTensor] = None,
671
+ past_key_value: Optional[Cache] = None,
672
+ output_attentions: bool = False,
673
+ use_cache: bool = False,
674
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
675
+ if output_attentions:
676
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
677
+ logger.warning_once(
678
+ "MinimixModel is using MinimixSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
679
+ '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.'
680
+ )
681
+ return super().forward(
682
+ hidden_states=hidden_states,
683
+ attention_mask=attention_mask,
684
+ position_ids=position_ids,
685
+ past_key_value=past_key_value,
686
+ output_attentions=output_attentions,
687
+ use_cache=use_cache,
688
+ )
689
+
690
+ bsz, q_len, _ = hidden_states.size()
691
+
692
+ query_states = self.q_proj(hidden_states)
693
+ key_states = self.k_proj(hidden_states)
694
+ value_states = self.v_proj(hidden_states)
695
+
696
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
697
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
698
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
699
+
700
+ kv_seq_len = key_states.shape[-2]
701
+ if past_key_value is not None:
702
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
703
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
704
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
705
+
706
+ if past_key_value is not None:
707
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
708
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
709
+
710
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
711
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
712
+
713
+ if attention_mask is not None:
714
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
715
+ raise ValueError(
716
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
717
+ )
718
+
719
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
720
+ query_states,
721
+ key_states,
722
+ value_states,
723
+ attn_mask=attention_mask,
724
+ dropout_p=self.attention_dropout if self.training else 0.0,
725
+ # 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.
726
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
727
+ )
728
+
729
+ attn_output = attn_output.transpose(1, 2).contiguous()
730
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
731
+
732
+ attn_output = self.o_proj(attn_output)
733
+
734
+ return attn_output, None, past_key_value
735
+
736
+
737
+ LLAMA_ATTENTION_CLASSES = {
738
+ "eager": MinimixAttention,
739
+ "flash_attention_2": MinimixFlashAttention2,
740
+ "sdpa": MinimixSdpaAttention,
741
+ }
742
+
743
+
744
+ # MoE adapted from https://github.com/microsoft/DeepSpeed/blob/v0.12.4/deepspeed/moe.
745
+ # einsum rewrites are on par or more performant
746
+ # switch can be bubbled up in future
747
+ USE_EINSUM = True
748
+
749
+ # einsum dimensions: (g)roup, (s)equence, (e)xpert, (m)odel, (c)apacity
750
+ # See https://arxiv.org/pdf/2006.16668.pdf for details.
751
+ def einsum(rule, a, b):
752
+ if USE_EINSUM:
753
+ return torch.einsum(rule, a, b)
754
+ elif rule == 's,se->se':
755
+ return a.reshape(a.shape[0], -1) * b
756
+ elif rule == 'se,sc->sec':
757
+ return a.unsqueeze(2) * b.unsqueeze(1)
758
+ elif rule == 'se,se->s':
759
+ return torch.bmm(a.unsqueeze(1), b.unsqueeze(2)).reshape(-1)
760
+ elif rule == 'sec,sm->ecm':
761
+ s = a.shape[0]
762
+ e = a.shape[1]
763
+ c = a.shape[2]
764
+ m = b.shape[1]
765
+ return torch.matmul(a.reshape(s, -1).t(), b).reshape(e, c, m)
766
+ elif rule == 'sec,ecm->sm':
767
+ return torch.matmul(a.reshape(a.shape[0], -1), b.reshape(-1, b.shape[-1]))
768
+ elif rule == 'ks,ksm->sm':
769
+ k = b.shape[0]
770
+ s = b.shape[1]
771
+ m = b.shape[2]
772
+ # [k, s] -> [s, k] -> [s, 1, k]
773
+ a = a.t().unsqueeze(1)
774
+ # [k,s,m] -> [k, sm] -> [sm, k] -> [s, m, k]
775
+ b = b.reshape(k, -1).t().reshape(s, m, k)
776
+ # bmm([s, 1, k], [s, m, k]^t) -> [s, m, 1]
777
+ return torch.bmm(a, b.transpose(1, 2)).squeeze(2)
778
+ else:
779
+ return torch.einsum(rule, a, b)
780
+
781
+ from tutel import moe as tutel_moe
782
+
783
+ class DeepSpeedMoELayer(nn.Module):
784
+ def __init__(self, gate, experts, num_experts):
785
+ super().__init__()
786
+ self.gate = gate
787
+ self.experts = experts
788
+ self.num_experts = num_experts
789
+
790
+ def forward(self, input):
791
+ # Implement Algorithm 2 from GShard paper.
792
+ d_model = input.shape[-1]
793
+
794
+ # Initial implementation -> Reshape into S tokens by dropping sequence dimension.
795
+ reshaped_input = input.reshape(-1, d_model)
796
+
797
+ self.l_aux, C, E, indices_, locations_, gates_, self.exp_counts = self.gate(reshaped_input)
798
+ S, M = reshaped_input.size(0), reshaped_input.size(1)
799
+ if not hasattr(self, '_tutel_dispatcher'):
800
+ self._tutel_dispatcher = tutel_moe.fast_dispatcher(E, C, M, dispatch_dtype=reshaped_input.dtype)
801
+ self._tutel_dispatcher.update(indices_, locations_, gates_, capacity=C)
802
+ dispatched_input = self._tutel_dispatcher.encode(reshaped_input)
803
+ # self.l_aux, combine_weights, dispatch_mask, self.exp_counts = self.gate(reshaped_input)
804
+ # dispatched_input = einsum("sec,sm->ecm", dispatch_mask.type_as(input[0]), reshaped_input)
805
+
806
+ dispatched_input = dispatched_input.unsqueeze(0) # Mimic the distributed behavior with `ep_size=1`.
807
+ expert_output = self.experts(dispatched_input)
808
+ expert_output = expert_output.squeeze(0) # Mimic the distributed behavior with `ep_size=1`.
809
+
810
+ combined_output = self._tutel_dispatcher.decode(expert_output.view(E * C, M))
811
+ # combined_output = einsum("sec,ecm->sm", combine_weights.type_as(input[0]), expert_output)
812
+
813
+ a = combined_output.reshape(input.shape)
814
+ return a
815
+
816
+
817
+ @torch.jit.script
818
+ def _top_idx(source, k):
819
+ return torch.topk(source, k=k, dim=0)[1]
820
+
821
+ @torch.jit.script
822
+ def _one_hot_to_float(x, num_classes):
823
+ return F.one_hot(x, num_classes=num_classes).float()
824
+
825
+ def top1gating(logits):
826
+ # everything is in fp32 in this function
827
+ gates = F.softmax(logits, dim=1)
828
+
829
+ # Create a mask for 1st's expert per token
830
+ # noisy gating
831
+ indices1_s = torch.argmax(gates, dim=1)
832
+ num_experts = int(gates.shape[1])
833
+ mask1 = F.one_hot(indices1_s, num_classes=num_experts)
834
+
835
+ # gating decisions
836
+ exp_counts = torch.sum(mask1, dim=0).detach().to('cpu')
837
+
838
+ # we don't want to drop any tokens
839
+ capacity = torch.max(exp_counts).to(logits.device)
840
+
841
+ # Compute l_aux
842
+ me = torch.mean(gates, dim=0)
843
+ ce = torch.mean(mask1.float(), dim=0)
844
+ l_aux = torch.sum(me * ce) * num_experts
845
+
846
+ top_idx = _top_idx(mask1, capacity)
847
+
848
+ new_mask1 = mask1 * torch.zeros_like(mask1).scatter_(0, top_idx, 1)
849
+ mask1 = new_mask1
850
+
851
+ # Tutel doesn't support index values masked with zero
852
+ # so we need to replace masked indices with -1
853
+ indices_mask = mask1.sum(dim=1) * num_experts - 1
854
+ indices1_s = torch.min(indices1_s, indices_mask)
855
+ locations1 = tutel_moe.fast_cumsum_sub_one(mask1)
856
+ # locations1 = torch.cumsum(mask1, dim=0) - 1
857
+
858
+ gates1_s = (gates * mask1).sum(dim=1)
859
+ locations1_s = torch.sum(locations1 * mask1, dim=1)
860
+ return l_aux, capacity, num_experts, [
861
+ indices1_s,
862
+ ], [
863
+ locations1_s,
864
+ ], [
865
+ gates1_s,
866
+ ], exp_counts
867
+
868
+ # # Store the capacity location for each token
869
+ # locations1_s = torch.sum(locations1 * mask1, dim=1)
870
+
871
+ # # Normalize gate probabilities
872
+ # mask1_float = mask1.float()
873
+ # gates = gates * mask1_float
874
+
875
+ # locations1_sc = _one_hot_to_float(locations1_s, capacity)
876
+ # combine_weights = einsum("se,sc->sec", gates, locations1_sc)
877
+
878
+ # dispatch_mask = combine_weights.bool()
879
+
880
+ # return l_aux, combine_weights, dispatch_mask, exp_counts
881
+
882
+ class TopKGate(nn.Module):
883
+ wg: torch.nn.Linear
884
+
885
+ def __init__(self, model_dim, num_experts):
886
+ super().__init__()
887
+ self.wg = torch.nn.Linear(model_dim, num_experts, bias=False).float()
888
+ self.num_experts = num_experts
889
+
890
+ def forward(self, input):
891
+ if self.wg.weight.dtype != torch.float32:
892
+ self.wg = self.wg.float()
893
+
894
+ input_fp32 = input.float()
895
+
896
+ logits = self.wg(input_fp32)
897
+
898
+ gate_output = top1gating(logits)
899
+
900
+ return gate_output
901
+
902
+
903
+ import copy
904
+
905
+ class DeepSpeedExperts(nn.Module):
906
+ def __init__(self, expert, num_experts):
907
+ super().__init__()
908
+ self.deepspeed_experts = nn.ModuleList([copy.deepcopy(expert) for i in range(num_experts)])
909
+ self.num_experts = num_experts
910
+
911
+ def forward(self, inputs):
912
+ chunks = inputs.chunk(self.num_experts, dim=1)
913
+ expert_outputs = []
914
+ for chunk, expert in zip(chunks, self.deepspeed_experts):
915
+ out = expert(chunk)
916
+ if type(out) is tuple:
917
+ out = out[0] # Ignore the bias term for now
918
+ expert_outputs += [out]
919
+
920
+ expert_output = torch.cat(expert_outputs, dim=1)
921
+ return expert_output
922
+
923
+
924
+ class DeepSpeedMoE(nn.Module):
925
+ def __init__(self, hidden_size, expert, num_experts=1):
926
+ super().__init__()
927
+ self.num_experts = num_experts
928
+ gate = TopKGate(hidden_size, num_experts)
929
+ experts = DeepSpeedExperts(expert, num_experts)
930
+ self.deepspeed_moe = DeepSpeedMoELayer(gate, experts, num_experts)
931
+
932
+ def forward(self, hidden_states):
933
+ output = self.deepspeed_moe(hidden_states)
934
+ return output, self.deepspeed_moe.l_aux, self.deepspeed_moe.exp_counts
935
+
936
+
937
+ class MinimixDecoderLayer(nn.Module):
938
+ def __init__(self, config: LlamaConfig, layer_idx: int):
939
+ super().__init__()
940
+ self.hidden_size = config.hidden_size
941
+
942
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
943
+
944
+ mlp = MinimixMLP(config)
945
+
946
+ self.half_experts = layer_idx < int(config.num_hidden_layers / 4)
947
+ self.mlp = DeepSpeedMoE(
948
+ hidden_size=self.hidden_size,
949
+ expert=mlp,
950
+ num_experts=int(config.num_experts / 2) if self.half_experts else config.num_experts
951
+ )
952
+
953
+ self.input_layernorm = MinimixRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
954
+ self.post_attention_layernorm = MinimixRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
955
+
956
+ def forward(
957
+ self,
958
+ hidden_states: torch.Tensor,
959
+ attention_mask: Optional[torch.Tensor] = None,
960
+ position_ids: Optional[torch.LongTensor] = None,
961
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
962
+ output_attentions: Optional[bool] = False,
963
+ use_cache: Optional[bool] = False,
964
+ **kwargs,
965
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
966
+ """
967
+ Args:
968
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
969
+ attention_mask (`torch.FloatTensor`, *optional*):
970
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
971
+ query_sequence_length, key_sequence_length)` if default attention is used.
972
+ output_attentions (`bool`, *optional*):
973
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
974
+ returned tensors for more detail.
975
+ use_cache (`bool`, *optional*):
976
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
977
+ (see `past_key_values`).
978
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
979
+ """
980
+ if "padding_mask" in kwargs:
981
+ warnings.warn(
982
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
983
+ )
984
+
985
+ residual = hidden_states
986
+
987
+ hidden_states = self.input_layernorm(hidden_states)
988
+
989
+ # Self Attention
990
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
991
+ hidden_states=hidden_states,
992
+ attention_mask=attention_mask,
993
+ position_ids=position_ids,
994
+ past_key_value=past_key_value,
995
+ output_attentions=output_attentions,
996
+ use_cache=use_cache,
997
+ **kwargs,
998
+ )
999
+ hidden_states = residual + hidden_states
1000
+
1001
+ # Fully Connected
1002
+ residual = hidden_states
1003
+ hidden_states = self.post_attention_layernorm(hidden_states)
1004
+ hidden_states, load_balancing_loss, tokens_per_expert = self.mlp(hidden_states)
1005
+ hidden_states = residual + hidden_states
1006
+
1007
+ outputs = (hidden_states,)
1008
+
1009
+ if output_attentions:
1010
+ outputs += (self_attn_weights,)
1011
+
1012
+ if use_cache:
1013
+ outputs += (present_key_value,)
1014
+
1015
+ return outputs
1016
+
1017
+
1018
+ LLAMA_START_DOCSTRING = r"""
1019
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1020
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1021
+ etc.)
1022
+
1023
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1024
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1025
+ and behavior.
1026
+
1027
+ Parameters:
1028
+ config ([`LlamaConfig`]):
1029
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1030
+ load the weights associated with the model, only the configuration. Check out the
1031
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1032
+ """
1033
+
1034
+
1035
+ @add_start_docstrings(
1036
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1037
+ LLAMA_START_DOCSTRING,
1038
+ )
1039
+ class MinimixPreTrainedModel(PreTrainedModel):
1040
+ config_class = LlamaConfig
1041
+ base_model_prefix = "model"
1042
+ supports_gradient_checkpointing = True
1043
+ _no_split_modules = ["MinimixDecoderLayer"]
1044
+ _skip_keys_device_placement = "past_key_values"
1045
+ _supports_flash_attn_2 = True
1046
+ _supports_sdpa = True
1047
+ _supports_cache_class = True
1048
+
1049
+ def _init_weights(self, module):
1050
+ std = self.config.initializer_range
1051
+ if isinstance(module, nn.Linear):
1052
+ module.weight.data.normal_(mean=0.0, std=std)
1053
+ if module.bias is not None:
1054
+ module.bias.data.zero_()
1055
+ elif isinstance(module, nn.Embedding):
1056
+ module.weight.data.normal_(mean=0.0, std=std)
1057
+ if module.padding_idx is not None:
1058
+ module.weight.data[module.padding_idx].zero_()
1059
+
1060
+
1061
+ LLAMA_INPUTS_DOCSTRING = r"""
1062
+ Args:
1063
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1064
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1065
+ it.
1066
+
1067
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1068
+ [`PreTrainedTokenizer.__call__`] for details.
1069
+
1070
+ [What are input IDs?](../glossary#input-ids)
1071
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1072
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1073
+
1074
+ - 1 for tokens that are **not masked**,
1075
+ - 0 for tokens that are **masked**.
1076
+
1077
+ [What are attention masks?](../glossary#attention-mask)
1078
+
1079
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1080
+ [`PreTrainedTokenizer.__call__`] for details.
1081
+
1082
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1083
+ `past_key_values`).
1084
+
1085
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1086
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1087
+ information on the default strategy.
1088
+
1089
+ - 1 indicates the head is **not masked**,
1090
+ - 0 indicates the head is **masked**.
1091
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1092
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1093
+ config.n_positions - 1]`.
1094
+
1095
+ [What are position IDs?](../glossary#position-ids)
1096
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1097
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1098
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1099
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1100
+
1101
+ Two formats are allowed:
1102
+ - a [`~cache_utils.Cache`] instance;
1103
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1104
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1105
+ cache format.
1106
+
1107
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1108
+ legacy cache format will be returned.
1109
+
1110
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1111
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1112
+ of shape `(batch_size, sequence_length)`.
1113
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1114
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1115
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1116
+ model's internal embedding lookup matrix.
1117
+ use_cache (`bool`, *optional*):
1118
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1119
+ `past_key_values`).
1120
+ output_attentions (`bool`, *optional*):
1121
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1122
+ tensors for more detail.
1123
+ output_hidden_states (`bool`, *optional*):
1124
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1125
+ more detail.
1126
+ return_dict (`bool`, *optional*):
1127
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1128
+ """
1129
+
1130
+
1131
+ @add_start_docstrings(
1132
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1133
+ LLAMA_START_DOCSTRING,
1134
+ )
1135
+ class MinimixModel(MinimixPreTrainedModel):
1136
+ """
1137
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MinimixDecoderLayer`]
1138
+
1139
+ Args:
1140
+ config: LlamaConfig
1141
+ """
1142
+
1143
+ def __init__(self, config: LlamaConfig):
1144
+ super().__init__(config)
1145
+ self.padding_idx = config.pad_token_id
1146
+ self.vocab_size = config.vocab_size
1147
+
1148
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1149
+ self.layers = nn.ModuleList(
1150
+ [MinimixDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1151
+ )
1152
+ self._use_sdpa = config._attn_implementation == "sdpa"
1153
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1154
+ self.norm = MinimixRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1155
+
1156
+ self.gradient_checkpointing = False
1157
+ # Initialize weights and apply final processing
1158
+ self.post_init()
1159
+
1160
+ def get_input_embeddings(self):
1161
+ return self.embed_tokens
1162
+
1163
+ def set_input_embeddings(self, value):
1164
+ self.embed_tokens = value
1165
+
1166
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1167
+ def forward(
1168
+ self,
1169
+ input_ids: torch.LongTensor = None,
1170
+ attention_mask: Optional[torch.Tensor] = None,
1171
+ position_ids: Optional[torch.LongTensor] = None,
1172
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1173
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1174
+ use_cache: Optional[bool] = None,
1175
+ output_attentions: Optional[bool] = None,
1176
+ output_hidden_states: Optional[bool] = None,
1177
+ return_dict: Optional[bool] = None,
1178
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1179
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1180
+ output_hidden_states = (
1181
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1182
+ )
1183
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1184
+
1185
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1186
+
1187
+ # retrieve input_ids and inputs_embeds
1188
+ if input_ids is not None and inputs_embeds is not None:
1189
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1190
+ elif input_ids is not None:
1191
+ batch_size, seq_length = input_ids.shape[:2]
1192
+ elif inputs_embeds is not None:
1193
+ batch_size, seq_length = inputs_embeds.shape[:2]
1194
+ else:
1195
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1196
+
1197
+ if self.gradient_checkpointing and self.training:
1198
+ if use_cache:
1199
+ logger.warning_once(
1200
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1201
+ )
1202
+ use_cache = False
1203
+
1204
+ past_key_values_length = 0
1205
+ if use_cache:
1206
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1207
+ if use_legacy_cache:
1208
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1209
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1210
+
1211
+ if position_ids is None:
1212
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1213
+ position_ids = torch.arange(
1214
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1215
+ )
1216
+ position_ids = position_ids.unsqueeze(0)
1217
+
1218
+ if inputs_embeds is None:
1219
+ inputs_embeds = self.embed_tokens(input_ids)
1220
+
1221
+ if self._use_flash_attention_2:
1222
+ # 2d mask is passed through the layers
1223
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1224
+ elif self._use_sdpa and not output_attentions:
1225
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1226
+ # the manual implementation that requires a 4D causal mask in all cases.
1227
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1228
+ attention_mask,
1229
+ (batch_size, seq_length),
1230
+ inputs_embeds,
1231
+ past_key_values_length,
1232
+ )
1233
+ else:
1234
+ # 4d mask is passed through the layers
1235
+ attention_mask = _prepare_4d_causal_attention_mask(
1236
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1237
+ )
1238
+
1239
+ # embed positions
1240
+ hidden_states = inputs_embeds
1241
+
1242
+ # decoder layers
1243
+ all_hidden_states = () if output_hidden_states else None
1244
+ all_self_attns = () if output_attentions else None
1245
+ next_decoder_cache = None
1246
+
1247
+ for decoder_layer in self.layers:
1248
+ if output_hidden_states:
1249
+ all_hidden_states += (hidden_states,)
1250
+
1251
+ if self.gradient_checkpointing and self.training:
1252
+ layer_outputs = self._gradient_checkpointing_func(
1253
+ decoder_layer.__call__,
1254
+ hidden_states,
1255
+ attention_mask,
1256
+ position_ids,
1257
+ past_key_values,
1258
+ output_attentions,
1259
+ use_cache,
1260
+ )
1261
+ else:
1262
+ layer_outputs = decoder_layer(
1263
+ hidden_states,
1264
+ attention_mask=attention_mask,
1265
+ position_ids=position_ids,
1266
+ past_key_value=past_key_values,
1267
+ output_attentions=output_attentions,
1268
+ use_cache=use_cache,
1269
+ )
1270
+
1271
+ hidden_states = layer_outputs[0]
1272
+
1273
+ if use_cache:
1274
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1275
+
1276
+ if output_attentions:
1277
+ all_self_attns += (layer_outputs[1],)
1278
+
1279
+ hidden_states = self.norm(hidden_states)
1280
+
1281
+ # add hidden states from the last decoder layer
1282
+ if output_hidden_states:
1283
+ all_hidden_states += (hidden_states,)
1284
+
1285
+ next_cache = None
1286
+ if use_cache:
1287
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1288
+ if not return_dict:
1289
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1290
+ return BaseModelOutputWithPast(
1291
+ last_hidden_state=hidden_states,
1292
+ past_key_values=next_cache,
1293
+ hidden_states=all_hidden_states,
1294
+ attentions=all_self_attns,
1295
+ )
1296
+
1297
+
1298
+ class MinimixForCausalLM(MinimixPreTrainedModel):
1299
+ _tied_weights_keys = ["lm_head.weight"]
1300
+
1301
+ def __init__(self, config):
1302
+ super().__init__(config)
1303
+ self.model = MinimixModel(config)
1304
+ self.vocab_size = config.vocab_size
1305
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1306
+
1307
+ # Initialize weights and apply final processing
1308
+ self.post_init()
1309
+
1310
+ def get_input_embeddings(self):
1311
+ return self.model.embed_tokens
1312
+
1313
+ def set_input_embeddings(self, value):
1314
+ self.model.embed_tokens = value
1315
+
1316
+ def get_output_embeddings(self):
1317
+ return self.lm_head
1318
+
1319
+ def set_output_embeddings(self, new_embeddings):
1320
+ self.lm_head = new_embeddings
1321
+
1322
+ def set_decoder(self, decoder):
1323
+ self.model = decoder
1324
+
1325
+ def get_decoder(self):
1326
+ return self.model
1327
+
1328
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1329
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1330
+ def forward(
1331
+ self,
1332
+ input_ids: torch.LongTensor = None,
1333
+ attention_mask: Optional[torch.Tensor] = None,
1334
+ position_ids: Optional[torch.LongTensor] = None,
1335
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1336
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1337
+ labels: Optional[torch.LongTensor] = None,
1338
+ use_cache: Optional[bool] = None,
1339
+ output_attentions: Optional[bool] = None,
1340
+ output_hidden_states: Optional[bool] = None,
1341
+ return_dict: Optional[bool] = None,
1342
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1343
+ r"""
1344
+ Args:
1345
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1346
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1347
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1348
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1349
+
1350
+ Returns:
1351
+
1352
+ Example:
1353
+
1354
+ ```python
1355
+ >>> from transformers import AutoTokenizer, MinimixForCausalLM
1356
+
1357
+ >>> model = MinimixForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1358
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1359
+
1360
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1361
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1362
+
1363
+ >>> # Generate
1364
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1365
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1366
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1367
+ ```"""
1368
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1369
+ output_hidden_states = (
1370
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1371
+ )
1372
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1373
+
1374
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1375
+ outputs = self.model(
1376
+ input_ids=input_ids,
1377
+ attention_mask=attention_mask,
1378
+ position_ids=position_ids,
1379
+ past_key_values=past_key_values,
1380
+ inputs_embeds=inputs_embeds,
1381
+ use_cache=use_cache,
1382
+ output_attentions=output_attentions,
1383
+ output_hidden_states=output_hidden_states,
1384
+ return_dict=return_dict,
1385
+ )
1386
+
1387
+ hidden_states = outputs[0]
1388
+ if self.config.pretraining_tp > 1:
1389
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1390
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1391
+ logits = torch.cat(logits, dim=-1)
1392
+ else:
1393
+ logits = self.lm_head(hidden_states)
1394
+ logits = logits.float()
1395
+
1396
+ loss = None
1397
+ if labels is not None:
1398
+ # Shift so that tokens < n predict n
1399
+ shift_logits = logits[..., :-1, :].contiguous()
1400
+ shift_labels = labels[..., 1:].contiguous()
1401
+ # Flatten the tokens
1402
+ loss_fct = CrossEntropyLoss()
1403
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1404
+ shift_labels = shift_labels.view(-1)
1405
+ # Enable model parallelism
1406
+ shift_labels = shift_labels.to(shift_logits.device)
1407
+ loss = loss_fct(shift_logits, shift_labels)
1408
+
1409
+ if not return_dict:
1410
+ output = (logits,) + outputs[1:]
1411
+ return (loss,) + output if loss is not None else output
1412
+
1413
+ return CausalLMOutputWithPast(
1414
+ loss=loss,
1415
+ logits=logits,
1416
+ past_key_values=outputs.past_key_values,
1417
+ hidden_states=outputs.hidden_states,
1418
+ attentions=outputs.attentions,
1419
+ )
1420
+
1421
+ def prepare_inputs_for_generation(
1422
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1423
+ ):
1424
+ if past_key_values is not None:
1425
+ if isinstance(past_key_values, Cache):
1426
+ cache_length = past_key_values.get_seq_length()
1427
+ past_length = past_key_values.seen_tokens
1428
+ max_cache_length = past_key_values.get_max_length()
1429
+ else:
1430
+ cache_length = past_length = past_key_values[0][0].shape[2]
1431
+ max_cache_length = None
1432
+
1433
+ # Keep only the unprocessed tokens:
1434
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1435
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1436
+ # input)
1437
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1438
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1439
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1440
+ # input_ids based on the past_length.
1441
+ elif past_length < input_ids.shape[1]:
1442
+ input_ids = input_ids[:, past_length:]
1443
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1444
+
1445
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1446
+ if (
1447
+ max_cache_length is not None
1448
+ and attention_mask is not None
1449
+ and cache_length + input_ids.shape[1] > max_cache_length
1450
+ ):
1451
+ attention_mask = attention_mask[:, -max_cache_length:]
1452
+
1453
+ position_ids = kwargs.get("position_ids", None)
1454
+ if attention_mask is not None and position_ids is None:
1455
+ # create position_ids on the fly for batch generation
1456
+ position_ids = attention_mask.long().cumsum(-1) - 1
1457
+ position_ids.masked_fill_(attention_mask == 0, 1)
1458
+ if past_key_values:
1459
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1460
+
1461
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1462
+ if inputs_embeds is not None and past_key_values is None:
1463
+ model_inputs = {"inputs_embeds": inputs_embeds}
1464
+ else:
1465
+ model_inputs = {"input_ids": input_ids}
1466
+
1467
+ model_inputs.update(
1468
+ {
1469
+ "position_ids": position_ids,
1470
+ "past_key_values": past_key_values,
1471
+ "use_cache": kwargs.get("use_cache"),
1472
+ "attention_mask": attention_mask,
1473
+ }
1474
+ )
1475
+ return model_inputs
1476
+
1477
+ @staticmethod
1478
+ def _reorder_cache(past_key_values, beam_idx):
1479
+ reordered_past = ()
1480
+ for layer_past in past_key_values:
1481
+ reordered_past += (
1482
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1483
+ )
1484
+ return reordered_past
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b94155514b815089d8aabce1c430eda98bdbbdf565d5f5bc02e43472555410e8
3
+ size 15101259818
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae87c0db2b21b0fa3fdc5e19d1f9cea94efb703cc7c6281d8718a6714b3cc2be
3
+ size 748869
tokenizer_config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "</s>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "legacy": null,
22
+ "model_max_length": 1000000000000000019884624838656,
23
+ "pad_token": null,
24
+ "sp_model_kwargs": {},
25
+ "spaces_between_special_tokens": false,
26
+ "tokenizer_class": "LlamaTokenizer",
27
+ "unk_token": {
28
+ "__type": "AddedToken",
29
+ "content": "<unk>",
30
+ "lstrip": false,
31
+ "normalized": true,
32
+ "rstrip": false,
33
+ "single_word": false
34
+ },
35
+ "use_default_system_prompt": true,
36
+ "use_fast": true
37
+ }