meet447 commited on
Commit
3fc435b
·
verified ·
1 Parent(s): 915e273

T4 packed pretrain + SFT 2026-09-02

Browse files
README.md ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - zh
6
+ library_name: transformers
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - minimind
10
+ - pytorch
11
+ base_model: jingyaogong/minimind-3
12
+ ---
13
+
14
+ # MiniMind (meet447/minimind)
15
+
16
+ ~64M MiniMind-3 dense checkpoint from the English-first fork
17
+ [meet447/minimind](https://github.com/meet447/minimind).
18
+
19
+ This Hub repo is the **living weight store**. New pretrain / SFT / later English
20
+ runs overwrite `main` so you can always pull the latest.
21
+
22
+ ## Current weights (T4, 2026-09-02)
23
+
24
+ | File | Stage | Notes |
25
+ |------|--------|--------|
26
+ | root (`config.json` + `model.safetensors`) | full SFT | Transformers / Qwen3-compatible layout |
27
+ | `pytorch/full_sft_768.pth` | full SFT | Native MiniMind trainer format |
28
+ | `pytorch/pretrain_768.pth` | pretrain | Native MiniMind trainer format |
29
+
30
+ **Architecture:** 8 × 768, GQA 8Q/4KV, vocab 6400, SwiGLU, QK-Norm, RoPE 1e6, tied embeddings, no MoE.
31
+
32
+ **This run:** 1 epoch packed pretrain on `pretrain_t2t_mini.jsonl` (Tesla T4, fp16, batch 96) then 1 epoch SFT on `sft_t2t_mini.jsonl` (batch 16, lr 3e-5). Trainer extras: sequence packing, 3% warmup, AdamW param groups, `torch.compile`.
33
+
34
+ **Honest quality note:** the tokenizer and mini datasets are still the upstream **Chinese-heavy** ones. These weights validate the fork trainer. They are **not** an English-from-scratch model yet. English tokenizer + FineWeb-Edu / SmolTalk data come next ([docs/ROADMAP.md](https://github.com/meet447/minimind/blob/master/docs/ROADMAP.md)).
35
+
36
+ ## Load (Transformers)
37
+
38
+ ```python
39
+ from transformers import AutoModelForCausalLM, AutoTokenizer
40
+
41
+ repo = "meet447/minimind"
42
+ tok = AutoTokenizer.from_pretrained(repo, trust_remote_code=True)
43
+ model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True, torch_dtype="auto")
44
+ messages = [{"role": "user", "content": "Why is the sky blue?"}]
45
+ inputs = tok.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt")
46
+ out = model.generate(inputs, max_new_tokens=128)
47
+ print(tok.decode(out[0], skip_special_tokens=True))
48
+ ```
49
+
50
+ ## Load (this repo's trainer)
51
+
52
+ ```bash
53
+ # download native .pth into ./out
54
+ huggingface-cli download meet447/minimind pytorch/full_sft_768.pth --local-dir .
55
+ # then
56
+ python eval_llm.py --weight full_sft --hidden_size 768 --num_hidden_layers 8
57
+ ```
58
+
59
+ ## Update this repo
60
+
61
+ From a checkout that has `out/full_sft_768.pth` (and optionally `out/pretrain_768.pth`):
62
+
63
+ ```bash
64
+ export HF_TOKEN=hf_...
65
+ python scripts/push_to_hub.py --repo-id meet447/minimind
66
+ ```
67
+
68
+ License: Apache 2.0. Architecture and tokenizer follow [jingyaogong/minimind](https://github.com/jingyaogong/minimind).
chat_template.jinja ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if true %}
44
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
45
+ {%- endif %}
46
+ {%- if message.tool_calls %}
47
+ {%- for tool_call in message.tool_calls %}
48
+ {%- if (loop.first and content) or (not loop.first) %}
49
+ {{- '\n' }}
50
+ {%- endif %}
51
+ {%- if tool_call.function %}
52
+ {%- set tool_call = tool_call.function %}
53
+ {%- endif %}
54
+ {{- '<tool_call>\n{"name": "' }}
55
+ {{- tool_call.name }}
56
+ {{- '", "arguments": ' }}
57
+ {%- if tool_call.arguments is string %}
58
+ {{- tool_call.arguments }}
59
+ {%- else %}
60
+ {{- tool_call.arguments | tojson }}
61
+ {%- endif %}
62
+ {{- '}\n</tool_call>' }}
63
+ {%- endfor %}
64
+ {%- endif %}
65
+ {{- '<|im_end|>\n' }}
66
+ {%- elif message.role == "tool" %}
67
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
68
+ {{- '<|im_start|>user' }}
69
+ {%- endif %}
70
+ {{- '\n<tool_response>\n' }}
71
+ {{- content }}
72
+ {{- '\n</tool_response>' }}
73
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
74
+ {{- '<|im_end|>\n' }}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if add_generation_prompt %}
79
+ {{- '<|im_start|>assistant\n' }}
80
+ {%- if open_thinking is defined and open_thinking is true %}
81
+ {{- '<think>\n' }}
82
+ {%- else %}
83
+ {{- '<think>\n\n</think>\n\n' }}
84
+ {%- endif %}
85
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "dtype": "float16",
8
+ "head_dim": 96,
9
+ "hidden_act": "silu",
10
+ "hidden_size": 768,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 2432,
13
+ "layer_types": [
14
+ "full_attention",
15
+ "full_attention",
16
+ "full_attention",
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention"
22
+ ],
23
+ "max_position_embeddings": 32768,
24
+ "max_window_layers": 28,
25
+ "model_type": "qwen3",
26
+ "num_attention_heads": 8,
27
+ "num_hidden_layers": 8,
28
+ "num_key_value_heads": 4,
29
+ "rms_norm_eps": 1e-06,
30
+ "rope_scaling": null,
31
+ "rope_theta": 1000000.0,
32
+ "sliding_window": null,
33
+ "tie_word_embeddings": true,
34
+ "transformers_version": "4.57.6",
35
+ "use_cache": true,
36
+ "use_sliding_window": false,
37
+ "vocab_size": 6400
38
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.57.6"
4
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82ca71af0c50927b76890e073beca37e96d9b3dcffd70ef26fb5a51cd351e0f1
3
+ size 127834168
model_minimind.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math, torch, torch.nn.functional as F
2
+ from torch import nn
3
+ from transformers.activations import ACT2FN
4
+ from transformers import PreTrainedModel, GenerationMixin, PretrainedConfig
5
+ from transformers.modeling_outputs import MoeCausalLMOutputWithPast
6
+
7
+ # 🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏
8
+ # MiniMind Config
9
+ # 🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏
10
+ class MiniMindConfig(PretrainedConfig):
11
+ model_type = "minimind"
12
+ def __init__(self, hidden_size=768, num_hidden_layers=8, use_moe=False, **kwargs):
13
+ super().__init__(**kwargs)
14
+ self.hidden_size = hidden_size
15
+ self.num_hidden_layers = num_hidden_layers
16
+ self.use_moe = use_moe
17
+ self.dropout = kwargs.get("dropout", 0.0)
18
+ self.vocab_size = kwargs.get("vocab_size", 6400)
19
+ self.bos_token_id = kwargs.get("bos_token_id", 1)
20
+ self.eos_token_id = kwargs.get("eos_token_id", 2)
21
+ self.flash_attn = kwargs.get("flash_attn", True)
22
+ self.num_attention_heads = kwargs.get("num_attention_heads", 8)
23
+ self.num_key_value_heads = kwargs.get("num_key_value_heads", 4)
24
+ self.head_dim = kwargs.get("head_dim", self.hidden_size // self.num_attention_heads)
25
+ self.hidden_act = kwargs.get("hidden_act", 'silu')
26
+ self.intermediate_size = kwargs.get("intermediate_size", math.ceil(hidden_size * math.pi / 64) * 64)
27
+ self.max_position_embeddings = kwargs.get("max_position_embeddings", 32768)
28
+ self.rms_norm_eps = kwargs.get("rms_norm_eps", 1e-6)
29
+ self.rope_theta = kwargs.get("rope_theta", 1e6)
30
+ self.tie_word_embeddings = kwargs.get("tie_word_embeddings", True)
31
+ self.inference_rope_scaling = kwargs.get("inference_rope_scaling", False)
32
+ self.rope_scaling = {
33
+ "beta_fast": 32,
34
+ "beta_slow": 1,
35
+ "factor": 16,
36
+ "original_max_position_embeddings": 2048,
37
+ "attention_factor": 1.0,
38
+ "type": "yarn"
39
+ } if self.inference_rope_scaling else None
40
+ ### MoE specific configs (ignored if use_moe = False)
41
+ self.num_experts = kwargs.get("num_experts", 4)
42
+ self.num_experts_per_tok = kwargs.get("num_experts_per_tok", 1)
43
+ self.moe_intermediate_size = kwargs.get("moe_intermediate_size", self.intermediate_size)
44
+ self.norm_topk_prob = kwargs.get("norm_topk_prob", True)
45
+ self.router_aux_loss_coef = kwargs.get("router_aux_loss_coef", 5e-4)
46
+
47
+ # 🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏
48
+ # MiniMind Model
49
+ # 🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏🌎🌍🌏
50
+ class RMSNorm(torch.nn.Module):
51
+ def __init__(self, dim: int, eps: float = 1e-5):
52
+ super().__init__()
53
+ self.eps = eps
54
+ self.weight = nn.Parameter(torch.ones(dim))
55
+
56
+ def norm(self, x):
57
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
58
+
59
+ def forward(self, x):
60
+ return (self.weight * self.norm(x.float())).type_as(x)
61
+
62
+ def precompute_freqs_cis(dim: int, end: int = int(32 * 1024), rope_base: float = 1e6, rope_scaling: dict = None):
63
+ freqs, attn_factor = 1.0 / (rope_base ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)), 1.0
64
+ if rope_scaling is not None: # YaRN: f'(i) = f(i)((1-γ) + γ/s), where γ∈[0,1] is linear ramp
65
+ orig_max, factor, beta_fast, beta_slow, attn_factor = (
66
+ rope_scaling.get("original_max_position_embeddings", 2048), rope_scaling.get("factor", 16),
67
+ rope_scaling.get("beta_fast", 32.0), rope_scaling.get("beta_slow", 1.0), rope_scaling.get("attention_factor", 1.0)
68
+ )
69
+ if end / orig_max > 1.0:
70
+ inv_dim = lambda b: (dim * math.log(orig_max / (b * 2 * math.pi))) / (2 * math.log(rope_base))
71
+ low, high = max(math.floor(inv_dim(beta_fast)), 0), min(math.ceil(inv_dim(beta_slow)), dim // 2 - 1)
72
+ ramp = torch.clamp((torch.arange(dim // 2, device=freqs.device).float() - low) / max(high - low, 0.001), 0, 1)
73
+ freqs = freqs * (1 - ramp + ramp / factor)
74
+ t = torch.arange(end, device=freqs.device)
75
+ freqs = torch.outer(t, freqs).float()
76
+ freqs_cos = torch.cat([torch.cos(freqs), torch.cos(freqs)], dim=-1) * attn_factor
77
+ freqs_sin = torch.cat([torch.sin(freqs), torch.sin(freqs)], dim=-1) * attn_factor
78
+ return freqs_cos, freqs_sin
79
+
80
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
81
+ def rotate_half(x): return torch.cat((-x[..., x.shape[-1] // 2:], x[..., : x.shape[-1] // 2]), dim=-1)
82
+ q_embed = ((q * cos.unsqueeze(unsqueeze_dim)) + (rotate_half(q) * sin.unsqueeze(unsqueeze_dim))).to(q.dtype)
83
+ k_embed = ((k * cos.unsqueeze(unsqueeze_dim)) + (rotate_half(k) * sin.unsqueeze(unsqueeze_dim))).to(k.dtype)
84
+ return q_embed, k_embed
85
+
86
+ def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
87
+ bs, slen, num_key_value_heads, head_dim = x.shape
88
+ if n_rep == 1: return x
89
+ return (x[:, :, :, None, :].expand(bs, slen, num_key_value_heads, n_rep, head_dim).reshape(bs, slen, num_key_value_heads * n_rep, head_dim))
90
+
91
+ class Attention(nn.Module):
92
+ def __init__(self, config: MiniMindConfig):
93
+ super().__init__()
94
+ self.num_key_value_heads = config.num_attention_heads if config.num_key_value_heads is None else config.num_key_value_heads
95
+ self.n_local_heads = config.num_attention_heads
96
+ self.n_local_kv_heads = self.num_key_value_heads
97
+ self.n_rep = self.n_local_heads // self.n_local_kv_heads
98
+ self.head_dim = config.head_dim
99
+ self.is_causal = True
100
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
101
+ self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
102
+ self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
103
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
104
+ self.q_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
105
+ self.k_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
106
+ self.attn_dropout = nn.Dropout(config.dropout)
107
+ self.resid_dropout = nn.Dropout(config.dropout)
108
+ self.dropout = config.dropout
109
+ self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and config.flash_attn
110
+
111
+ def forward(self, x, position_embeddings, past_key_value=None, use_cache=False, attention_mask=None):
112
+ bsz, seq_len, _ = x.shape
113
+ xq, xk, xv = self.q_proj(x), self.k_proj(x), self.v_proj(x)
114
+ xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
115
+ xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
116
+ xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
117
+ xq, xk = self.q_norm(xq), self.k_norm(xk)
118
+ cos, sin = position_embeddings
119
+ xq, xk = apply_rotary_pos_emb(xq, xk, cos, sin)
120
+ if past_key_value is not None:
121
+ xk = torch.cat([past_key_value[0], xk], dim=1)
122
+ xv = torch.cat([past_key_value[1], xv], dim=1)
123
+ past_kv = (xk, xv) if use_cache else None
124
+ xq, xk, xv = (xq.transpose(1, 2), repeat_kv(xk, self.n_rep).transpose(1, 2), repeat_kv(xv, self.n_rep).transpose(1, 2))
125
+ if self.flash and (seq_len > 1) and (not self.is_causal or past_key_value is None) and (attention_mask is None or torch.all(attention_mask == 1)):
126
+ output = F.scaled_dot_product_attention(xq, xk, xv, dropout_p=self.dropout if self.training else 0.0, is_causal=self.is_causal)
127
+ else:
128
+ scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
129
+ if self.is_causal: scores[:, :, :, -seq_len:] += torch.full((seq_len, seq_len), float("-inf"), device=scores.device).triu(1)
130
+ if attention_mask is not None: scores += (1.0 - attention_mask.unsqueeze(1).unsqueeze(2)) * -1e9
131
+ output = self.attn_dropout(F.softmax(scores.float(), dim=-1).type_as(xq)) @ xv
132
+ output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
133
+ output = self.resid_dropout(self.o_proj(output))
134
+ return output, past_kv
135
+
136
+ class FeedForward(nn.Module):
137
+ def __init__(self, config: MiniMindConfig, intermediate_size: int = None):
138
+ super().__init__()
139
+ intermediate_size = intermediate_size or config.intermediate_size
140
+ self.gate_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
141
+ self.down_proj = nn.Linear(intermediate_size, config.hidden_size, bias=False)
142
+ self.up_proj = nn.Linear(config.hidden_size, intermediate_size, bias=False)
143
+ self.act_fn = ACT2FN[config.hidden_act]
144
+
145
+ def forward(self, x):
146
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
147
+
148
+ class MOEFeedForward(nn.Module):
149
+ def __init__(self, config: MiniMindConfig):
150
+ super().__init__()
151
+ self.config = config
152
+ self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
153
+ self.experts = nn.ModuleList([FeedForward(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.num_experts)])
154
+ self.act_fn = ACT2FN[config.hidden_act]
155
+
156
+ def forward(self, x):
157
+ batch_size, seq_len, hidden_dim = x.shape
158
+ x_flat = x.view(-1, hidden_dim)
159
+ scores = F.softmax(self.gate(x_flat), dim=-1)
160
+ topk_weight, topk_idx = torch.topk(scores, k=self.config.num_experts_per_tok, dim=-1, sorted=False)
161
+ if self.config.norm_topk_prob: topk_weight = topk_weight / (topk_weight.sum(dim=-1, keepdim=True) + 1e-20)
162
+ y = torch.zeros_like(x_flat)
163
+ for i, expert in enumerate(self.experts):
164
+ mask = (topk_idx == i)
165
+ if mask.any():
166
+ token_idx = mask.any(dim=-1).nonzero().flatten()
167
+ weight = topk_weight[mask].view(-1, 1)
168
+ y.index_add_(0, token_idx, (expert(x_flat[token_idx]) * weight).to(y.dtype))
169
+ elif self.training:
170
+ y[0, 0] += 0 * sum(p.sum() for p in expert.parameters())
171
+ if self.training and self.config.router_aux_loss_coef > 0:
172
+ load = F.one_hot(topk_idx, self.config.num_experts).float().mean(0)
173
+ self.aux_loss = (load * scores.mean(0)).sum() * self.config.num_experts * self.config.router_aux_loss_coef
174
+ else:
175
+ self.aux_loss = scores.new_zeros(1).squeeze()
176
+ return y.view(batch_size, seq_len, hidden_dim)
177
+
178
+ class MiniMindBlock(nn.Module):
179
+ def __init__(self, layer_id: int, config: MiniMindConfig):
180
+ super().__init__()
181
+ self.self_attn = Attention(config)
182
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
183
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
184
+ self.mlp = FeedForward(config) if not config.use_moe else MOEFeedForward(config)
185
+
186
+ def forward(self, hidden_states, position_embeddings, past_key_value=None, use_cache=False, attention_mask=None):
187
+ residual = hidden_states
188
+ hidden_states, present_key_value = self.self_attn(
189
+ self.input_layernorm(hidden_states), position_embeddings,
190
+ past_key_value, use_cache, attention_mask
191
+ )
192
+ hidden_states += residual
193
+ hidden_states = hidden_states + self.mlp(self.post_attention_layernorm(hidden_states))
194
+ return hidden_states, present_key_value
195
+
196
+ class MiniMindModel(nn.Module):
197
+ def __init__(self, config: MiniMindConfig):
198
+ super().__init__()
199
+ self.config = config
200
+ self.vocab_size, self.num_hidden_layers = config.vocab_size, config.num_hidden_layers
201
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
202
+ self.dropout = nn.Dropout(config.dropout)
203
+ self.layers = nn.ModuleList([MiniMindBlock(l, config) for l in range(self.num_hidden_layers)])
204
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
205
+ freqs_cos, freqs_sin = precompute_freqs_cis(dim=config.head_dim, end=config.max_position_embeddings, rope_base=config.rope_theta, rope_scaling=config.rope_scaling)
206
+ self.register_buffer("freqs_cos", freqs_cos, persistent=False)
207
+ self.register_buffer("freqs_sin", freqs_sin, persistent=False)
208
+
209
+ def forward(self, input_ids, attention_mask=None, past_key_values=None, use_cache=False, **kwargs):
210
+ batch_size, seq_length = input_ids.shape
211
+ if hasattr(past_key_values, 'layers'): past_key_values = None
212
+ past_key_values = past_key_values or [None] * len(self.layers)
213
+ start_pos = past_key_values[0][0].shape[1] if past_key_values[0] is not None else 0
214
+ hidden_states = self.dropout(self.embed_tokens(input_ids))
215
+ # Recompute RoPE buffers lost during meta-device init (transformers>=5.x)
216
+ if self.freqs_cos[0, 0] == 0:
217
+ freqs_cos, freqs_sin = precompute_freqs_cis(dim=self.config.head_dim, end=self.config.max_position_embeddings, rope_base=self.config.rope_theta, rope_scaling=self.config.rope_scaling)
218
+ self.freqs_cos, self.freqs_sin = freqs_cos.to(hidden_states.device), freqs_sin.to(hidden_states.device)
219
+ position_embeddings = (self.freqs_cos[start_pos:start_pos + seq_length], self.freqs_sin[start_pos:start_pos + seq_length])
220
+ presents = []
221
+ for layer, past_key_value in zip(self.layers, past_key_values):
222
+ hidden_states, present = layer(
223
+ hidden_states,
224
+ position_embeddings,
225
+ past_key_value=past_key_value,
226
+ use_cache=use_cache,
227
+ attention_mask=attention_mask
228
+ )
229
+ presents.append(present)
230
+ hidden_states = self.norm(hidden_states)
231
+ aux_loss = sum([l.mlp.aux_loss for l in self.layers if isinstance(l.mlp, MOEFeedForward)], hidden_states.new_zeros(1).squeeze())
232
+ return hidden_states, presents, aux_loss
233
+
234
+ class MiniMindForCausalLM(PreTrainedModel, GenerationMixin):
235
+ config_class = MiniMindConfig
236
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
237
+ def __init__(self, config: MiniMindConfig = None):
238
+ self.config = config or MiniMindConfig()
239
+ super().__init__(self.config)
240
+ self.model = MiniMindModel(self.config)
241
+ self.lm_head = nn.Linear(self.config.hidden_size, self.config.vocab_size, bias=False)
242
+ if self.config.tie_word_embeddings: self.model.embed_tokens.weight = self.lm_head.weight
243
+ self.post_init()
244
+
245
+ def forward(self, input_ids, attention_mask=None, past_key_values=None, use_cache=False, logits_to_keep=0, labels=None, **kwargs):
246
+ hidden_states, past_key_values, aux_loss = self.model(input_ids, attention_mask, past_key_values, use_cache, **kwargs)
247
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
248
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
249
+ loss = None
250
+ if labels is not None:
251
+ x, y = logits[..., :-1, :].contiguous(), labels[..., 1:].contiguous()
252
+ loss = F.cross_entropy(x.view(-1, x.size(-1)), y.view(-1), ignore_index=-100)
253
+ return MoeCausalLMOutputWithPast(loss=loss, aux_loss=aux_loss, logits=logits, past_key_values=past_key_values, hidden_states=hidden_states)
254
+
255
+ # https://github.com/jingyaogong/minimind/discussions/611
256
+ @torch.inference_mode()
257
+ def generate(self, inputs=None, attention_mask=None, max_new_tokens=8192, temperature=0.85, top_p=0.85, top_k=50, eos_token_id=2, streamer=None, use_cache=True, num_return_sequences=1, do_sample=True, repetition_penalty=1.0, **kwargs):
258
+ input_ids = kwargs.pop("input_ids", inputs).repeat(num_return_sequences, 1)
259
+ attention_mask = attention_mask.repeat(num_return_sequences, 1) if attention_mask is not None else None
260
+ past_key_values = kwargs.pop("past_key_values", None)
261
+ finished = torch.zeros(input_ids.shape[0], dtype=torch.bool, device=input_ids.device)
262
+ if streamer: streamer.put(input_ids.cpu())
263
+ for _ in range(max_new_tokens):
264
+ past_len = past_key_values[0][0].shape[1] if past_key_values else 0
265
+ outputs = self.forward(input_ids[:, past_len:], attention_mask, past_key_values, use_cache=use_cache, **kwargs)
266
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones(attention_mask.shape[0], 1)], -1) if attention_mask is not None else None
267
+ logits = outputs.logits[:, -1, :] / temperature
268
+ if repetition_penalty != 1.0:
269
+ for i in range(input_ids.shape[0]):
270
+ seen = torch.unique(input_ids[i]); score = logits[i, seen]; logits[i, seen] = torch.where(score > 0, score / repetition_penalty, score * repetition_penalty)
271
+ if top_k > 0:
272
+ logits[logits < torch.topk(logits, top_k)[0][..., -1, None]] = -float('inf')
273
+ if top_p < 1.0:
274
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
275
+ mask = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1) > top_p
276
+ mask[..., 1:], mask[..., 0] = mask[..., :-1].clone(), 0
277
+ logits[mask.scatter(1, sorted_indices, mask)] = -float('inf')
278
+ next_token = torch.multinomial(torch.softmax(logits, dim=-1), num_samples=1) if do_sample else torch.argmax(logits, dim=-1, keepdim=True)
279
+ if eos_token_id is not None: next_token = torch.where(finished.unsqueeze(-1), next_token.new_full((next_token.shape[0], 1), eos_token_id), next_token)
280
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
281
+ past_key_values = outputs.past_key_values if use_cache else None
282
+ if streamer: streamer.put(next_token.cpu())
283
+ if eos_token_id is not None:
284
+ finished |= next_token.squeeze(-1).eq(eos_token_id)
285
+ if finished.all(): break
286
+ if streamer: streamer.end()
287
+ if kwargs.get("return_kv"): return {'generated_ids': input_ids, 'past_kv': past_key_values}
288
+ return input_ids
pytorch/full_sft_768.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54dc5680f234230089df0c77240816d7b0640a672547804e331c8f29fcf86792
3
+ size 137684407
pytorch/pretrain_768.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d10a867a0640e47ae849dc04c8349a9366348389711c36fe34867c89c6543c74
3
+ size 137684407
special_tokens_map.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>",
16
+ "<|audio_start|>",
17
+ "<|audio_end|>",
18
+ "<|audio_pad|>",
19
+ "<tts_pad>",
20
+ "<tts_text_bos>",
21
+ "<tts_text_eod>",
22
+ "<tts_text_bos_single>"
23
+ ],
24
+ "bos_token": {
25
+ "content": "<|im_start|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ "eos_token": {
32
+ "content": "<|im_end|>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ },
38
+ "pad_token": {
39
+ "content": "<|endoftext|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false
44
+ },
45
+ "unk_token": {
46
+ "content": "<|endoftext|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false
51
+ }
52
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<|im_start|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "<|im_end|>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": true
29
+ },
30
+ "3": {
31
+ "content": "<|object_ref_start|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "4": {
39
+ "content": "<|object_ref_end|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "5": {
47
+ "content": "<|box_start|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "6": {
55
+ "content": "<|box_end|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "7": {
63
+ "content": "<|quad_start|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "8": {
71
+ "content": "<|quad_end|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "9": {
79
+ "content": "<|vision_start|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "10": {
87
+ "content": "<|vision_end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "11": {
95
+ "content": "<|vision_pad|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "12": {
103
+ "content": "<|image_pad|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "13": {
111
+ "content": "<|video_pad|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": true
117
+ },
118
+ "14": {
119
+ "content": "<|audio_start|>",
120
+ "lstrip": false,
121
+ "normalized": false,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": true
125
+ },
126
+ "15": {
127
+ "content": "<|audio_end|>",
128
+ "lstrip": false,
129
+ "normalized": false,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": true
133
+ },
134
+ "16": {
135
+ "content": "<|audio_pad|>",
136
+ "lstrip": false,
137
+ "normalized": false,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": true
141
+ },
142
+ "17": {
143
+ "content": "<tts_pad>",
144
+ "lstrip": false,
145
+ "normalized": false,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": true
149
+ },
150
+ "18": {
151
+ "content": "<tts_text_bos>",
152
+ "lstrip": false,
153
+ "normalized": false,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": true
157
+ },
158
+ "19": {
159
+ "content": "<tts_text_eod>",
160
+ "lstrip": false,
161
+ "normalized": false,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": true
165
+ },
166
+ "20": {
167
+ "content": "<tts_text_bos_single>",
168
+ "lstrip": false,
169
+ "normalized": false,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": true
173
+ },
174
+ "21": {
175
+ "content": "<tool_call>",
176
+ "lstrip": false,
177
+ "normalized": false,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "22": {
183
+ "content": "</tool_call>",
184
+ "lstrip": false,
185
+ "normalized": false,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": false
189
+ },
190
+ "23": {
191
+ "content": "<tool_response>",
192
+ "lstrip": false,
193
+ "normalized": false,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "24": {
199
+ "content": "</tool_response>",
200
+ "lstrip": false,
201
+ "normalized": false,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ },
206
+ "25": {
207
+ "content": "<think>",
208
+ "lstrip": false,
209
+ "normalized": false,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": false
213
+ },
214
+ "26": {
215
+ "content": "</think>",
216
+ "lstrip": false,
217
+ "normalized": false,
218
+ "rstrip": false,
219
+ "single_word": false,
220
+ "special": false
221
+ },
222
+ "27": {
223
+ "content": "<|buffer1|>",
224
+ "lstrip": false,
225
+ "normalized": false,
226
+ "rstrip": false,
227
+ "single_word": false,
228
+ "special": false
229
+ },
230
+ "28": {
231
+ "content": "<|buffer2|>",
232
+ "lstrip": false,
233
+ "normalized": false,
234
+ "rstrip": false,
235
+ "single_word": false,
236
+ "special": false
237
+ },
238
+ "29": {
239
+ "content": "<|buffer3|>",
240
+ "lstrip": false,
241
+ "normalized": false,
242
+ "rstrip": false,
243
+ "single_word": false,
244
+ "special": false
245
+ },
246
+ "30": {
247
+ "content": "<|buffer4|>",
248
+ "lstrip": false,
249
+ "normalized": false,
250
+ "rstrip": false,
251
+ "single_word": false,
252
+ "special": false
253
+ },
254
+ "31": {
255
+ "content": "<|buffer5|>",
256
+ "lstrip": false,
257
+ "normalized": false,
258
+ "rstrip": false,
259
+ "single_word": false,
260
+ "special": false
261
+ },
262
+ "32": {
263
+ "content": "<|buffer6|>",
264
+ "lstrip": false,
265
+ "normalized": false,
266
+ "rstrip": false,
267
+ "single_word": false,
268
+ "special": false
269
+ },
270
+ "33": {
271
+ "content": "<|buffer7|>",
272
+ "lstrip": false,
273
+ "normalized": false,
274
+ "rstrip": false,
275
+ "single_word": false,
276
+ "special": false
277
+ },
278
+ "34": {
279
+ "content": "<|buffer8|>",
280
+ "lstrip": false,
281
+ "normalized": false,
282
+ "rstrip": false,
283
+ "single_word": false,
284
+ "special": false
285
+ },
286
+ "35": {
287
+ "content": "<|buffer9|>",
288
+ "lstrip": false,
289
+ "normalized": false,
290
+ "rstrip": false,
291
+ "single_word": false,
292
+ "special": false
293
+ }
294
+ },
295
+ "additional_special_tokens": [
296
+ "<|im_start|>",
297
+ "<|im_end|>",
298
+ "<|object_ref_start|>",
299
+ "<|object_ref_end|>",
300
+ "<|box_start|>",
301
+ "<|box_end|>",
302
+ "<|quad_start|>",
303
+ "<|quad_end|>",
304
+ "<|vision_start|>",
305
+ "<|vision_end|>",
306
+ "<|vision_pad|>",
307
+ "<|image_pad|>",
308
+ "<|video_pad|>",
309
+ "<|audio_start|>",
310
+ "<|audio_end|>",
311
+ "<|audio_pad|>",
312
+ "<tts_pad>",
313
+ "<tts_text_bos>",
314
+ "<tts_text_eod>",
315
+ "<tts_text_bos_single>"
316
+ ],
317
+ "audio_bos_token": "<|audio_start|>",
318
+ "audio_eos_token": "<|audio_end|>",
319
+ "audio_token": "<|audio_pad|>",
320
+ "bos_token": "<|im_start|>",
321
+ "clean_up_tokenization_spaces": false,
322
+ "eos_token": "<|im_end|>",
323
+ "extra_special_tokens": {},
324
+ "image_token": "<|image_pad|>",
325
+ "legacy": true,
326
+ "model_max_length": 131072,
327
+ "pad_token": "<|endoftext|>",
328
+ "sp_model_kwargs": {},
329
+ "spaces_between_special_tokens": false,
330
+ "tokenizer_class": "PreTrainedTokenizerFast",
331
+ "unk_token": "<|endoftext|>",
332
+ "video_token": "<|video_pad|>",
333
+ "vision_bos_token": "<|vision_start|>",
334
+ "vision_eos_token": "<|vision_end|>"
335
+ }