dzhang50 commited on
Commit
08ac121
·
verified ·
1 Parent(s): 1e7ffb2

Upload folder using huggingface_hub

Browse files
RESHARD_INFO.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_dir": "/home/ubuntu/checkpoints/ri-hero-65b-11xC-topsel-3m-1c877500-wc2/hf/step877500",
3
+ "source_manifest": {
4
+ "fingerprint": "584628ff3081cd3f19e2d3ddde02d58eb2228fd6f0888e9cdb8baff3cc5fb9f6",
5
+ "model_safetensors_sha256": "fe0af61d5b75ebd80446457e4f91988cd7811ae0bd492e44069ccf05a47d60ae"
6
+ },
7
+ "max_shard_size_bytes": 8000000000,
8
+ "total_size_bytes": 129565378720,
9
+ "num_shards": 17,
10
+ "shard_sha256": {
11
+ "model-00001-of-00017.safetensors": "2defe6ee993a7a8667f286e2f0d171111601d8020ca69f666c005fd4986a99c9",
12
+ "model-00002-of-00017.safetensors": "eaf95a952ae1ef67c1190e3fd7160f62fac92cb34aadafca23107ecdbb0f0816",
13
+ "model-00003-of-00017.safetensors": "f081888035e5119ef338fcc87b716e30fe1b936e5c2128ec3efe80e38d7d74ab",
14
+ "model-00004-of-00017.safetensors": "33df2d04e5bf1fa248782cc81c77ca19bb5d045e4385ab6ad77bbd326a89abbb",
15
+ "model-00005-of-00017.safetensors": "07391a73962b13a26c39ea61d849fc4f80853e994d1c153a28e9c6256d4c0290",
16
+ "model-00006-of-00017.safetensors": "f4fadf975816e1fe33ea9fe3ddbd40c6b1e61761c1677368d8e1b407ccce5594",
17
+ "model-00007-of-00017.safetensors": "5740d3fb1e1ff8d15a5de7e1e1fe235c1534d41ea44f6640872f5cc733b293c8",
18
+ "model-00008-of-00017.safetensors": "ebd43c1c0f281879ef5324992298e7432b93390c9a251f5e1f43a1bd3de09484",
19
+ "model-00009-of-00017.safetensors": "fe21a5ac74f580a0d30f33f6aaeb97c204fd650cf377c77d6dd6d0c30547455b",
20
+ "model-00010-of-00017.safetensors": "9126a023ec3e2f87da062b97e0f5ee6b61d35cde9154a9f5e24eaf08a381d5d0",
21
+ "model-00011-of-00017.safetensors": "0edc2746125355cf2dcf041ec99edab4b1645bc4965128645ed15953cfe02b2c",
22
+ "model-00012-of-00017.safetensors": "0d3c5a82a77a38c4713ff1146c05db9cd353985430a7a7fbf4c6faa4a2655f0c",
23
+ "model-00013-of-00017.safetensors": "e0269bf7f5829e10661f22e893cb8b477bcfcbd8f250a62cc934c11670174c64",
24
+ "model-00014-of-00017.safetensors": "9cc7af6165de693dc58b871e7e031298c17e3ae542d2fbaf3d4c713c7e925603",
25
+ "model-00015-of-00017.safetensors": "1b8711409f6c45f182855d6c77bc4603201dbc2f8bbfb1b0400d14045c210897",
26
+ "model-00016-of-00017.safetensors": "5c0c5595a615657277925fd6a4ee1d483fa58b42c9c835eb31eb319c6a4916ee",
27
+ "model-00017-of-00017.safetensors": "e6b0f529781875827e7d6cb71ce441a273c44405f1e449434a7894e2b0a9017b"
28
+ },
29
+ "verified_against_source": true,
30
+ "copied_assets": [
31
+ "config.json",
32
+ "configuration_ricursive.py",
33
+ "modeling_ricursive.py",
34
+ "tokenizer.json",
35
+ "tokenizer_config.json",
36
+ "special_tokens_map.json",
37
+ "chat_template.jinja"
38
+ ]
39
+ }
chat_template.jinja ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {% for message in messages %}{{'<|im_start|>' + message['role'] + '
2
+ ' + message['content'] + '<|im_end|>' + '
3
+ '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
4
+ ' }}{% endif %}
config.json ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "RicursiveForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_ricursive.RicursiveConfig",
7
+ "AutoModel": "modeling_ricursive.RicursiveModel",
8
+ "AutoModelForCausalLM": "modeling_ricursive.RicursiveForCausalLM"
9
+ },
10
+ "bos_token_id": 100257,
11
+ "embed_scale": 71.55417527999327,
12
+ "eos_token_id": 100257,
13
+ "ffn_clamp_threshold": 20.0,
14
+ "gate_full_precision": true,
15
+ "head_dim": 128,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 5120,
18
+ "hybrid_layer_pattern": [
19
+ 1,
20
+ 1,
21
+ 1,
22
+ 1,
23
+ 0,
24
+ 1,
25
+ 1,
26
+ 1,
27
+ 1,
28
+ 0,
29
+ 1,
30
+ 1,
31
+ 1,
32
+ 1,
33
+ 0,
34
+ 1,
35
+ 1,
36
+ 1,
37
+ 1,
38
+ 0,
39
+ 1,
40
+ 1,
41
+ 1,
42
+ 1,
43
+ 0,
44
+ 1,
45
+ 1,
46
+ 1,
47
+ 1,
48
+ 0,
49
+ 1,
50
+ 1,
51
+ 1,
52
+ 1,
53
+ 0,
54
+ 1,
55
+ 1,
56
+ 1,
57
+ 1,
58
+ 0,
59
+ 1,
60
+ 1,
61
+ 1,
62
+ 1,
63
+ 0,
64
+ 1,
65
+ 1,
66
+ 1,
67
+ 1,
68
+ 0,
69
+ 1,
70
+ 1,
71
+ 1,
72
+ 1,
73
+ 0,
74
+ 1,
75
+ 1,
76
+ 1,
77
+ 1,
78
+ 0,
79
+ 1,
80
+ 1,
81
+ 1,
82
+ 1,
83
+ 0,
84
+ 1,
85
+ 1,
86
+ 1,
87
+ 1,
88
+ 0,
89
+ 1,
90
+ 1,
91
+ 1,
92
+ 1,
93
+ 0,
94
+ 1,
95
+ 1,
96
+ 1,
97
+ 1,
98
+ 0
99
+ ],
100
+ "intermediate_size": 40960,
101
+ "is_hybrid_swa": true,
102
+ "layer_types": [
103
+ "sliding_attention",
104
+ "sliding_attention",
105
+ "sliding_attention",
106
+ "sliding_attention",
107
+ "full_attention",
108
+ "sliding_attention",
109
+ "sliding_attention",
110
+ "sliding_attention",
111
+ "sliding_attention",
112
+ "full_attention",
113
+ "sliding_attention",
114
+ "sliding_attention",
115
+ "sliding_attention",
116
+ "sliding_attention",
117
+ "full_attention",
118
+ "sliding_attention",
119
+ "sliding_attention",
120
+ "sliding_attention",
121
+ "sliding_attention",
122
+ "full_attention",
123
+ "sliding_attention",
124
+ "sliding_attention",
125
+ "sliding_attention",
126
+ "sliding_attention",
127
+ "full_attention",
128
+ "sliding_attention",
129
+ "sliding_attention",
130
+ "sliding_attention",
131
+ "sliding_attention",
132
+ "full_attention",
133
+ "sliding_attention",
134
+ "sliding_attention",
135
+ "sliding_attention",
136
+ "sliding_attention",
137
+ "full_attention",
138
+ "sliding_attention",
139
+ "sliding_attention",
140
+ "sliding_attention",
141
+ "sliding_attention",
142
+ "full_attention",
143
+ "sliding_attention",
144
+ "sliding_attention",
145
+ "sliding_attention",
146
+ "sliding_attention",
147
+ "full_attention",
148
+ "sliding_attention",
149
+ "sliding_attention",
150
+ "sliding_attention",
151
+ "sliding_attention",
152
+ "full_attention",
153
+ "sliding_attention",
154
+ "sliding_attention",
155
+ "sliding_attention",
156
+ "sliding_attention",
157
+ "full_attention",
158
+ "sliding_attention",
159
+ "sliding_attention",
160
+ "sliding_attention",
161
+ "sliding_attention",
162
+ "full_attention",
163
+ "sliding_attention",
164
+ "sliding_attention",
165
+ "sliding_attention",
166
+ "sliding_attention",
167
+ "full_attention",
168
+ "sliding_attention",
169
+ "sliding_attention",
170
+ "sliding_attention",
171
+ "sliding_attention",
172
+ "full_attention",
173
+ "sliding_attention",
174
+ "sliding_attention",
175
+ "sliding_attention",
176
+ "sliding_attention",
177
+ "full_attention",
178
+ "sliding_attention",
179
+ "sliding_attention",
180
+ "sliding_attention",
181
+ "sliding_attention",
182
+ "full_attention"
183
+ ],
184
+ "max_position_embeddings": 8192,
185
+ "model_type": "ricursive",
186
+ "num_attention_heads": 80,
187
+ "num_hidden_layers": 80,
188
+ "num_key_value_heads": 8,
189
+ "pad_token_id": 100277,
190
+ "rms_norm_eps": 1e-06,
191
+ "rope_theta": 10000.0,
192
+ "sliding_window": 1024,
193
+ "tie_word_embeddings": false,
194
+ "transformers_version": "4.57.1",
195
+ "use_cache": true,
196
+ "use_gated_attention": true,
197
+ "use_valres": true,
198
+ "vocab_size": 100352
199
+ }
configuration_ricursive.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace PretrainedConfig for the Ricursive transformer architecture."""
2
+
3
+ from transformers import PretrainedConfig
4
+
5
+
6
+ class RicursiveConfig(PretrainedConfig):
7
+ """
8
+ Configuration for the Ricursive transformer.
9
+
10
+ Key architectural features:
11
+ - PeriNorm blocks (4 layer norms per block instead of 2)
12
+ - Gated attention with elementwise sigmoid gate
13
+ - Mixed local/global layers: local layers use sliding window + RoPE,
14
+ global layers (every 5th) use full attention with no RoPE
15
+ - Per-head Q/K RMSNorm
16
+ """
17
+
18
+ model_type = "ricursive"
19
+
20
+ def __init__(
21
+ self,
22
+ vocab_size=100352,
23
+ hidden_size=3072,
24
+ intermediate_size=24576,
25
+ num_hidden_layers=50,
26
+ num_attention_heads=48,
27
+ num_key_value_heads=8,
28
+ head_dim=128,
29
+ max_position_embeddings=2048,
30
+ hidden_act="silu",
31
+ rms_norm_eps=1e-6,
32
+ rope_theta=10000.0,
33
+ sliding_window=1024,
34
+ layer_types=None,
35
+ use_gated_attention=True,
36
+ gate_full_precision=True,
37
+ use_valres=False,
38
+ ffn_clamp_threshold=None,
39
+ embed_scale=None,
40
+ tie_word_embeddings=False,
41
+ **kwargs,
42
+ ):
43
+ self.vocab_size = vocab_size
44
+ self.hidden_size = hidden_size
45
+ self.intermediate_size = intermediate_size
46
+ self.num_hidden_layers = num_hidden_layers
47
+ self.num_attention_heads = num_attention_heads
48
+ self.num_key_value_heads = num_key_value_heads
49
+ self.head_dim = head_dim
50
+ self.max_position_embeddings = max_position_embeddings
51
+ self.hidden_act = hidden_act
52
+ self.rms_norm_eps = rms_norm_eps
53
+ self.rope_theta = rope_theta
54
+ self.sliding_window = sliding_window
55
+ self.use_gated_attention = use_gated_attention
56
+ self.gate_full_precision = gate_full_precision
57
+ self.use_valres = use_valres
58
+ self.ffn_clamp_threshold = ffn_clamp_threshold
59
+ # Hybrid-SWA metadata is derived below. Serialized copies must not override the
60
+ # architecture encoded by layer_types.
61
+ kwargs.pop("is_hybrid_swa", None)
62
+ kwargs.pop("hybrid_layer_pattern", None)
63
+ # Embedding scale convention (see modeling_ricursive.RicursiveModel.forward):
64
+ # - non-folded checkpoints set embed_scale (e.g. sqrt(hidden_size)) and the model
65
+ # scales the embeddings at runtime;
66
+ # - folded checkpoints bake the scale into embed_tokens.weight and leave this None.
67
+ # Either way the SGLang native port (sglang_ricursive) reads this same key, so the
68
+ # served and trained forwards agree.
69
+ self.embed_scale = embed_scale
70
+
71
+ # Per-layer type: "sliding_attention" (window + RoPE) or "full_attention" (no RoPE)
72
+ # These names follow the HuggingFace PretrainedConfig layer_types validation.
73
+ if layer_types is not None:
74
+ self.layer_types = layer_types
75
+ else:
76
+ # Default: every 5th layer is full_attention (indices 4, 9, 14, ...)
77
+ self.layer_types = [
78
+ "full_attention" if i % 5 == 4 else "sliding_attention"
79
+ for i in range(num_hidden_layers)
80
+ ]
81
+ if len(self.layer_types) != num_hidden_layers:
82
+ raise ValueError(
83
+ f"layer_types has {len(self.layer_types)} entries, expected {num_hidden_layers}"
84
+ )
85
+ invalid_layer_types = set(self.layer_types) - {
86
+ "sliding_attention",
87
+ "full_attention",
88
+ }
89
+ if invalid_layer_types:
90
+ raise ValueError(f"unsupported Ricursive layer_types: {sorted(invalid_layer_types)}")
91
+
92
+ # SGLang's compact hybrid KV allocator uses 1 for sliding attention and 0 for full
93
+ # attention. Keep these fields fully derived so they cannot drift from model semantics.
94
+ self.hybrid_layer_pattern = [
95
+ 1 if layer_type == "sliding_attention" else 0 for layer_type in self.layer_types
96
+ ]
97
+ self.is_hybrid_swa = 0 in self.hybrid_layer_pattern and 1 in self.hybrid_layer_pattern
98
+
99
+ # Standard HF config fields expected by modeling code
100
+ self.use_cache = kwargs.pop("use_cache", True)
101
+
102
+ self.base_model_tp_plan = {
103
+ "layers.*.self_attn.q_proj": "colwise",
104
+ "layers.*.self_attn.k_proj": "colwise",
105
+ "layers.*.self_attn.v_proj": "colwise",
106
+ "layers.*.self_attn.o_proj": "rowwise",
107
+ "layers.*.self_attn.g_proj": "colwise",
108
+ "layers.*.mlp.gate_proj": "colwise",
109
+ "layers.*.mlp.up_proj": "colwise",
110
+ "layers.*.mlp.down_proj": "rowwise",
111
+ }
112
+ self.auto_map = {
113
+ "AutoConfig": "configuration_ricursive.RicursiveConfig",
114
+ "AutoModel": "modeling_ricursive.RicursiveModel",
115
+ "AutoModelForCausalLM": "modeling_ricursive.RicursiveForCausalLM",
116
+ }
117
+
118
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
119
+
120
+ # Must be set AFTER super().__init__ — HF's PretrainedConfig.__init__
121
+ # pops "architectures" from kwargs (default None) and assigns it to
122
+ # self.architectures, which would otherwise overwrite our value.
123
+ self.architectures = ["RicursiveForCausalLM"]
model-00001-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2defe6ee993a7a8667f286e2f0d171111601d8020ca69f666c005fd4986a99c9
3
+ size 7822560416
model-00002-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eaf95a952ae1ef67c1190e3fd7160f62fac92cb34aadafca23107ecdbb0f0816
3
+ size 7969393682
model-00003-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f081888035e5119ef338fcc87b716e30fe1b936e5c2128ec3efe80e38d7d74ab
3
+ size 7969393746
model-00004-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33df2d04e5bf1fa248782cc81c77ca19bb5d045e4385ab6ad77bbd326a89abbb
3
+ size 7969393762
model-00005-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07391a73962b13a26c39ea61d849fc4f80853e994d1c153a28e9c6256d4c0290
3
+ size 7969393762
model-00006-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4fadf975816e1fe33ea9fe3ddbd40c6b1e61761c1677368d8e1b407ccce5594
3
+ size 7969393762
model-00007-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5740d3fb1e1ff8d15a5de7e1e1fe235c1534d41ea44f6640872f5cc733b293c8
3
+ size 7969393762
model-00008-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebd43c1c0f281879ef5324992298e7432b93390c9a251f5e1f43a1bd3de09484
3
+ size 7969393762
model-00009-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe21a5ac74f580a0d30f33f6aaeb97c204fd650cf377c77d6dd6d0c30547455b
3
+ size 7969393762
model-00010-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9126a023ec3e2f87da062b97e0f5ee6b61d35cde9154a9f5e24eaf08a381d5d0
3
+ size 7969393762
model-00011-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0edc2746125355cf2dcf041ec99edab4b1645bc4965128645ed15953cfe02b2c
3
+ size 7969393762
model-00012-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d3c5a82a77a38c4713ff1146c05db9cd353985430a7a7fbf4c6faa4a2655f0c
3
+ size 7969393762
model-00013-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e0269bf7f5829e10661f22e893cb8b477bcfcbd8f250a62cc934c11670174c64
3
+ size 7969393762
model-00014-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9cc7af6165de693dc58b871e7e031298c17e3ae542d2fbaf3d4c713c7e925603
3
+ size 7969393762
model-00015-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b8711409f6c45f182855d6c77bc4603201dbc2f8bbfb1b0400d14045c210897
3
+ size 7969393762
model-00016-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c0c5595a615657277925fd6a4ee1d483fa58b42c9c835eb31eb319c6a4916ee
3
+ size 7969393762
model-00017-of-00017.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6b0f529781875827e7d6cb71ce441a273c44405f1e449434a7894e2b0a9017b
3
+ size 2202052818
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_ricursive.py ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace modeling implementation for the Ricursive transformer architecture.
2
+
3
+ Designed for inference with vLLM (via --trust-remote-code). Key differences from
4
+ standard Llama/Mistral:
5
+ - PeriNorm blocks: 4 layer norms per block (pre/post attention + pre/post FFN)
6
+ - Gated attention: elementwise sigmoid gate on attention output
7
+ - Mixed local/global layers: local = sliding window + RoPE, global = full attention + no RoPE
8
+ - Per-head Q/K RMSNorm
9
+ """
10
+
11
+ from typing import Optional, Tuple, Union
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ from transformers import PreTrainedModel
17
+ from transformers.cache_utils import Cache, DynamicCache
18
+ from transformers.modeling_outputs import (
19
+ BaseModelOutputWithPast,
20
+ CausalLMOutputWithPast,
21
+ )
22
+
23
+ from .configuration_ricursive import RicursiveConfig
24
+
25
+
26
+ class RicursiveRMSNorm(nn.Module):
27
+ def __init__(self, hidden_size: int, eps: float = 1e-6):
28
+ super().__init__()
29
+ self.weight = nn.Parameter(torch.ones(hidden_size))
30
+ self.eps = eps
31
+
32
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
33
+ input_dtype = hidden_states.dtype
34
+ hidden_states = hidden_states.float()
35
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
36
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
37
+ return self.weight * hidden_states.to(input_dtype)
38
+
39
+
40
+ class RicursiveRotaryEmbedding(nn.Module):
41
+ def __init__(self, dim: int, theta: float = 10000.0):
42
+ super().__init__()
43
+ self.dim = dim
44
+ self.theta = theta
45
+ # NOTE: inv_freq is computed on-the-fly in forward() rather than stored
46
+ # as a buffer, because non-persistent buffers get corrupted during
47
+ # from_pretrained() loading.
48
+
49
+ @torch.no_grad()
50
+ def forward(self, x: torch.Tensor, position_ids: torch.Tensor):
51
+ inv_freq = 1.0 / (
52
+ self.theta ** (torch.arange(0, self.dim, 2, device=x.device).float() / self.dim)
53
+ )
54
+ inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
55
+ position_ids_expanded = position_ids[:, None, :].float()
56
+
57
+ device_type = x.device.type
58
+ with torch.autocast(device_type=device_type, enabled=False):
59
+ freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2)
60
+ emb = torch.cat((freqs, freqs), dim=-1)
61
+ cos = emb.cos()
62
+ sin = emb.sin()
63
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
64
+
65
+
66
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
67
+ x1 = x[..., : x.shape[-1] // 2]
68
+ x2 = x[..., x.shape[-1] // 2 :]
69
+ return torch.cat((-x2, x1), dim=-1)
70
+
71
+
72
+ def apply_rotary_pos_emb(
73
+ q: torch.Tensor,
74
+ k: torch.Tensor,
75
+ cos: torch.Tensor,
76
+ sin: torch.Tensor,
77
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
78
+ cos = cos.unsqueeze(1) # (B, 1, T, dim)
79
+ sin = sin.unsqueeze(1) # (B, 1, T, dim)
80
+ # OLMo-core applies RoPE in full precision (float32) for numerical stability
81
+ orig_dtype = q.dtype
82
+ q_float, k_float = q.float(), k.float()
83
+ cos_float, sin_float = cos.float(), sin.float()
84
+ q_embed = (q_float * cos_float) + (rotate_half(q_float) * sin_float)
85
+ k_embed = (k_float * cos_float) + (rotate_half(k_float) * sin_float)
86
+ return q_embed.to(orig_dtype), k_embed.to(orig_dtype)
87
+
88
+
89
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
90
+ if n_rep == 1:
91
+ return hidden_states
92
+ batch, num_kv_heads, slen, head_dim = hidden_states.shape
93
+ hidden_states = hidden_states[:, :, None, :, :].expand(
94
+ batch, num_kv_heads, n_rep, slen, head_dim
95
+ )
96
+ return hidden_states.reshape(batch, num_kv_heads * n_rep, slen, head_dim)
97
+
98
+
99
+ class RicursiveAttention(nn.Module):
100
+ def __init__(self, config: RicursiveConfig, layer_idx: int):
101
+ super().__init__()
102
+ self.config = config
103
+ self.layer_idx = layer_idx
104
+ self.layer_type = config.layer_types[layer_idx]
105
+
106
+ self.hidden_size = config.hidden_size
107
+ self.num_heads = config.num_attention_heads
108
+ self.num_kv_heads = config.num_key_value_heads
109
+ self.head_dim = config.head_dim
110
+ self.num_kv_groups = self.num_heads // self.num_kv_heads
111
+
112
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
113
+ self.k_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
114
+ self.v_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.head_dim, bias=False)
115
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
116
+ if config.use_valres:
117
+ self.value_res_lambda = nn.Parameter(torch.zeros(1))
118
+
119
+ # Per-head Q/K norms (RMSNorm on head_dim)
120
+ self.q_norm = RicursiveRMSNorm(self.head_dim, eps=config.rms_norm_eps)
121
+ self.k_norm = RicursiveRMSNorm(self.head_dim, eps=config.rms_norm_eps)
122
+
123
+ # Gated attention
124
+ if config.use_gated_attention:
125
+ self.g_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
126
+
127
+ # RoPE only for local (sliding_attention) layers
128
+ if self.layer_type == "sliding_attention":
129
+ self.rotary_emb = RicursiveRotaryEmbedding(self.head_dim, theta=config.rope_theta)
130
+
131
+ def _apply_sliding_window_mask(
132
+ self,
133
+ attention_mask: Optional[torch.Tensor],
134
+ q_len: int,
135
+ kv_len: int,
136
+ dtype: torch.dtype,
137
+ device: torch.device,
138
+ cache_position: Optional[torch.LongTensor],
139
+ ) -> Optional[torch.Tensor]:
140
+ if self.layer_type != "sliding_attention":
141
+ return attention_mask
142
+
143
+ key_positions = torch.arange(kv_len, device=device)
144
+ if cache_position is not None:
145
+ query_positions = cache_position.to(device=device)
146
+ else:
147
+ query_positions = torch.arange(kv_len - q_len, kv_len, device=device)
148
+
149
+ window = self.config.sliding_window
150
+ allowed = (
151
+ (key_positions[None, :] <= query_positions[:, None])
152
+ & (key_positions[None, :] >= query_positions[:, None] - (window - 1))
153
+ )[None, None, :, :]
154
+
155
+ if attention_mask is None:
156
+ return allowed
157
+ if attention_mask.dtype == torch.bool:
158
+ return attention_mask & allowed
159
+ return attention_mask.masked_fill(~allowed, torch.finfo(dtype).min)
160
+
161
+ def forward(
162
+ self,
163
+ hidden_states: torch.Tensor,
164
+ attention_mask: Optional[torch.Tensor] = None,
165
+ position_ids: Optional[torch.Tensor] = None,
166
+ past_key_value: Optional[Cache] = None,
167
+ output_attentions: bool = False,
168
+ use_cache: bool = False,
169
+ cache_position: Optional[torch.LongTensor] = None,
170
+ value_residual: Optional[torch.Tensor] = None,
171
+ **kwargs,
172
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
173
+ bsz, q_len, _ = hidden_states.shape
174
+
175
+ # Project Q, K, V
176
+ q = self.q_proj(hidden_states)
177
+ k = self.k_proj(hidden_states)
178
+ value_states = hidden_states
179
+ if value_residual is not None:
180
+ if not self.config.use_valres:
181
+ raise RuntimeError("value_residual was supplied but config.use_valres is false")
182
+ blend = torch.sigmoid(self.value_res_lambda[0]).to(dtype=hidden_states.dtype)
183
+ value_states = torch.lerp(
184
+ value_residual.to(dtype=hidden_states.dtype), hidden_states, blend
185
+ )
186
+ v = self.v_proj(value_states)
187
+
188
+ # Reshape to (B, T, n_heads, head_dim) then transpose to (B, n_heads, T, head_dim)
189
+ q = q.view(bsz, q_len, self.num_heads, self.head_dim)
190
+ k = k.view(bsz, q_len, self.num_kv_heads, self.head_dim)
191
+ v = v.view(bsz, q_len, self.num_kv_heads, self.head_dim)
192
+
193
+ # Per-head Q/K norm (applied before transpose, on head_dim)
194
+ q = self.q_norm(q)
195
+ k = self.k_norm(k)
196
+
197
+ # Transpose to (B, n_heads, T, head_dim) for attention
198
+ q = q.transpose(1, 2)
199
+ k = k.transpose(1, 2)
200
+ v = v.transpose(1, 2)
201
+
202
+ # RoPE only for local layers
203
+ if self.layer_type == "sliding_attention":
204
+ cos, sin = self.rotary_emb(v, position_ids)
205
+ q, k = apply_rotary_pos_emb(q, k, cos, sin)
206
+
207
+ # KV cache
208
+ if past_key_value is not None:
209
+ k, v = past_key_value.update(k, v, self.layer_idx)
210
+
211
+ # GQA: expand KV heads
212
+ k = repeat_kv(k, self.num_kv_groups)
213
+ v = repeat_kv(v, self.num_kv_groups)
214
+
215
+ attention_mask = self._apply_sliding_window_mask(
216
+ attention_mask=attention_mask,
217
+ q_len=q.shape[2],
218
+ kv_len=k.shape[2],
219
+ dtype=q.dtype,
220
+ device=q.device,
221
+ cache_position=cache_position,
222
+ )
223
+
224
+ # Attention (use is_causal when no explicit mask for correct causal behavior)
225
+ # Cast to plain bool to avoid SymBool issues with torch.compile
226
+ is_causal = bool(attention_mask is None and q.shape[2] > 1)
227
+ attn_output = F.scaled_dot_product_attention(
228
+ q, k, v, attn_mask=attention_mask, dropout_p=0.0, is_causal=is_causal
229
+ )
230
+
231
+ # (B, n_heads, T, head_dim) -> (B, T, n_heads * head_dim)
232
+ attn_output = attn_output.transpose(1, 2).contiguous()
233
+
234
+ # Gated attention: output * sigmoid(g_proj(input))
235
+ if self.config.use_gated_attention:
236
+ gate = self.g_proj(hidden_states)
237
+ if self.config.gate_full_precision:
238
+ gate = gate.float()
239
+ gate = torch.sigmoid(gate).to(attn_output.dtype)
240
+ attn_output = attn_output.view(bsz, q_len, -1) * gate
241
+ else:
242
+ attn_output = attn_output.view(bsz, q_len, -1)
243
+
244
+ # Output projection
245
+ attn_output = self.o_proj(attn_output)
246
+
247
+ return attn_output, None, past_key_value
248
+
249
+
250
+ class RicursiveMLP(nn.Module):
251
+ def __init__(self, config: RicursiveConfig):
252
+ super().__init__()
253
+ self.clamp_threshold = config.ffn_clamp_threshold
254
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
255
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
256
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
257
+
258
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
259
+ gate = self.gate_proj(x)
260
+ up = self.up_proj(x)
261
+ if self.clamp_threshold:
262
+ gate = gate.clamp(min=None, max=self.clamp_threshold)
263
+ up = up.clamp(min=-self.clamp_threshold, max=self.clamp_threshold)
264
+ return self.down_proj(F.silu(gate) * up)
265
+
266
+
267
+ class RicursiveDecoderLayer(nn.Module):
268
+ """PeriNorm decoder layer with 4 layer norms."""
269
+
270
+ def __init__(self, config: RicursiveConfig, layer_idx: int):
271
+ super().__init__()
272
+ self.self_attn = RicursiveAttention(config, layer_idx)
273
+ self.mlp = RicursiveMLP(config)
274
+
275
+ # PeriNorm: 4 norms
276
+ self.input_layernorm = RicursiveRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
277
+ self.post_attention_layernorm = RicursiveRMSNorm(
278
+ config.hidden_size, eps=config.rms_norm_eps
279
+ )
280
+ self.pre_feedforward_layernorm = RicursiveRMSNorm(
281
+ config.hidden_size, eps=config.rms_norm_eps
282
+ )
283
+ self.post_feedforward_layernorm = RicursiveRMSNorm(
284
+ config.hidden_size, eps=config.rms_norm_eps
285
+ )
286
+
287
+ def forward(
288
+ self,
289
+ hidden_states: torch.Tensor,
290
+ attention_mask: Optional[torch.Tensor] = None,
291
+ position_ids: Optional[torch.Tensor] = None,
292
+ past_key_value: Optional[Cache] = None,
293
+ output_attentions: bool = False,
294
+ use_cache: bool = False,
295
+ cache_position: Optional[torch.LongTensor] = None,
296
+ value_residual: Optional[torch.Tensor] = None,
297
+ **kwargs,
298
+ ) -> Tuple[torch.Tensor, ...]:
299
+ # Attention sub-block (PeriNorm: pre-norm -> attn -> post-norm -> residual)
300
+ normed = self.input_layernorm(hidden_states)
301
+ attn_output, attn_weights, present_key_value = self.self_attn(
302
+ normed,
303
+ attention_mask=attention_mask,
304
+ position_ids=position_ids,
305
+ past_key_value=past_key_value,
306
+ output_attentions=output_attentions,
307
+ use_cache=use_cache,
308
+ cache_position=cache_position,
309
+ value_residual=value_residual,
310
+ **kwargs,
311
+ )
312
+ hidden_states = hidden_states + self.post_attention_layernorm(attn_output)
313
+
314
+ # FFN sub-block (PeriNorm: pre-norm -> ffn -> post-norm -> residual)
315
+ normed = self.pre_feedforward_layernorm(hidden_states)
316
+ ff_output = self.mlp(normed)
317
+ hidden_states = hidden_states + self.post_feedforward_layernorm(ff_output)
318
+
319
+ outputs = (hidden_states,)
320
+ if output_attentions:
321
+ outputs += (attn_weights,)
322
+ if use_cache:
323
+ outputs += (present_key_value,)
324
+ return outputs
325
+
326
+
327
+ class RicursivePreTrainedModel(PreTrainedModel):
328
+ config_class = RicursiveConfig
329
+ base_model_prefix = "model"
330
+ supports_gradient_checkpointing = True
331
+ _no_split_modules = ["RicursiveDecoderLayer"]
332
+ _supports_sdpa = True
333
+ _supports_cache_class = True
334
+
335
+
336
+ class RicursiveModel(RicursivePreTrainedModel):
337
+ def __init__(self, config: RicursiveConfig):
338
+ super().__init__(config)
339
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
340
+ self.layers = nn.ModuleList(
341
+ [RicursiveDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
342
+ )
343
+ self.norm = RicursiveRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
344
+ self.post_init()
345
+
346
+ def forward(
347
+ self,
348
+ input_ids: Optional[torch.LongTensor] = None,
349
+ attention_mask: Optional[torch.Tensor] = None,
350
+ position_ids: Optional[torch.LongTensor] = None,
351
+ past_key_values: Optional[Cache] = None,
352
+ inputs_embeds: Optional[torch.FloatTensor] = None,
353
+ use_cache: Optional[bool] = None,
354
+ output_attentions: Optional[bool] = None,
355
+ output_hidden_states: Optional[bool] = None,
356
+ return_dict: Optional[bool] = None,
357
+ cache_position: Optional[torch.LongTensor] = None,
358
+ **kwargs,
359
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
360
+ output_attentions = (
361
+ output_attentions if output_attentions is not None else self.config.output_attentions
362
+ )
363
+ output_hidden_states = (
364
+ output_hidden_states
365
+ if output_hidden_states is not None
366
+ else self.config.output_hidden_states
367
+ )
368
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
369
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
370
+
371
+ if inputs_embeds is None:
372
+ inputs_embeds = self.embed_tokens(input_ids)
373
+
374
+ # embed_scale: non-folded checkpoints carry the scale (e.g. sqrt(hidden_size)) in the
375
+ # config and apply it here at runtime; folded checkpoints set embed_scale=None and bake
376
+ # the scale into embed_tokens.weight, so this is a no-op. This mirrors the SGLang native
377
+ # port (sglang_ricursive) so served and trained forwards agree. It must run BEFORE the
378
+ # value-residual seed below, whose source is the (scaled) layer-0 embeddings.
379
+ embed_scale = getattr(self.config, "embed_scale", None)
380
+ if embed_scale is not None:
381
+ inputs_embeds = inputs_embeds * embed_scale
382
+
383
+ if use_cache and past_key_values is None:
384
+ past_key_values = DynamicCache()
385
+
386
+ if cache_position is None:
387
+ past_seen_tokens = (
388
+ past_key_values.get_seq_length() if past_key_values is not None else 0
389
+ )
390
+ cache_position = torch.arange(
391
+ past_seen_tokens,
392
+ past_seen_tokens + inputs_embeds.shape[1],
393
+ device=inputs_embeds.device,
394
+ )
395
+
396
+ if position_ids is None:
397
+ position_ids = cache_position.unsqueeze(0)
398
+
399
+ # Build causal mask
400
+ causal_mask = self._update_causal_mask(
401
+ attention_mask, inputs_embeds, cache_position, past_key_values
402
+ )
403
+
404
+ hidden_states = inputs_embeds
405
+ value_residual = hidden_states if self.config.use_valres else None
406
+ all_hidden_states = () if output_hidden_states else None
407
+ all_self_attns = () if output_attentions else None
408
+
409
+ for layer in self.layers:
410
+ if output_hidden_states:
411
+ all_hidden_states += (hidden_states,)
412
+
413
+ layer_outputs = layer(
414
+ hidden_states,
415
+ attention_mask=causal_mask,
416
+ position_ids=position_ids,
417
+ past_key_value=past_key_values,
418
+ output_attentions=output_attentions,
419
+ use_cache=use_cache,
420
+ cache_position=cache_position,
421
+ value_residual=value_residual,
422
+ **kwargs,
423
+ )
424
+ hidden_states = layer_outputs[0]
425
+
426
+ if output_attentions:
427
+ all_self_attns += (layer_outputs[1],)
428
+
429
+ hidden_states = self.norm(hidden_states)
430
+
431
+ if output_hidden_states:
432
+ all_hidden_states += (hidden_states,)
433
+
434
+ next_cache = past_key_values if use_cache else None
435
+
436
+ if not return_dict:
437
+ return tuple(
438
+ v
439
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
440
+ if v is not None
441
+ )
442
+ return BaseModelOutputWithPast(
443
+ last_hidden_state=hidden_states,
444
+ past_key_values=next_cache,
445
+ hidden_states=all_hidden_states,
446
+ attentions=all_self_attns,
447
+ )
448
+
449
+ def _update_causal_mask(
450
+ self,
451
+ attention_mask: Optional[torch.Tensor],
452
+ input_tensor: torch.Tensor,
453
+ cache_position: torch.Tensor,
454
+ past_key_values: Optional[Cache],
455
+ ) -> Optional[torch.Tensor]:
456
+ # When there's no explicit attention_mask (no padding) and we're doing
457
+ # standard prefill or cached decoding, return None and let SDPA use
458
+ # its efficient is_causal path. This also avoids numerical issues
459
+ # from float min mask values with large activations.
460
+ if attention_mask is None:
461
+ return None
462
+ if torch.all(attention_mask == 1):
463
+ return None
464
+
465
+ # Only build an explicit mask when we have a padding mask
466
+ dtype, device = input_tensor.dtype, input_tensor.device
467
+ sequence_length = input_tensor.shape[1]
468
+
469
+ if past_key_values is not None:
470
+ target_length = past_key_values.get_max_cache_shape()
471
+ if target_length is None or target_length < 0:
472
+ target_length = (
473
+ cache_position[-1].item() + 1 if cache_position is not None else sequence_length
474
+ )
475
+ else:
476
+ target_length = sequence_length
477
+
478
+ causal_mask = torch.full(
479
+ (sequence_length, target_length),
480
+ fill_value=torch.finfo(dtype).min,
481
+ dtype=dtype,
482
+ device=device,
483
+ )
484
+ if sequence_length != 1:
485
+ causal_mask = torch.triu(causal_mask, diagonal=target_length - sequence_length + 1)
486
+
487
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
488
+
489
+ if attention_mask.dim() == 2:
490
+ mask_length = attention_mask.shape[-1]
491
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
492
+ causal_mask.dtype
493
+ ).masked_fill(attention_mask[:, None, None, :] == 0, torch.finfo(dtype).min)
494
+ causal_mask = (
495
+ torch.cat([padding_mask, causal_mask[:, :, :, mask_length:]], dim=-1)
496
+ if mask_length < target_length
497
+ else padding_mask
498
+ )
499
+
500
+ return causal_mask
501
+
502
+
503
+ class RicursiveForCausalLM(RicursivePreTrainedModel):
504
+ _tied_weights_keys = []
505
+
506
+ def __init__(self, config: RicursiveConfig):
507
+ super().__init__(config)
508
+ self.model = RicursiveModel(config)
509
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
510
+ self.post_init()
511
+
512
+ def get_input_embeddings(self):
513
+ return self.model.embed_tokens
514
+
515
+ def set_input_embeddings(self, value):
516
+ self.model.embed_tokens = value
517
+
518
+ def get_output_embeddings(self):
519
+ return self.lm_head
520
+
521
+ def set_output_embeddings(self, new_embeddings):
522
+ self.lm_head = new_embeddings
523
+
524
+ def forward(
525
+ self,
526
+ input_ids: Optional[torch.LongTensor] = None,
527
+ attention_mask: Optional[torch.Tensor] = None,
528
+ position_ids: Optional[torch.LongTensor] = None,
529
+ past_key_values: Optional[Cache] = None,
530
+ inputs_embeds: Optional[torch.FloatTensor] = None,
531
+ labels: Optional[torch.LongTensor] = None,
532
+ use_cache: Optional[bool] = None,
533
+ output_attentions: Optional[bool] = None,
534
+ output_hidden_states: Optional[bool] = None,
535
+ return_dict: Optional[bool] = None,
536
+ cache_position: Optional[torch.LongTensor] = None,
537
+ **kwargs,
538
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
539
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
540
+
541
+ outputs = self.model(
542
+ input_ids=input_ids,
543
+ attention_mask=attention_mask,
544
+ position_ids=position_ids,
545
+ past_key_values=past_key_values,
546
+ inputs_embeds=inputs_embeds,
547
+ use_cache=use_cache,
548
+ output_attentions=output_attentions,
549
+ output_hidden_states=output_hidden_states,
550
+ return_dict=return_dict,
551
+ cache_position=cache_position,
552
+ **kwargs,
553
+ )
554
+ hidden_states = outputs[0]
555
+ logits = self.lm_head(hidden_states)
556
+
557
+ loss = None
558
+ if labels is not None:
559
+ shift_logits = logits[..., :-1, :].contiguous()
560
+ shift_labels = labels[..., 1:].contiguous()
561
+ loss = F.cross_entropy(
562
+ shift_logits.view(-1, shift_logits.size(-1)),
563
+ shift_labels.view(-1),
564
+ )
565
+
566
+ if not return_dict:
567
+ output = (logits,) + outputs[1:]
568
+ return (loss,) + output if loss is not None else output
569
+
570
+ return CausalLMOutputWithPast(
571
+ loss=loss,
572
+ logits=logits,
573
+ past_key_values=outputs.past_key_values,
574
+ hidden_states=outputs.hidden_states,
575
+ attentions=outputs.attentions,
576
+ )
577
+
578
+ def prepare_inputs_for_generation(
579
+ self,
580
+ input_ids: torch.LongTensor,
581
+ past_key_values: Optional[Cache] = None,
582
+ attention_mask: Optional[torch.Tensor] = None,
583
+ inputs_embeds: Optional[torch.FloatTensor] = None,
584
+ cache_position: Optional[torch.LongTensor] = None,
585
+ use_cache: Optional[bool] = None,
586
+ **kwargs,
587
+ ):
588
+ if past_key_values is not None:
589
+ if input_ids.shape[1] != 1:
590
+ input_ids = input_ids[:, cache_position]
591
+
592
+ if inputs_embeds is not None and cache_position[0] == 0:
593
+ model_inputs = {"inputs_embeds": inputs_embeds}
594
+ else:
595
+ model_inputs = {"input_ids": input_ids}
596
+
597
+ model_inputs.update(
598
+ {
599
+ "position_ids": cache_position.unsqueeze(0) if cache_position is not None else None,
600
+ "past_key_values": past_key_values,
601
+ "use_cache": use_cache,
602
+ "attention_mask": attention_mask,
603
+ "cache_position": cache_position,
604
+ }
605
+ )
606
+ return model_inputs
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|pad|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<|endoftext|>",
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_config.json ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "100256": {
5
+ "content": "<|extra_id_0|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": false
11
+ },
12
+ "100257": {
13
+ "content": "<|endoftext|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "100258": {
21
+ "content": "<|fim_prefix|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "100259": {
29
+ "content": "<|fim_middle|>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "100260": {
37
+ "content": "<|fim_suffix|>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "100261": {
45
+ "content": "|||PHONE_NUMBER|||",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": false
51
+ },
52
+ "100262": {
53
+ "content": "|||EMAIL_ADDRESS|||",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": false
59
+ },
60
+ "100263": {
61
+ "content": "|||IP_ADDRESS|||",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": false
67
+ },
68
+ "100264": {
69
+ "content": "<|im_start|>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "100265": {
77
+ "content": "<|im_end|>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "100266": {
85
+ "content": "<|extra_id_1|>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": false
91
+ },
92
+ "100267": {
93
+ "content": "<|extra_id_2|>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": false
99
+ },
100
+ "100268": {
101
+ "content": "<|extra_id_3|>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": false
107
+ },
108
+ "100269": {
109
+ "content": "<|extra_id_4|>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": false
115
+ },
116
+ "100270": {
117
+ "content": "<|extra_id_5|>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": false
123
+ },
124
+ "100271": {
125
+ "content": "<|extra_id_6|>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": false
131
+ },
132
+ "100272": {
133
+ "content": "<|extra_id_7|>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": false
139
+ },
140
+ "100273": {
141
+ "content": "<|extra_id_8|>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": false
147
+ },
148
+ "100274": {
149
+ "content": "<|extra_id_9|>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": false
155
+ },
156
+ "100275": {
157
+ "content": "<|extra_id_10|>",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": false
163
+ },
164
+ "100276": {
165
+ "content": "<|endofprompt|>",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": true
171
+ },
172
+ "100277": {
173
+ "content": "<|pad|>",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": true
179
+ }
180
+ },
181
+ "bos_token": "<|endoftext|>",
182
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}",
183
+ "clean_up_tokenization_spaces": false,
184
+ "eos_token": "<|endoftext|>",
185
+ "model_max_length": 8192,
186
+ "pad_token": "<|pad|>",
187
+ "tokenizer_class": "GPT2Tokenizer",
188
+ "unk_token": "<|endoftext|>"
189
+ }