SnifferCaptain commited on
Commit
5f26b65
·
verified ·
1 Parent(s): 8583aaf
README.md CHANGED
@@ -1,3 +1,52 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ language:
4
+ - zh
5
+ - en
6
+ pipeline_tag: text-generation
7
+ library_name: transformers
8
+ tags:
9
+ - custom_code
10
+ - safetensors
11
+ - ymodel
12
+ - ymodel31
13
  ---
14
+
15
+ # ymodel3.1-200M
16
+
17
+ `ymodel3.1-200M`是SnifferCaptain训练的到目前为止(7/7/2026)最新、最大的语言模型。采用ynet3.1架构,在ymodel3所使用的ynet3架构上添加了Sengram记忆模块,其模型容量上相比上一代架构有一定的提升。
18
+
19
+ ## 模型细节
20
+
21
+ - 在ynet3的基础上,添加了Sengram记忆模块,这种稀疏嵌入可以在增大模型参数量的时候,尽可能减少模型的额外计算量。
22
+ - Sengram (Simplified Engram( https://arxiv.org/abs/2601.07372 ))记忆模块对原始的Engram基于n-gram的记忆模块进行了简化,分为掌管稀疏路由的SengramIndexer与掌管嵌入的SengramPLE。
23
+ - 在SengramIndexer记忆选择过程中,相比原来的Engram,它将记忆的选择从简单快速的哈希改为在语义空间内线性投影,而后使用类似MoE的softmax + topk让后续嵌入在语义空间中得到连续的表示。其优点在于它将离散的可碰撞的哈希嵌入转换为在语义空间中连续的嵌入方式,且在建模上不局限于n-gram这种仅语言模型支持的特殊数据,它天生支持多模态。其缺点在于相比简单哈希计算量会大很多,但是整体上来说由于所有层共享一个选择结果,占用模型推理的总计算量很小。
24
+ - SengramPLE的意思是Sengram模块的逐层嵌入(Per-Layer Embedding),模块接收来自Indexer的topk与score输出,在每层独立的分桶内取得逐层嵌入并加权求和。SengramPLE去掉了原本engram对嵌入的gate,选择了直接相加的方式加速计算。
25
+
26
+ | 键 | 值 |
27
+ | --- | --- |
28
+ | 架构 | YModel3.1 |
29
+ | 参数数量 | 210.22M |
30
+ | 层数 | 12 |
31
+ | 隐藏层维度 | 768 |
32
+ | 词表大小 | 6400 |
33
+ | 注意力头数 | 8 |
34
+ | 注意力头维度 | 192 |
35
+ | KV嵌入维度 | 256 |
36
+ | RoPE嵌入维度 | 64 |
37
+ | FFN激活函数 | SwiGLU |
38
+ | FFN中间层大小 | 2048 |
39
+ | 归一化 | RMSNorm + SEBlock |
40
+ | 注意力机制 | MLGA |
41
+ | Sengram桶大小 | 8192 |
42
+ | Sengram选择数量 | 8 |
43
+ | Sengram评分函数 | Softmax |
44
+ | 数据类型 | bfloat16 |
45
+
46
+ ## 训练细节
47
+
48
+ - 在预训练阶段,模型在512长度的上下文充分使用**5B tokens**,1e-4带warmup的余弦退火到1e-5的学习率下,完成预训练。最终的ppl为5.041(6400BPE词表长度)
49
+ - 模型全程采用与YModel3相同的**SiMuon优化器**训练
50
+ - 模型的tokenlizer与词嵌入层使用的是预训练权重,来自MiniMind3-v( https://github.com/jingyaogong/minimind )
51
+ - 预训练阶段采用的批次大小为前50% 64k tokens/step、后50% 128k tokens/step
52
+
__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .modeling_ymodel31 import YForCausalLM31
config.json ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "return_dict": true,
3
+ "output_hidden_states": false,
4
+ "torchscript": false,
5
+ "dtype": "bfloat16",
6
+ "_output_attentions": false,
7
+ "pruned_heads": {},
8
+ "tie_word_embeddings": true,
9
+ "chunk_size_feed_forward": 0,
10
+ "is_encoder_decoder": false,
11
+ "is_decoder": false,
12
+ "cross_attention_hidden_size": null,
13
+ "add_cross_attention": false,
14
+ "tie_encoder_decoder": false,
15
+ "architectures": [
16
+ "YForCausalLM31"
17
+ ],
18
+ "finetuning_task": null,
19
+ "id2label": {
20
+ "0": "LABEL_0",
21
+ "1": "LABEL_1"
22
+ },
23
+ "label2id": {
24
+ "LABEL_0": 0,
25
+ "LABEL_1": 1
26
+ },
27
+ "task_specific_params": null,
28
+ "problem_type": null,
29
+ "tokenizer_class": null,
30
+ "prefix": null,
31
+ "bos_token_id": 151644,
32
+ "pad_token_id": 151643,
33
+ "eos_token_id": 151645,
34
+ "sep_token_id": null,
35
+ "decoder_start_token_id": null,
36
+ "max_length": 20,
37
+ "min_length": 0,
38
+ "do_sample": false,
39
+ "early_stopping": false,
40
+ "num_beams": 1,
41
+ "temperature": 1.0,
42
+ "top_k": 50,
43
+ "top_p": 1.0,
44
+ "typical_p": 1.0,
45
+ "repetition_penalty": 1.0,
46
+ "length_penalty": 1.0,
47
+ "no_repeat_ngram_size": 0,
48
+ "encoder_no_repeat_ngram_size": 0,
49
+ "bad_words_ids": null,
50
+ "num_return_sequences": 1,
51
+ "output_scores": false,
52
+ "return_dict_in_generate": false,
53
+ "forced_bos_token_id": null,
54
+ "forced_eos_token_id": null,
55
+ "remove_invalid_values": false,
56
+ "exponential_decay_length_penalty": null,
57
+ "suppress_tokens": null,
58
+ "begin_suppress_tokens": null,
59
+ "num_beam_groups": 1,
60
+ "diversity_penalty": 0.0,
61
+ "_name_or_path": "",
62
+ "_commit_hash": null,
63
+ "_attn_implementation_internal": "eager",
64
+ "transformers_version": null,
65
+ "tf_legacy_loss": false,
66
+ "use_bfloat16": false,
67
+ "dropout": 0.0,
68
+ "hidden_act": "silu",
69
+ "hidden_size": 768,
70
+ "num_hidden_layers": 12,
71
+ "max_position_embeddings": 8192,
72
+ "vocab_size": 6400,
73
+ "rms_norm_eps": 1e-06,
74
+ "rope_theta": 50000.0,
75
+ "rope_scaling": null,
76
+ "self_distill": true,
77
+ "intermediate_size": 2048,
78
+ "num_heads": 8,
79
+ "mla_kv_lora_rank": 256,
80
+ "mla_qk_nope_head_dim": 128,
81
+ "mla_qk_rope_head_dim": 64,
82
+ "mla_attn_impl": "absorb",
83
+ "qkv_lora": false,
84
+ "gradient_checkpointing": 0,
85
+ "use_sengram": true,
86
+ "sengram_bucket_size": 8192,
87
+ "sengram_topk": 8,
88
+ "engram_bucket_size": 4096,
89
+ "engram_topk": 2,
90
+ "model_type": "ynet31",
91
+ "auto_map": {
92
+ "AutoConfig": "configuration_ymodel31.YConfig31",
93
+ "AutoModelForCausalLM": "modeling_ymodel31.YForCausalLM31"
94
+ }
95
+ }
configuration_ymodel31.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class YConfig31(PretrainedConfig):
5
+ model_type = "ynet31"
6
+
7
+ def __init__(self, **kwargs):
8
+ self.dropout = kwargs.pop("dropout", 0.0)
9
+ self.bos_token_id = kwargs.pop("bos_token_id", 151644)
10
+ self.eos_token_id = kwargs.pop("eos_token_id", 151645)
11
+ self.pad_token_id = kwargs.pop("pad_token_id", 151643)
12
+ self.hidden_act = kwargs.pop("hidden_act", "silu")
13
+ self.hidden_size = kwargs.pop("hidden_size", 768)
14
+ self.num_hidden_layers = kwargs.pop("num_hidden_layers", 8)
15
+ self.max_position_embeddings = kwargs.pop("max_position_embeddings", 8192)
16
+ self.vocab_size = kwargs.pop("vocab_size", 6400)
17
+ self.rms_norm_eps = kwargs.pop("rms_norm_eps", 1e-6)
18
+ self.rope_theta = kwargs.pop("rope_theta", 5e4)
19
+ self.rope_scaling = kwargs.pop("rope_scaling", None)
20
+ self.dtype = kwargs.pop("dtype", "float32")
21
+ self.self_distill = kwargs.pop("self_distill", True)
22
+ self.intermediate_size = kwargs.pop("intermediate_size", 1536)
23
+ self.num_heads = kwargs.pop("num_heads", 12)
24
+ self.mla_kv_lora_rank = kwargs.pop("mla_kv_lora_rank", 64)
25
+ self.mla_qk_nope_head_dim = kwargs.pop("mla_qk_nope_head_dim", 64)
26
+ self.mla_qk_rope_head_dim = kwargs.pop("mla_qk_rope_head_dim", 32)
27
+ self.mla_attn_impl = kwargs.pop("mla_attn_impl", "absorb")
28
+ self.qkv_lora = kwargs.pop("qkv_lora", False)
29
+ self.gradient_checkpointing = kwargs.pop("gradient_checkpointing", 0)
30
+ self.use_sengram = kwargs.pop("use_sengram", True)
31
+ self.sengram_bucket_size = kwargs.pop("sengram_bucket_size", 4096)
32
+ self.sengram_topk = kwargs.pop("sengram_topk", 2)
33
+ self.engram_bucket_size = kwargs.pop("engram_bucket_size", self.sengram_bucket_size)
34
+ self.engram_topk = kwargs.pop("engram_topk", self.sengram_topk)
35
+ super().__init__(
36
+ bos_token_id=self.bos_token_id,
37
+ eos_token_id=self.eos_token_id,
38
+ pad_token_id=self.pad_token_id,
39
+ **kwargs,
40
+ )
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4163a5a055327983c2207236968d7b2e7a75eb3018082320d3606c2c7feb627c
3
+ size 442887840
modeling_ymodel31.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers import PreTrainedModel
6
+ from transformers.modeling_outputs import CausalLMOutputWithPast
7
+
8
+ from .configuration_ymodel31 import YConfig31
9
+ from .ymodel31_eval import YModel31
10
+
11
+
12
+ class YForCausalLM31(PreTrainedModel):
13
+ config_class = YConfig31
14
+ base_model_prefix = "model"
15
+
16
+ def __init__(self, config: YConfig31):
17
+ super().__init__(config)
18
+ self.model = YModel31(config)
19
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
20
+ self.model.embed_tokens.weight = self.lm_head.weight
21
+ self.post_init()
22
+
23
+ def get_input_embeddings(self):
24
+ return self.model.embed_tokens
25
+
26
+ def set_input_embeddings(self, value):
27
+ self.model.embed_tokens = value
28
+ self.lm_head.weight = value.weight
29
+
30
+ def get_output_embeddings(self):
31
+ return self.lm_head
32
+
33
+ def tie_weights(self):
34
+ self.model.embed_tokens.weight = self.lm_head.weight
35
+ return None
36
+
37
+ def prepare_inputs_for_generation(
38
+ self,
39
+ input_ids,
40
+ past_key_values=None,
41
+ attention_mask=None,
42
+ use_cache=True,
43
+ **kwargs,
44
+ ):
45
+ if past_key_values is not None:
46
+ input_ids = input_ids[:, -1:]
47
+ return {
48
+ "input_ids": input_ids,
49
+ "past_key_values": past_key_values,
50
+ "attention_mask": attention_mask,
51
+ "use_cache": use_cache,
52
+ "cache_position": kwargs.get("cache_position", None),
53
+ "position_ids": kwargs.get("position_ids", None),
54
+ }
55
+
56
+ def forward(
57
+ self,
58
+ input_ids=None,
59
+ attention_mask=None,
60
+ past_key_values=None,
61
+ use_cache=False,
62
+ cache_position=None,
63
+ position_ids=None,
64
+ **kwargs,
65
+ ):
66
+ h, past_kvs = self.model(
67
+ input_ids=input_ids,
68
+ attention_mask=attention_mask,
69
+ past_key_values=past_key_values,
70
+ use_cache=use_cache,
71
+ cache_position=cache_position,
72
+ position_ids=position_ids,
73
+ )
74
+ logits = self.lm_head(h)
75
+ return CausalLMOutputWithPast(
76
+ logits=logits,
77
+ past_key_values=past_kvs,
78
+ hidden_states=(h,),
79
+ )
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
+ "bos_token": "<|im_start|>",
318
+ "clean_up_tokenization_spaces": false,
319
+ "eos_token": "<|im_end|>",
320
+ "legacy": true,
321
+ "model_max_length": 262144,
322
+ "pad_token": "<|endoftext|>",
323
+ "sp_model_kwargs": {},
324
+ "spaces_between_special_tokens": false,
325
+ "unk_token": "<|endoftext|>",
326
+ "image_token": "<|image_pad|>",
327
+ "audio_token": "<|audio_pad|>",
328
+ "video_token": "<|video_pad|>",
329
+ "vision_bos_token": "<|vision_start|>",
330
+ "vision_eos_token": "<|vision_end|>",
331
+ "audio_bos_token": "<|audio_start|>",
332
+ "audio_eos_token": "<|audio_end|>",
333
+ "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# 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>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\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\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- 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>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if true %}\n {{- '<|im_start|>' + message.role + '\\n<think>' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if open_thinking is defined and open_thinking is true %}\n {{- '<think>' }}\n {%- else %}\n {{- '<think>\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
334
+ "tokenizer_class": "PreTrainedTokenizerFast"
335
+ }
ymodel31_eval.py ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone evaluation/inference implementation for ymodel31.
2
+
3
+ This file intentionally contains a self-contained inference path so exported
4
+ checkpoints can be loaded without importing the training implementation.
5
+ Training-only features such as gradient checkpointing and self-distillation are
6
+ omitted here on purpose.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from pathlib import Path
13
+ from typing import Optional, Union
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from safetensors.torch import load_file as load_safetensors
19
+ from transformers import GenerationMixin, PreTrainedModel
20
+ from transformers.activations import ACT2FN
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.modeling_outputs import CausalLMOutputWithPast
23
+
24
+
25
+ def normalize_gradient_checkpointing_level(value: Union[bool, int, str, None]) -> int:
26
+ if isinstance(value, bool):
27
+ return 1 if value else 0
28
+ if value is None:
29
+ return 0
30
+ if isinstance(value, int):
31
+ return max(0, value)
32
+ text = str(value).strip().lower()
33
+ if text in {"", "false", "off", "no", "none"}:
34
+ return 0
35
+ if text in {"true", "on", "yes"}:
36
+ return 1
37
+ try:
38
+ return max(0, int(text))
39
+ except ValueError as exc:
40
+ raise ValueError(f"Unsupported gradient_checkpointing level: {value!r}") from exc
41
+
42
+
43
+ class YConfig31(PretrainedConfig):
44
+ model_type = "ynet31"
45
+
46
+ def __init__(
47
+ self,
48
+ dropout: float = 0.0,
49
+ bos_token_id: int = 151644,
50
+ eos_token_id: int = 151645,
51
+ pad_token_id: int = 151643,
52
+ hidden_act: str = "silu",
53
+ hidden_size: int = 768,
54
+ num_hidden_layers: int = 8,
55
+ max_position_embeddings: int = 8192,
56
+ vocab_size: int = 6400,
57
+ rms_norm_eps: float = 1e-6,
58
+ rope_theta: float = 5e4,
59
+ rope_scaling: Optional[dict] = None,
60
+ dtype: str = "float32",
61
+ self_distill: bool = True,
62
+ intermediate_size: int = 1536,
63
+ num_heads: int = 12,
64
+ mla_kv_lora_rank: int = 64,
65
+ mla_qk_nope_head_dim: int = 64,
66
+ mla_qk_rope_head_dim: int = 32,
67
+ mla_attn_impl: str = "absorb",
68
+ qkv_lora: bool = False,
69
+ gradient_checkpointing: Union[bool, int, str] = 0,
70
+ use_sengram: bool = True,
71
+ sengram_bucket_size: Optional[int] = 4096,
72
+ sengram_topk: int = 2,
73
+ engram_bucket_size: Optional[int] = None,
74
+ engram_topk: Optional[int] = None,
75
+ **kwargs,
76
+ ):
77
+ super().__init__(
78
+ bos_token_id=bos_token_id,
79
+ eos_token_id=eos_token_id,
80
+ pad_token_id=pad_token_id,
81
+ **kwargs,
82
+ )
83
+ self.dropout = dropout
84
+ self.hidden_act = hidden_act
85
+ self.hidden_size = hidden_size
86
+ self.num_hidden_layers = num_hidden_layers
87
+ self.max_position_embeddings = max_position_embeddings
88
+ self.vocab_size = vocab_size
89
+ self.rms_norm_eps = rms_norm_eps
90
+ self.rope_theta = rope_theta
91
+ self.rope_scaling = rope_scaling
92
+ self.dtype = dtype
93
+ self.self_distill = self_distill
94
+ self.intermediate_size = intermediate_size
95
+ self.num_heads = num_heads
96
+ self.mla_kv_lora_rank = mla_kv_lora_rank
97
+ self.mla_qk_nope_head_dim = mla_qk_nope_head_dim
98
+ self.mla_qk_rope_head_dim = mla_qk_rope_head_dim
99
+ self.mla_attn_impl = mla_attn_impl
100
+ self.qkv_lora = qkv_lora
101
+ self.gradient_checkpointing = normalize_gradient_checkpointing_level(gradient_checkpointing)
102
+ self.use_sengram = bool(use_sengram)
103
+ if engram_bucket_size is not None:
104
+ sengram_bucket_size = engram_bucket_size
105
+ if engram_topk is not None:
106
+ sengram_topk = engram_topk
107
+ self.sengram_bucket_size = sengram_bucket_size
108
+ self.sengram_topk = sengram_topk
109
+ self.engram_bucket_size = self.sengram_bucket_size
110
+ self.engram_topk = self.sengram_topk
111
+
112
+ @property
113
+ def head_dim(self) -> int:
114
+ return self.mla_qk_nope_head_dim + self.mla_qk_rope_head_dim
115
+
116
+ @property
117
+ def qk_head_dim(self) -> int:
118
+ return self.head_dim
119
+
120
+ def scale_lvl(self, lvl: int = 0):
121
+ if lvl == 0:
122
+ self.hidden_size = 768
123
+ self.num_hidden_layers = 12
124
+ self.num_heads = 8
125
+ self.mla_kv_lora_rank = 256
126
+ self.mla_qk_nope_head_dim = 128
127
+ self.mla_qk_rope_head_dim = 64
128
+ self.intermediate_size = 2048
129
+ self.use_sengram = True
130
+ self.sengram_bucket_size = 8192
131
+ self.sengram_topk = 8
132
+ elif lvl == -1:
133
+ self.hidden_size = 768
134
+ self.num_hidden_layers = 8
135
+ self.num_heads = 6
136
+ self.mla_kv_lora_rank = 128
137
+ self.mla_qk_nope_head_dim = 64
138
+ self.mla_qk_rope_head_dim = 64
139
+ self.intermediate_size = 1536
140
+ self.use_sengram = True
141
+ elif lvl == -2:
142
+ self.hidden_size = 512
143
+ self.num_hidden_layers = 4
144
+ self.num_heads = 4
145
+ self.mla_kv_lora_rank = 128
146
+ self.mla_qk_nope_head_dim = 64
147
+ self.mla_qk_rope_head_dim = 64
148
+ self.intermediate_size = 1024
149
+ self.use_sengram = True
150
+ else:
151
+ raise ValueError(f"invalid ymodel31 scale level: {lvl}")
152
+ return self
153
+
154
+
155
+ def _yarn_linear_ramp(low: float, high: float, dim: int) -> torch.Tensor:
156
+ if low == high:
157
+ high += 0.001
158
+ linear = (torch.arange(dim, dtype=torch.float32) - low) / (high - low)
159
+ return torch.clamp(linear, 0.0, 1.0)
160
+
161
+
162
+ def _yarn_correction_dim(num_rotations: float, dim: int, theta: float, max_position_embeddings: int) -> float:
163
+ return dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi)) / (2 * math.log(theta))
164
+
165
+
166
+ def precompute_freqs_cis(
167
+ dim: int,
168
+ end: int,
169
+ theta: float,
170
+ rope_scaling: Optional[dict] = None,
171
+ ) -> tuple[torch.Tensor, torch.Tensor]:
172
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
173
+ attention_factor = 1.0
174
+ if rope_scaling and str(rope_scaling.get("type", "yarn")).lower() == "yarn":
175
+ factor = float(rope_scaling.get("factor", 1.0))
176
+ if factor > 1.0:
177
+ original = int(rope_scaling.get("original_max_position_embeddings", end))
178
+ beta_fast = float(rope_scaling.get("beta_fast", 32.0))
179
+ beta_slow = float(rope_scaling.get("beta_slow", 1.0))
180
+ low = math.floor(_yarn_correction_dim(beta_fast, dim, theta, original))
181
+ high = math.ceil(_yarn_correction_dim(beta_slow, dim, theta, original))
182
+ ramp = _yarn_linear_ramp(low, high, dim // 2)
183
+ freqs = freqs / factor * (1.0 - ramp) + freqs * ramp
184
+ attention_factor = float(rope_scaling.get("attention_factor", 1.0))
185
+ t = torch.arange(end)
186
+ freqs = torch.outer(t, freqs).float()
187
+ freqs_cos = torch.cat([torch.cos(freqs), torch.cos(freqs)], dim=-1) * attention_factor
188
+ freqs_sin = torch.cat([torch.sin(freqs), torch.sin(freqs)], dim=-1) * attention_factor
189
+ return freqs_cos, freqs_sin
190
+
191
+
192
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
193
+ return torch.cat((-x[..., x.shape[-1] // 2 :], x[..., : x.shape[-1] // 2]), dim=-1)
194
+
195
+
196
+ def apply_rope_to_single(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
197
+ if cos.dim() == 2:
198
+ cos = cos.unsqueeze(0).unsqueeze(0)
199
+ sin = sin.unsqueeze(0).unsqueeze(0)
200
+ elif cos.dim() == 3:
201
+ cos = cos.unsqueeze(1)
202
+ sin = sin.unsqueeze(1)
203
+ return (x * cos) + (rotate_half(x) * sin)
204
+
205
+
206
+ class RMSNorm(nn.Module):
207
+ def __init__(self, dim: int, eps: float = 1e-6):
208
+ super().__init__()
209
+ self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
210
+ self.eps = eps
211
+
212
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
213
+ out = x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
214
+ return (out * self.weight.float()).to(x.dtype)
215
+
216
+
217
+ class SEBlock(nn.Module):
218
+ def __init__(self, dim: int, reduction: int = 16, act: Optional[nn.Module] = None):
219
+ super().__init__()
220
+ reduction = max(reduction, dim // reduction)
221
+ self.se = nn.Sequential(
222
+ nn.Linear(dim, reduction, bias=False),
223
+ act or nn.SiLU(),
224
+ nn.Linear(reduction, dim, bias=False),
225
+ nn.Sigmoid(),
226
+ )
227
+
228
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
229
+ return x * self.se(x)
230
+
231
+
232
+ class MLGA(nn.Module):
233
+ """Multihead Latent Gated Attention"""
234
+
235
+ def __init__(self, config: YConfig31, layer_id: int):
236
+ super().__init__()
237
+ self.layer_id = layer_id
238
+ self.hidden_size = config.hidden_size
239
+ self.num_heads = config.num_heads
240
+ self.dropout = config.dropout
241
+ self.kv_lora_rank = config.mla_kv_lora_rank
242
+ self.qk_nope_head_dim = config.mla_qk_nope_head_dim
243
+ self.qk_rope_head_dim = config.mla_qk_rope_head_dim
244
+ self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
245
+ self.attn_impl = config.mla_attn_impl
246
+ self.softmax_scale = self.qk_head_dim**-0.5
247
+ self.out_dim = self.num_heads * self.kv_lora_rank
248
+
249
+ self.wq = nn.Linear(self.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
250
+ self.wkv_a = nn.Linear(self.hidden_size, self.kv_lora_rank + self.qk_rope_head_dim, bias=False)
251
+ self.kv_norm = RMSNorm(self.kv_lora_rank, config.rms_norm_eps)
252
+ self.wkv_b = nn.Linear(self.kv_lora_rank, self.num_heads * self.qk_nope_head_dim, bias=False)
253
+ self.z_proj = nn.Linear(self.hidden_size, self.out_dim, bias=False)
254
+ self.o_proj = nn.Linear(self.out_dim, self.hidden_size, bias=False)
255
+
256
+ def _project_q(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
257
+ bsz, seq_len, _ = x.shape
258
+ q = self.wq(x).reshape(bsz, seq_len, self.num_heads, self.qk_head_dim)
259
+ return q.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
260
+
261
+ def _project_kv(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
262
+ raw = self.wkv_a(x)
263
+ c_kv, k_pe = raw.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
264
+ c_kv = self.kv_norm(c_kv)
265
+ k_pe = apply_rope_to_single(k_pe.unsqueeze(1), cos, sin).permute(0, 2, 1, 3)
266
+ return c_kv, k_pe
267
+
268
+ def _explicit_kv(self, c_kv: torch.Tensor, k_pe: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
269
+ bsz, seq_len, _ = c_kv.shape
270
+ k_nope = self.wkv_b(c_kv).reshape(bsz, seq_len, self.num_heads, self.qk_nope_head_dim)
271
+ k = torch.cat([k_nope, k_pe.expand(-1, -1, self.num_heads, -1)], dim=-1)
272
+ v = c_kv.unsqueeze(2).expand(-1, -1, self.num_heads, -1)
273
+ return k, v
274
+
275
+ def _attention_mask(self, attention_mask: Optional[torch.Tensor], bsz: int, seq_len: int, total_len: int):
276
+ if attention_mask is None:
277
+ return None
278
+ if attention_mask.shape[-1] != total_len:
279
+ attention_mask = attention_mask[..., -total_len:]
280
+ mask = attention_mask.reshape(bsz, 1, 1, total_len).bool()
281
+ return mask.expand(bsz, self.num_heads, seq_len, total_len)
282
+
283
+ def _forward_sdpa(
284
+ self,
285
+ q_nope: torch.Tensor,
286
+ q_pe: torch.Tensor,
287
+ c_kv: torch.Tensor,
288
+ k_pe: torch.Tensor,
289
+ z: torch.Tensor,
290
+ attention_mask: Optional[torch.Tensor],
291
+ ) -> torch.Tensor:
292
+ bsz, seq_len, _, _ = q_nope.shape
293
+ total_len = c_kv.shape[1]
294
+ k, v = self._explicit_kv(c_kv, k_pe)
295
+ q = torch.cat([q_nope, q_pe], dim=-1).permute(0, 2, 1, 3)
296
+ k = k.permute(0, 2, 1, 3)
297
+ v = v.permute(0, 2, 1, 3)
298
+ attn_mask = self._attention_mask(attention_mask, bsz, seq_len, total_len)
299
+ is_causal = attention_mask is None and seq_len == total_len
300
+ out = F.scaled_dot_product_attention(
301
+ q,
302
+ k,
303
+ v,
304
+ attn_mask=attn_mask,
305
+ dropout_p=0.0,
306
+ is_causal=is_causal,
307
+ scale=self.softmax_scale,
308
+ )
309
+ out = out.permute(0, 2, 1, 3).reshape(bsz, seq_len, self.out_dim)
310
+ out = out * torch.sigmoid(z)
311
+ return self.o_proj(out)
312
+
313
+ def _forward_absorb(
314
+ self,
315
+ q_nope: torch.Tensor,
316
+ q_pe: torch.Tensor,
317
+ c_kv: torch.Tensor,
318
+ k_pe: torch.Tensor,
319
+ z: torch.Tensor,
320
+ attention_mask: Optional[torch.Tensor],
321
+ ) -> torch.Tensor:
322
+ bsz, seq_len, _, _ = q_nope.shape
323
+ total_len = c_kv.shape[1]
324
+ w = self.wkv_b.weight.reshape(self.num_heads, self.qk_nope_head_dim, self.kv_lora_rank)
325
+ q_nope_c = torch.einsum("bshd,hdc->bshc", q_nope, w)
326
+ scores = torch.einsum("bshc,btc->bsht", q_nope_c, c_kv)
327
+ scores = scores + torch.einsum("bshr,btr->bsht", q_pe, k_pe.squeeze(2))
328
+ scores = scores * self.softmax_scale
329
+
330
+ causal = torch.full((seq_len, seq_len), float("-inf"), device=scores.device, dtype=scores.dtype)
331
+ causal = torch.triu(causal, diagonal=1).reshape(1, seq_len, 1, seq_len)
332
+ scores = scores + F.pad(causal, (total_len - seq_len, 0), value=0.0)
333
+ if attention_mask is not None:
334
+ if attention_mask.shape[-1] != total_len:
335
+ attention_mask = attention_mask[..., -total_len:]
336
+ scores = scores + (1.0 - attention_mask.reshape(bsz, 1, 1, total_len).float()) * -1e9
337
+ probs = torch.softmax(scores.float(), dim=-1).to(q_nope.dtype)
338
+ out = torch.einsum("bsht,btc->bshc", probs, c_kv).reshape(bsz, seq_len, self.out_dim)
339
+ out = out * torch.sigmoid(z)
340
+ return self.o_proj(out)
341
+
342
+ def forward(
343
+ self,
344
+ x: torch.Tensor,
345
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
346
+ past_key_values: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
347
+ attention_mask: Optional[torch.Tensor] = None,
348
+ use_cache: bool = False,
349
+ **kwargs,
350
+ ) -> tuple[torch.Tensor, Optional[tuple[torch.Tensor, torch.Tensor]]]:
351
+ bsz, seq_len, _ = x.shape
352
+ cos, sin = position_embeddings
353
+ if cos.dim() == 2:
354
+ cos = cos[:seq_len, : self.qk_rope_head_dim]
355
+ sin = sin[:seq_len, : self.qk_rope_head_dim]
356
+ else:
357
+ cos = cos[:, :seq_len, : self.qk_rope_head_dim]
358
+ sin = sin[:, :seq_len, : self.qk_rope_head_dim]
359
+ q_nope, q_pe = self._project_q(x)
360
+ q_pe = apply_rope_to_single(q_pe.permute(0, 2, 1, 3), cos, sin).permute(0, 2, 1, 3)
361
+ c_kv, k_pe = self._project_kv(x, cos, sin)
362
+ z = self.z_proj(x)
363
+
364
+ if past_key_values is not None:
365
+ past_c, past_pe = past_key_values
366
+ c_kv = torch.cat([past_c, c_kv], dim=1)
367
+ k_pe = torch.cat([past_pe, k_pe], dim=1)
368
+ new_past = (c_kv, k_pe) if use_cache else None
369
+
370
+ if self.attn_impl == "naive":
371
+ out = self._forward_sdpa(q_nope, q_pe, c_kv, k_pe, z, attention_mask)
372
+ else:
373
+ out = self._forward_absorb(q_nope, q_pe, c_kv, k_pe, z, attention_mask)
374
+ return out, new_past
375
+
376
+
377
+ class SwiGLU(nn.Module):
378
+ def __init__(self, config: YConfig31, intermediate_size: Optional[int] = None):
379
+ super().__init__()
380
+ inter = intermediate_size or config.intermediate_size
381
+ self.up_proj = nn.Linear(config.hidden_size, inter, bias=False)
382
+ self.gate_proj = nn.Linear(config.hidden_size, inter, bias=False)
383
+ self.down_proj = nn.Linear(inter, config.hidden_size, bias=False)
384
+
385
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
386
+ up, gate = self.up_proj(x), self.gate_proj(x)
387
+ up = nn.functional.silu(gate) * up
388
+ return self.down_proj(up)
389
+
390
+
391
+ class SengramIndexer(nn.Module):
392
+ def __init__(self, config: YConfig31):
393
+ super().__init__()
394
+ self.hidden_size = int(config.hidden_size)
395
+ self.bucket_size = int(config.sengram_bucket_size or 4096)
396
+ self.topk = max(1, min(int(config.sengram_topk), self.bucket_size))
397
+ self.bucket_proj = nn.Linear(self.hidden_size, self.bucket_size, bias=False)
398
+
399
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
400
+ bucket_logits = self.bucket_proj(hidden_states)
401
+ route_scores = torch.softmax(bucket_logits.float(), dim=-1)
402
+ topk_ids = torch.topk(route_scores, k=self.topk, dim=-1, sorted=False).indices
403
+ topk_scores = route_scores.gather(-1, topk_ids)
404
+ denom = topk_scores.sum(dim=-1, keepdim=True).clamp_min(1e-20)
405
+ topk_scores = (topk_scores / denom).to(bucket_logits.dtype)
406
+ return topk_ids, topk_scores
407
+
408
+
409
+ class SengramPLE(nn.Module):
410
+ def __init__(self, config: YConfig31):
411
+ super().__init__()
412
+ self.hidden_size = int(config.hidden_size)
413
+ self.embedding = nn.Embedding(int(config.sengram_bucket_size or 4096), self.hidden_size)
414
+ self.key_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
415
+ self.memory_norm = RMSNorm(self.hidden_size, config.rms_norm_eps)
416
+ self.key_norm = RMSNorm(self.hidden_size, config.rms_norm_eps)
417
+ self.query_norm = RMSNorm(self.hidden_size, config.rms_norm_eps)
418
+
419
+ def forward(
420
+ self,
421
+ hidden_states: torch.Tensor,
422
+ topk_ids: torch.Tensor,
423
+ topk_scores: torch.Tensor,
424
+ ) -> torch.Tensor:
425
+ topk_embed = F.embedding(topk_ids, self.embedding.weight)
426
+ return (topk_embed * topk_scores.unsqueeze(-1).to(topk_embed.dtype)).sum(dim=-2)
427
+
428
+
429
+ class YBlock31(nn.Module):
430
+ def __init__(self, config: YConfig31, layer_id: int):
431
+ super().__init__()
432
+ self.use_sengram = bool(config.use_sengram)
433
+ self.input_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
434
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, config.rms_norm_eps)
435
+ self.sengram_ple = SengramPLE(config) if self.use_sengram else None
436
+ self.attn = MLGA(config, layer_id)
437
+ self.ffn = SwiGLU(config)
438
+ self.se1 = SEBlock(config.hidden_size, act=ACT2FN[config.hidden_act])
439
+ self.se2 = SEBlock(config.hidden_size, act=ACT2FN[config.hidden_act])
440
+
441
+ def forward(
442
+ self,
443
+ x: torch.Tensor,
444
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
445
+ past_key_values: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
446
+ use_cache: bool = False,
447
+ attention_mask: Optional[torch.Tensor] = None,
448
+ route_ids: Optional[torch.Tensor] = None,
449
+ route_scores: Optional[torch.Tensor] = None,
450
+ **kwargs,
451
+ ):
452
+ if self.use_sengram and route_ids is not None and route_scores is not None and self.sengram_ple is not None:
453
+ x = x + self.sengram_ple(x, route_ids, route_scores)
454
+ x0 = self.se1(self.input_layernorm(x))
455
+ attn_out, past = self.attn(
456
+ x0,
457
+ position_embeddings,
458
+ past_key_values=past_key_values,
459
+ attention_mask=attention_mask,
460
+ use_cache=use_cache,
461
+ )
462
+ x = x + attn_out
463
+ x0 = self.se2(self.post_attention_layernorm(x))
464
+ x = x + self.ffn(x0)
465
+ return x, past
466
+
467
+
468
+ class YModel31(nn.Module):
469
+ def __init__(self, config: YConfig31):
470
+ super().__init__()
471
+ self.config = config
472
+ self.vocab_size = config.vocab_size
473
+ self.num_layers = config.num_hidden_layers
474
+ self.dropout = config.dropout
475
+ self.use_sengram = bool(config.use_sengram)
476
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
477
+ self.sengram_indexer = SengramIndexer(config) if self.use_sengram else None
478
+ self.sengram = self.sengram_indexer
479
+ self.layers = nn.ModuleList([YBlock31(config, i) for i in range(config.num_hidden_layers)])
480
+ self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
481
+ freqs_cos, freqs_sin = precompute_freqs_cis(
482
+ dim=config.mla_qk_rope_head_dim,
483
+ end=config.max_position_embeddings,
484
+ theta=config.rope_theta,
485
+ rope_scaling=config.rope_scaling,
486
+ )
487
+ self.register_buffer("freqs_cos", freqs_cos, persistent=False)
488
+ self.register_buffer("freqs_sin", freqs_sin, persistent=False)
489
+
490
+ def forward(
491
+ self,
492
+ input_ids: Optional[torch.Tensor] = None,
493
+ attention_mask: Optional[torch.Tensor] = None,
494
+ past_key_values: Optional[list] = None,
495
+ use_cache: bool = False,
496
+ cache_position: Optional[torch.LongTensor] = None,
497
+ position_ids: Optional[torch.LongTensor] = None,
498
+ **kwargs,
499
+ ):
500
+ bsz, seq_len = input_ids.shape
501
+ if use_cache and past_key_values is None:
502
+ past_key_values = [None] * self.num_layers
503
+ if cache_position is None:
504
+ if past_key_values is not None and past_key_values[0] is not None:
505
+ past_seen = past_key_values[0][0].shape[1]
506
+ else:
507
+ past_seen = 0
508
+ cache_position = torch.arange(past_seen, past_seen + seq_len, device=input_ids.device)
509
+
510
+ x = self.embed_tokens(input_ids)
511
+ if position_ids is None:
512
+ position_ids = cache_position
513
+ position_embeddings = (self.freqs_cos[position_ids].to(x.device), self.freqs_sin[position_ids].to(x.device))
514
+ route_ids = None
515
+ route_scores = None
516
+ if self.use_sengram and self.sengram_indexer is not None:
517
+ route_ids, route_scores = self.sengram_indexer(x)
518
+ new_past = [] if use_cache else None
519
+
520
+ for i, layer in enumerate(self.layers):
521
+ past = past_key_values[i] if past_key_values is not None else None
522
+ x, layer_past = layer(
523
+ x,
524
+ position_embeddings=position_embeddings,
525
+ past_key_values=past,
526
+ attention_mask=attention_mask,
527
+ use_cache=use_cache,
528
+ route_ids=route_ids,
529
+ route_scores=route_scores,
530
+ )
531
+ if use_cache:
532
+ new_past.append(layer_past)
533
+ return self.norm(x), new_past
534
+
535
+
536
+ class YForCausalLM31(PreTrainedModel, GenerationMixin):
537
+ config_class = YConfig31
538
+
539
+ def __init__(self, config: Optional[YConfig31] = None):
540
+ self.config = config or YConfig31()
541
+ super().__init__(self.config)
542
+ self.model = YModel31(self.config)
543
+ self.lm_head = nn.Linear(self.config.hidden_size, self.config.vocab_size, bias=False)
544
+ self.model.embed_tokens.weight = self.lm_head.weight
545
+ self.OUT = CausalLMOutputWithPast()
546
+ dtype = {"float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32}.get(self.config.dtype)
547
+ if dtype is not None:
548
+ self.to(dtype)
549
+
550
+ def forward(
551
+ self,
552
+ input_ids: Optional[torch.Tensor] = None,
553
+ attention_mask: Optional[torch.Tensor] = None,
554
+ past_key_values: Optional[list] = None,
555
+ use_cache: bool = False,
556
+ logits_to_keep: Union[int, torch.Tensor] = 0,
557
+ cache_position: Optional[torch.LongTensor] = None,
558
+ **kwargs,
559
+ ):
560
+ h, past_kvs = self.model(
561
+ input_ids=input_ids,
562
+ attention_mask=attention_mask,
563
+ past_key_values=past_key_values,
564
+ use_cache=use_cache,
565
+ cache_position=cache_position,
566
+ position_ids=kwargs.get("position_ids", None),
567
+ )
568
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
569
+ logits = self.lm_head(h[:, slice_indices, :])
570
+ self.OUT.__setitem__("last_hidden_state", h)
571
+ self.OUT.__setitem__("logits", logits)
572
+ self.OUT.__setitem__("past_key_values", past_kvs)
573
+ return self.OUT
574
+
575
+ def generate(
576
+ self,
577
+ inputs,
578
+ attention_mask=None,
579
+ max_new_tokens=8192,
580
+ temperature=0.85,
581
+ top_p=0.85,
582
+ top_k=50,
583
+ eos_token_id=None,
584
+ streamer=None,
585
+ use_cache=True,
586
+ num_return_sequences=1,
587
+ do_sample=True,
588
+ repetition_penalty=1.0,
589
+ **kwargs,
590
+ ):
591
+ input_ids = kwargs.get("input_ids", inputs).repeat(num_return_sequences, 1)
592
+ attention_mask = attention_mask.repeat(num_return_sequences, 1) if attention_mask is not None else None
593
+ logits_processor = kwargs.get("logits_processor", None)
594
+ past_key_values = None
595
+ if streamer:
596
+ streamer.put(input_ids.cpu())
597
+ with torch.no_grad():
598
+ for _ in range(max_new_tokens):
599
+ if use_cache and past_key_values is not None:
600
+ outputs = self.forward(input_ids[:, -1:], None, past_key_values, use_cache=use_cache)
601
+ else:
602
+ outputs = self.forward(input_ids, attention_mask, past_key_values, use_cache=use_cache)
603
+ logits = outputs.logits[:, -1, :] / temperature
604
+ if repetition_penalty != 1.0:
605
+ for i in range(input_ids.shape[0]):
606
+ logits[i, torch.unique(input_ids[i])] /= repetition_penalty
607
+ if logits_processor is not None:
608
+ logits = logits_processor(input_ids, logits)
609
+ if top_k > 0:
610
+ logits[logits < torch.topk(logits, top_k)[0][..., -1, None]] = -float("inf")
611
+ if top_p < 1.0:
612
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
613
+ mask = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1) > top_p
614
+ mask[..., 1:], mask[..., 0] = mask[..., :-1].clone(), 0
615
+ logits[mask.scatter(1, sorted_indices, mask)] = -float("inf")
616
+ next_token = (
617
+ torch.multinomial(torch.softmax(logits, dim=-1), 1)
618
+ if do_sample
619
+ else torch.argmax(logits, dim=-1, keepdim=True)
620
+ )
621
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
622
+ if attention_mask is not None:
623
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1)
624
+ past_key_values = outputs.past_key_values
625
+ if streamer:
626
+ streamer.put(next_token.cpu())
627
+ if eos_token_id and (next_token == eos_token_id).any():
628
+ break
629
+ if streamer:
630
+ streamer.end()
631
+ return input_ids
632
+
633
+
634
+ def count_parameters(config: YConfig31) -> int:
635
+ return sum(p.numel() for p in YForCausalLM31(config).parameters())
636
+
637
+
638
+ def _load_state_dict(path: Union[str, Path]) -> dict[str, torch.Tensor]:
639
+ path = Path(path)
640
+ if path.is_dir():
641
+ safetensors_path = path / "model.safetensors"
642
+ bin_path = path / "pytorch_model.bin"
643
+ if safetensors_path.exists():
644
+ path = safetensors_path
645
+ elif bin_path.exists():
646
+ path = bin_path
647
+ else:
648
+ raise FileNotFoundError(f"no model.safetensors or pytorch_model.bin found in {path}")
649
+ if path.suffix == ".safetensors":
650
+ return load_safetensors(str(path), device="cpu")
651
+ return torch.load(path, map_location="cpu", weights_only=True)
652
+
653
+
654
+ def load_ymodel31_eval(path: Union[str, Path], config: Optional[YConfig31] = None, strict: bool = True) -> YForCausalLM31:
655
+ path = Path(path)
656
+ if config is None:
657
+ config_path = path / "config.json" if path.is_dir() else path.with_name("config.json")
658
+ if not config_path.exists():
659
+ raise FileNotFoundError("config is required when config.json is not next to the checkpoint")
660
+ config = YConfig31.from_json_file(str(config_path))
661
+ model = YForCausalLM31(config)
662
+ state = _load_state_dict(path)
663
+ model.load_state_dict(state, strict=strict)
664
+ model.eval()
665
+ return model
666
+
667
+
668
+ YModel31Eval = YModel31
669
+ YForCausalLM31Eval = YForCausalLM31
670
+
671
+
672
+ __all__ = [
673
+ "MLGA",
674
+ "RMSNorm",
675
+ "SEBlock",
676
+ "SengramIndexer",
677
+ "SengramPLE",
678
+ "SwiGLU",
679
+ "YBlock31",
680
+ "YConfig31",
681
+ "YForCausalLM31",
682
+ "YForCausalLM31Eval",
683
+ "YModel31",
684
+ "YModel31Eval",
685
+ "apply_rope_to_single",
686
+ "count_parameters",
687
+ "load_ymodel31_eval",
688
+ "precompute_freqs_cis",
689
+ ]