Text Generation
Transformers
PyTorch
tinymixtral
conversational
custom_code
mikecovlee commited on
Commit
c6e33a9
·
verified ·
1 Parent(s): 93f020d

Upload checkpoint on step 0177557

Browse files
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael Lee (李登淳)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
chat_template.jinja ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% for message in messages %}
2
+ {% if message['role'] == 'user' %}
3
+ {{ '<|user|>
4
+ ' + message['content'] + eos_token }}
5
+ {% elif message['role'] == 'system' %}
6
+ {{ '<|system|>
7
+ ' + message['content'] + eos_token }}
8
+ {% elif message['role'] == 'assistant' %}
9
+ {{ '<|assistant|>
10
+ ' + message['content'] + eos_token }}
11
+ {% endif %}
12
+ {% if loop.last and add_generation_prompt %}
13
+ {{ '<|assistant|>' }}
14
+ {% endif %}
15
+ {% endfor %}
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TinyMixtralForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "dtype": "float32",
7
+ "expert_intermediate_size": 2389,
8
+ "head_dim": 64,
9
+ "hidden_size": 896,
10
+ "initializer_range": 0.02,
11
+ "max_position_embeddings": 2048,
12
+ "model_type": "tinymixtral",
13
+ "num_attention_heads": 14,
14
+ "num_experts_per_tok": 2,
15
+ "num_hidden_layers": 10,
16
+ "num_key_value_heads": 2,
17
+ "num_local_experts": 6,
18
+ "rms_norm_eps": 1e-06,
19
+ "rope_theta": 1000000.0,
20
+ "router_aux_loss_coef": 0.01,
21
+ "router_jitter_noise": 0.01,
22
+ "transformers_version": "4.57.3",
23
+ "vocab_size": 32000,
24
+ "auto_map": {
25
+ "AutoConfig": "configuration_tinymixtral.TinyMixtralConfig",
26
+ "AutoModelForCausalLM": "modeling_tinymixtral.TinyMixtralForCausalLM"
27
+ }
28
+ }
configuration_tinymixtral.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) Michael Lee (李登淳) 2026. All rights reserved.
2
+ # Open-source under the MIT License. See LICENSE for details.
3
+
4
+ from transformers import PretrainedConfig
5
+
6
+
7
+ class TinyMixtralConfig(PretrainedConfig):
8
+ model_type = "tinymixtral"
9
+
10
+ def __init__(
11
+ self,
12
+ vocab_size: int = 32000,
13
+ hidden_size: int = 896,
14
+ num_hidden_layers: int = 10,
15
+ num_attention_heads: int = 14,
16
+ num_key_value_heads: int = 2,
17
+ head_dim: int = 64,
18
+ max_position_embeddings: int = 2048,
19
+ num_local_experts: int = 6,
20
+ num_experts_per_tok: int = 2,
21
+ expert_intermediate_size: int = 2389,
22
+ router_aux_loss_coef: float = 0.01,
23
+ router_jitter_noise: float = 0.01,
24
+ rms_norm_eps: float = 1e-6,
25
+ rope_theta: float = 1_000_000.0,
26
+ attention_dropout: float = 0.0,
27
+ tie_word_embeddings: bool = True,
28
+ initializer_range: float = 0.02,
29
+ **kwargs,
30
+ ):
31
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
32
+ self.vocab_size = vocab_size
33
+ self.hidden_size = hidden_size
34
+ self.num_hidden_layers = num_hidden_layers
35
+ self.num_attention_heads = num_attention_heads
36
+ self.num_key_value_heads = num_key_value_heads
37
+ self.head_dim = head_dim
38
+ self.max_position_embeddings = max_position_embeddings
39
+ self.num_local_experts = num_local_experts
40
+ self.num_experts_per_tok = num_experts_per_tok
41
+ self.expert_intermediate_size = expert_intermediate_size
42
+ self.router_aux_loss_coef = router_aux_loss_coef
43
+ self.router_jitter_noise = router_jitter_noise
44
+ self.rms_norm_eps = rms_norm_eps
45
+ self.rope_theta = rope_theta
46
+ self.attention_dropout = attention_dropout
47
+ self.initializer_range = initializer_range
modeling_tinymixtral.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) Michael Lee (李登淳) 2026. All rights reserved.
2
+ # Open-source under the MIT License. See LICENSE for details.
3
+
4
+ from dataclasses import dataclass
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from torch.utils.checkpoint import checkpoint
11
+ from transformers import PreTrainedModel
12
+
13
+ from .configuration_tinymixtral import TinyMixtralConfig
14
+
15
+
16
+ # ============================================================
17
+ # Layers
18
+ # ============================================================
19
+
20
+ class RMSNorm(nn.Module):
21
+ def __init__(self, dim: int, eps: float = 1e-6):
22
+ super().__init__()
23
+ self.weight = nn.Parameter(torch.ones(dim))
24
+ self.eps = eps
25
+
26
+ def forward(self, x):
27
+ dtype = x.dtype
28
+ x = x.float()
29
+ norm = x.pow(2).mean(-1, keepdim=True)
30
+ x = x * torch.rsqrt(norm + self.eps)
31
+ return (x * self.weight).to(dtype)
32
+
33
+
34
+ class RotaryEmbedding(nn.Module):
35
+ def __init__(self, dim, max_position_embeddings=2048, theta=10000.0):
36
+ super().__init__()
37
+ self.dim = dim
38
+ self.max_position_embeddings = max_position_embeddings
39
+ self.theta = theta
40
+ self._build_cache()
41
+
42
+ def _build_cache(self):
43
+ inv_freq = 1.0 / (self.theta ** (torch.arange(0, self.dim, 2).float() / self.dim))
44
+ t = torch.arange(self.max_position_embeddings).float()
45
+ freqs = torch.outer(t, inv_freq)
46
+ emb = torch.cat((freqs, freqs), dim=-1)
47
+ self.register_buffer("cos_cached", emb.cos(), persistent=False)
48
+ self.register_buffer("sin_cached", emb.sin(), persistent=False)
49
+
50
+ def forward(self, x, position_ids):
51
+ cos = self.cos_cached[position_ids].unsqueeze(1)
52
+ sin = self.sin_cached[position_ids].unsqueeze(1)
53
+ x_rot = x.float()
54
+ x1, x2 = x_rot.chunk(2, dim=-1)
55
+ rotated = torch.cat((-x2, x1), dim=-1)
56
+ return (x_rot * cos + rotated * sin).to(x.dtype)
57
+
58
+
59
+ class GQAAttention(nn.Module):
60
+ def __init__(self, config):
61
+ super().__init__()
62
+ self.hidden_size = config.hidden_size
63
+ self.num_heads = config.num_attention_heads
64
+ self.num_kv_heads = config.num_key_value_heads
65
+ self.head_dim = config.head_dim
66
+ self.num_groups = self.num_heads // self.num_kv_heads
67
+ assert self.num_heads % self.num_kv_heads == 0
68
+
69
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
70
+ self.k_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
71
+ self.v_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
72
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
73
+ self.rotary_emb = RotaryEmbedding(self.head_dim, config.max_position_embeddings, config.rope_theta)
74
+ self.attention_dropout = config.attention_dropout
75
+
76
+ def forward(self, hidden_states, attention_mask=None, position_ids=None):
77
+ B, S, _ = hidden_states.shape
78
+ q = self.q_proj(hidden_states).view(B, S, self.num_heads, self.head_dim).transpose(1, 2)
79
+ k = self.k_proj(hidden_states).view(B, S, self.num_kv_heads, self.head_dim).transpose(1, 2)
80
+ v = self.v_proj(hidden_states).view(B, S, self.num_kv_heads, self.head_dim).transpose(1, 2)
81
+ k = k.unsqueeze(2).expand(-1, -1, self.num_groups, -1, -1).reshape(B, self.num_heads, S, self.head_dim)
82
+ v = v.unsqueeze(2).expand(-1, -1, self.num_groups, -1, -1).reshape(B, self.num_heads, S, self.head_dim)
83
+ if position_ids is None:
84
+ position_ids = torch.arange(S, device=hidden_states.device).unsqueeze(0).expand(B, -1)
85
+ q, k = self.rotary_emb(q, position_ids), self.rotary_emb(k, position_ids)
86
+
87
+ if attention_mask is not None:
88
+ causal = torch.tril(torch.ones(S, S, device=hidden_states.device, dtype=torch.bool))
89
+ combined = causal[None, None, :, :] & attention_mask[:, None, None, :]
90
+ attn = F.scaled_dot_product_attention(
91
+ q, k, v, attn_mask=combined,
92
+ dropout_p=self.attention_dropout if self.training else 0.0,
93
+ is_causal=False,
94
+ )
95
+ else:
96
+ attn = F.scaled_dot_product_attention(
97
+ q, k, v, attn_mask=None,
98
+ dropout_p=self.attention_dropout if self.training else 0.0,
99
+ is_causal=True,
100
+ )
101
+ return self.o_proj(attn.transpose(1, 2).reshape(B, S, -1))
102
+
103
+
104
+ class SparseMoE(nn.Module):
105
+ def __init__(self, config):
106
+ super().__init__()
107
+ self.hidden_size = config.hidden_size
108
+ self.num_experts = config.num_local_experts
109
+ self.top_k = config.num_experts_per_tok
110
+ self.expert_intermediate = config.expert_intermediate_size
111
+ self.jitter_noise = config.router_jitter_noise
112
+ self.aux_loss_coef = config.router_aux_loss_coef
113
+ self.router = nn.Linear(self.hidden_size, self.num_experts, bias=False)
114
+ self.gate_proj = nn.Parameter(torch.empty(self.num_experts, self.expert_intermediate, self.hidden_size))
115
+ self.up_proj = nn.Parameter(torch.empty(self.num_experts, self.expert_intermediate, self.hidden_size))
116
+ self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_size, self.expert_intermediate))
117
+ self._init_weights()
118
+
119
+ def _init_weights(self, std=0.02):
120
+ nn.init.normal_(self.gate_proj, std=std)
121
+ nn.init.normal_(self.up_proj, std=std)
122
+ nn.init.normal_(self.down_proj, std=std)
123
+
124
+ def forward(self, x):
125
+ B, S, D = x.shape
126
+ x_flat = x.view(-1, D)
127
+ logits = self.router(x_flat)
128
+ if self.training and self.jitter_noise > 0:
129
+ logits = logits * (1 + torch.randn_like(logits) * self.jitter_noise)
130
+ weights = F.softmax(logits.float(), dim=-1).to(x.dtype)
131
+ w_topk, experts = torch.topk(weights, self.top_k, dim=-1)
132
+ w_topk = w_topk / w_topk.sum(dim=-1, keepdim=True)
133
+
134
+ aux = torch.tensor(0.0, device=x.device, dtype=x.dtype)
135
+ if self.training and self.aux_loss_coef > 0:
136
+ with torch.no_grad():
137
+ mask = F.one_hot(experts, num_classes=self.num_experts).float()
138
+ f_i = mask.mean(dim=(0, 1))
139
+ P_i = weights.mean(dim=0)
140
+ aux = (f_i.detach() * P_i).sum() * self.num_experts
141
+
142
+ out = torch.zeros(B * S, D, device=x.device, dtype=x.dtype)
143
+ for k in range(self.top_k):
144
+ for e in range(self.num_experts):
145
+ m = (experts[:, k] == e)
146
+ if not m.any():
147
+ continue
148
+ ts = x_flat[m]
149
+ gate = F.silu(ts @ self.gate_proj[e].T)
150
+ up = ts @ self.up_proj[e].T
151
+ out[m] += (gate * up @ self.down_proj[e].T) * w_topk[m, k].unsqueeze(-1)
152
+ return out.view(B, S, D), aux
153
+
154
+
155
+ class MoETransformerBlock(nn.Module):
156
+ def __init__(self, config):
157
+ super().__init__()
158
+ self.input_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
159
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
160
+ self.self_attn = GQAAttention(config)
161
+ self.moe = SparseMoE(config)
162
+
163
+ def forward(self, x, attention_mask=None, position_ids=None):
164
+ x = x + self.self_attn(self.input_layernorm(x), attention_mask, position_ids)
165
+ h, aux = self.moe(self.post_attention_layernorm(x))
166
+ return x + h, aux
167
+
168
+
169
+ # ============================================================
170
+ # Causal LM
171
+ # ============================================================
172
+
173
+ @dataclass
174
+ class CausalLMOutputWithPast:
175
+ loss: Optional[torch.Tensor] = None
176
+ logits: torch.Tensor = None
177
+
178
+
179
+ class TinyMixtralForCausalLM(PreTrainedModel):
180
+ config_class = TinyMixtralConfig
181
+ base_model_prefix = "tinymixtral"
182
+ supports_gradient_checkpointing = True
183
+ _no_split_modules = ["MoETransformerBlock"]
184
+
185
+ def __init__(self, config):
186
+ super().__init__(config)
187
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
188
+ self.layers = nn.ModuleList([MoETransformerBlock(config) for _ in range(config.num_hidden_layers)])
189
+ self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
190
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
191
+ if config.tie_word_embeddings:
192
+ self.lm_head.weight = self.embed_tokens.weight
193
+ self._use_activation_checkpointing = False
194
+ self.post_init()
195
+
196
+ def _init_weights(self, module):
197
+ std = self.config.initializer_range
198
+ if isinstance(module, nn.Linear):
199
+ module.weight.data.normal_(mean=0.0, std=std)
200
+ if module.bias is not None:
201
+ module.bias.data.zero_()
202
+ elif isinstance(module, nn.Embedding):
203
+ module.weight.data.normal_(mean=0.0, std=std)
204
+
205
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
206
+ self._use_activation_checkpointing = True
207
+
208
+ def gradient_checkpointing_disable(self):
209
+ self._use_activation_checkpointing = False
210
+
211
+ def forward(self, input_ids, attention_mask=None, labels=None, return_dict=True, **kwargs):
212
+ B, S = input_ids.shape
213
+ pos = torch.arange(S, device=input_ids.device).unsqueeze(0).expand(B, -1)
214
+ cmask = attention_mask.bool() if attention_mask is not None else None
215
+
216
+ h = self.embed_tokens(input_ids)
217
+ total_aux = torch.tensor(0.0, device=input_ids.device, dtype=torch.float32)
218
+ for layer in self.layers:
219
+ if self._use_activation_checkpointing and self.training:
220
+ h, aux = checkpoint(layer, h, cmask, pos, use_reentrant=False)
221
+ else:
222
+ h, aux = layer(h, cmask, pos)
223
+ total_aux = total_aux + aux
224
+ logits = self.lm_head(self.norm(h)).float()
225
+
226
+ loss = None
227
+ if labels is not None:
228
+ loss = F.cross_entropy(
229
+ logits.reshape(-1, logits.size(-1)),
230
+ labels.reshape(-1),
231
+ ignore_index=-100,
232
+ )
233
+ loss = loss + self.config.router_aux_loss_coef * total_aux
234
+
235
+ if not return_dict:
236
+ return (loss, logits) if loss is not None else (logits,)
237
+ return CausalLMOutputWithPast(loss=loss, logits=logits)
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad3e467d0a029b27fc6e13c44d1e36ac1552cc183996aae04161215c47876864
3
+ size 1729603131
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ }
30
+ },
31
+ "bos_token": "<s>",
32
+ "clean_up_tokenization_spaces": false,
33
+ "eos_token": "</s>",
34
+ "extra_special_tokens": {},
35
+ "legacy": false,
36
+ "model_max_length": 2048,
37
+ "pad_token": "</s>",
38
+ "padding_side": "right",
39
+ "sp_model_kwargs": {},
40
+ "tokenizer_class": "LlamaTokenizer",
41
+ "unk_token": "<unk>",
42
+ "use_default_system_prompt": false
43
+ }