PursuitOfDataScience commited on
Commit
63cbe49
·
verified ·
1 Parent(s): 9de57f0

Argonne 3.5-base: 2.88B, 88.84B tokens, trained 13,568-token context

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ plots/loss_plot.png filter=lfs diff=lfs merge=lfs -text
37
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ library_name: transformers
6
+ tags:
7
+ - text-generation
8
+ - causal-lm
9
+ - transformer
10
+ - argonne
11
+ - pretrained
12
+ - base-model
13
+ - long-context
14
+ pipeline_tag: text-generation
15
+ ---
16
+
17
+ # Argonne 3.5-base
18
+
19
+ Argonne 3.5-base is a 2.88B-parameter decoder-only transformer trained from scratch. It is the
20
+ base (foundation) checkpoint of the Argonne 3.5 line and the successor to
21
+ [argonne-3.0-base](https://huggingface.co/PursuitOfDataScience/argonne-3.0-base).
22
+
23
+ Two things separate it from 3.0-base:
24
+
25
+ 1. **A three-stage curriculum** — general pretraining, then a reasoning/code/math anneal, then a
26
+ context-extension stage — for **88.84B total tokens** versus 3.0-base's 76.05B.
27
+ 2. **A 13,568-token context**, which is *trained*, not extrapolated. 3.0-base is a 1,024-token
28
+ model; so was this one until the third stage. That stage was validated against a
29
+ pre-extension control (numbers below), because on this architecture RoPE θ=1e6 does **not**
30
+ extrapolate on its own.
31
+
32
+ The architecture is unchanged from 3.0 — grouped-query attention with QK-norm, V-norm, sandwich
33
+ norms, interleaved local/global attention, and a final logit softcap. What changed is the
34
+ training recipe (FP8, a higher peak LR with a proper cooldown, tighter gradient clipping) and
35
+ the data curriculum.
36
+
37
+ This is a **base model**: no instruction tuning, no alignment, no safety filtering.
38
+
39
+ ## Model architecture
40
+
41
+ | Component | Specification |
42
+ |-----------|---------------|
43
+ | **Parameters** | 2,882,162,688 (~2.88B) |
44
+ | **Layers** | 24 transformer blocks |
45
+ | **Hidden size** | 3,072 |
46
+ | **Attention heads** | 12 query / 4 key-value (GQA) |
47
+ | **Head dimension** | 256 |
48
+ | **Feed-forward** | SwiGLU MLP, 8,192 intermediate dim |
49
+ | **Attention pattern** | Interleaved local/global causal attention |
50
+ | **Local attention window** | 256 tokens (every other layer) |
51
+ | **Normalization** | RMSNorm with QK / V / sandwich norms |
52
+ | **Position encoding** | RoPE (θ = 1,000,000) |
53
+ | **Logit stabilization** | Final logit softcap = 15.0 |
54
+ | **Context length** | **13,568 tokens** (trained, not extrapolated) |
55
+ | **Vocabulary size** | 151,669 |
56
+ | **Tied embeddings** | Yes (input ↔ output) |
57
+
58
+ ## Training
59
+
60
+ Three stages, all causal language modeling, all on 3× NVIDIA H100/H200 GPUs with DDP.
61
+
62
+ | | Stage 1 — pretrain | Stage 2 — reasoning anneal | Stage 3 — context extension |
63
+ |---|---|---|---|
64
+ | **Script** | `pretrain.py` | `continue_pretrain.py` | `continue_pretrain.py` |
65
+ | **Steps** | 50 → 244,000 | 244,010 → 308,730 | 308,740 → 321,062 |
66
+ | **Tokens** | 65.30B | 17.50B | 6.02B |
67
+ | **Cumulative** | 65.31B | 82.81B | **88.84B** |
68
+ | **Sequence length** | 1,024 | 1,024 | **13,568** |
69
+ | **Batch / GPU** | 38 → 44 | 88 | 3 |
70
+ | **Grad accumulation** | 2 | 1 | 4 |
71
+ | **Effective batch** | 233,472 → 270,336 tok/step | 270,336 tok/step | 488,448 tok/step |
72
+ | **Peak LR** | 6.0e-4 | 2.0e-4 | 1.0e-4 |
73
+ | **End LR** | 6.0e-5 | 2.0e-5 | 1.0e-5 |
74
+ | **Warmup** | 8,000 steps | 0 | 0 |
75
+ | **Schedule** | WSD, cooldown_frac 0.15 | cooldown to 0.1× | cooldown to 0.1× |
76
+
77
+ Shared across all three stages:
78
+
79
+ | Item | Value |
80
+ |------|-------|
81
+ | **Optimizer** | AdamW (β₁=0.9, β₂=0.95, weight decay 0.1) |
82
+ | **Gradient clipping** | 0.4 |
83
+ | **Precision** | FP8 (torchao tensorwise, including `lm_head`) under bf16 autocast; fp32 optimizer states |
84
+ | **Vocab padding** | 151,669 → 151,680 during training for the FP8 `lm_head` (trimmed back on export) |
85
+ | **`torch.compile`** | Enabled |
86
+ | **Gradient checkpointing** | Enabled |
87
+ | **Data parallel** | 3 GPUs (DDP) |
88
+ | **Total optimizer steps** | 321,062 |
89
+ | **Final train loss** | 0.8923 (stage-3 slice average; not comparable across stages — the mixtures differ) |
90
+ | **Checkpoint dtype on Hub** | bfloat16 |
91
+ | **Weight format on Hub** | 5 sharded safetensors + index |
92
+
93
+ ### Why the recipe changed from 3.0
94
+
95
+ 3.0-base ran WSD with `cooldown = 0` — the stable phase only, no decay. 3.5 uses a real cooldown
96
+ in every stage (visible in the LR panel of the figure below), a higher peak LR (6e-4 vs 3e-4), a
97
+ longer warmup (8,000 vs 1,000 steps), and tighter gradient clipping (0.4 vs 1.0). The tighter clip
98
+ and QK-norm are what make the higher LR stable.
99
+
100
+ ## Training data
101
+
102
+ | Stage | Corpus | Tokens |
103
+ |---|---|---|
104
+ | **1 — pretrain** | [FineWeb](https://huggingface.co/datasets/HuggingFaceFW/fineweb) + [FineMath](https://huggingface.co/datasets/HuggingFaceTB/finemath), 85/15 | 65.30B |
105
+ | **2 — reasoning anneal** | code / math / reasoning / tool mixture with a general-web replay tier (below) | 17.50B |
106
+ | **3 — context extension** | a **disjoint** slice of the same stage-2 composite, read at 13,568 tokens | 6.02B |
107
+
108
+ The stage-2/3 composite is built by
109
+ [`build_reasoning_corpus.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/build_reasoning_corpus.py)
110
+ from:
111
+
112
+ | Tier | Source |
113
+ |---|---|
114
+ | code | [nick007x/github-code-2025](https://huggingface.co/datasets/nick007x/github-code-2025) (≥2 stars) · [nvidia/Nemotron-Competitive-Programming-v1](https://huggingface.co/datasets/nvidia/Nemotron-Competitive-Programming-v1) |
115
+ | math | [nvidia/OpenMathReasoning](https://huggingface.co/datasets/nvidia/OpenMathReasoning) |
116
+ | reasoning | [a-m-team/AM-DeepSeek-R1-Distilled-1.4M](https://huggingface.co/datasets/a-m-team/AM-DeepSeek-R1-Distilled-1.4M) · [open-r1/Mixture-of-Thoughts](https://huggingface.co/datasets/open-r1/Mixture-of-Thoughts) · [PursuitOfDataScience/0.5M-thinking](https://huggingface.co/datasets/PursuitOfDataScience/0.5M-thinking) |
117
+ | tool | [nvidia/Nemotron-SFT-Agentic-v2](https://huggingface.co/datasets/nvidia/Nemotron-SFT-Agentic-v2) |
118
+ | general (replay) | [HuggingFaceFW/fineweb-edu](https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu) |
119
+
120
+ Reasoning traces keep their `<think>`/tool tags, so the base has seen that formatting before any
121
+ fine-tuning. The corpus is decontaminated against common evaluation sets, and stages 2 and 3 use
122
+ **disjoint** slices of it (`--holdout_frac` / `--part`) so stage 3 is not a second epoch over
123
+ stage 2's tokens.
124
+
125
+ The general-web replay tier exists because it is needed: an earlier build capped that tier at 2.2B
126
+ tokens (9% of the anneal mix), and 18% of the way in, held-out FineWeb-Edu cross-entropy had risen
127
+ **+0.246 nats** — the base was measurably regressing on general text while improving on the target
128
+ tiers. The tier was raised to a 20.6B-token pool.
129
+
130
+ **Tokenizer:** [Qwen/Qwen3-0.6B-Base](https://huggingface.co/Qwen/Qwen3-0.6B-Base) (151,669-token
131
+ vocab), via the `Qwen2Tokenizer` compatibility class. Bundled with the checkpoint.
132
+
133
+ ## Training loss
134
+
135
+ ![Training loss curve](plots/loss_plot.png)
136
+
137
+ Loss, perplexity, and learning rate against cumulative tokens across all three stages, with the
138
+ stage boundaries marked. The LR panel shows the three cooldowns. Note that the loss step down at
139
+ each stage boundary is a **change of data mixture**, not a capability jump — the anneal and
140
+ context-extension corpora are intrinsically lower-entropy than FineWeb, so cross-stage loss values
141
+ are not comparable.
142
+
143
+ ## Evaluation
144
+
145
+ Two measurements were run on the final checkpoint. Both are reported with their limitations,
146
+ because neither is a general capability benchmark.
147
+
148
+ ### Context extension — position-bucketed NLL on held-out arXiv
149
+
150
+ The question is whether stage 3 actually taught the model to *use* long positions, or just trained
151
+ it more. The test is a paired A/B on identical held-out windows (40 documents, 24,576 tokens each,
152
+ [proof-pile-2](https://huggingface.co/datasets/EleutherAI/proof-pile-2) arXiv — a domain neither
153
+ stage trained on), comparing the final weights against the stage-2 checkpoint they were seeded
154
+ from. Lower is better.
155
+
156
+ | Token position | Stage-2 checkpoint (ctx 1,024) | **Argonne 3.5-base** (ctx 13,568) |
157
+ |---|---|---|
158
+ | 0 – 1,024 | 2.194 | **2.161** |
159
+ | 1,024 – 2,048 | 5.536 | **1.860** |
160
+ | 2,048 – 4,096 | 5.969 | **1.576** |
161
+ | 4,096 – 8,192 | 5.895 | **1.320** |
162
+ | 8,192 – 13,568 | 5.961 | **1.207** |
163
+ | 13,568 – 20,480 | 5.965 | **1.122** |
164
+ | 20,480 – 24,576 | 5.938 | **1.096** |
165
+
166
+ Three things this shows:
167
+
168
+ - **RoPE θ=1e6 does not extrapolate unaided on this architecture.** The stage-2 model is coherent
169
+ inside its 1,024-token training window (2.19) and effectively blind past it (~5.9, flat). If you
170
+ are tempted to assume a large RoPE base buys you free context, this is the counterexample.
171
+ - **The extension is real.** NLL falls *monotonically with position* rather than shifting by a
172
+ constant, which is what generic extra training would have produced.
173
+ - **It generalizes past its own training length.** The 13,568–24,576 buckets — beyond anything
174
+ stage 3 trained on — keep improving, and there is **no short-context tax**: the 0–1,024 control
175
+ bucket is *better* than the stage-2 model (2.161 vs 2.194).
176
+
177
+ Reproduce with
178
+ [`reasoning/exp_longctx_learning.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/reasoning/exp_longctx_learning.py).
179
+
180
+ ### Two-axis base gate
181
+
182
+ A 35-item greedy few-shot probe (20 arithmetic/word-problem, 15 world-knowledge) used as a
183
+ **go/no-go gate** for whether a base is worth running a reasoning recipe on.
184
+
185
+ | Checkpoint | Math /20 | General /15 |
186
+ |---|---|---|
187
+ | Stage-2 (pre-extension, step 308,733) | 18 | 15 |
188
+ | step 320,885 | 18 | 15 |
189
+ | step 321,054 | 17 | 15 |
190
+ | **step 321,062 (this model)** | **18** | **15** |
191
+
192
+ Both axes clear the ≥14/20 ∧ ≥14/15 gate, and the context-extension stage cost nothing on either.
193
+
194
+ **Read this as a gate, not as a capability number.** The probe is small (n=20/15), it saturates,
195
+ and it has a measured ±2-item noise floor — which is why three checkpoints are shown rather than
196
+ one. It says the base is worth building on. It does not say how good it is. Reproduce with
197
+ [`reasoning/probe_pretrain_ckpt.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/reasoning/probe_pretrain_ckpt.py).
198
+
199
+ ### What has not been measured
200
+
201
+ No standard held-out benchmark suite (MMLU, ARC, HellaSwag, GSM8K, …) has been run on this
202
+ checkpoint yet. Those numbers are not withheld — they do not exist, and this card will be updated
203
+ when they do. Do not infer benchmark standing from the two measurements above.
204
+
205
+ One caution specific to this line: **GSM8K is contaminated** for Argonne reasoning derivatives
206
+ downstream of this base, and should not be used to grade them.
207
+
208
+ ## Source code
209
+
210
+ Built from the GitHub main branch: https://github.com/PursuitOfDataScience/ArgonneAI/tree/main
211
+
212
+ | File | Role |
213
+ |---|---|
214
+ | [`model.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/model.py) | `ArgonneModel` / `ArgonneConfig` architecture + KV cache (bundled here as `model.py`) |
215
+ | [`pretrain.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/pretrain.py) | stage 1 — DDP pretraining loop |
216
+ | [`continue_pretrain.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/continue_pretrain.py) | stages 2 and 3 — anneal and context extension |
217
+ | [`build_reasoning_corpus.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/build_reasoning_corpus.py) | builds the stage-2/3 corpus (tiering, decontamination, disjoint slicing) |
218
+ | [`reasoning/probe_pretrain_ckpt.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/reasoning/probe_pretrain_ckpt.py) | the two-axis base gate probe |
219
+ | [`reasoning/exp_longctx_learning.py`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/reasoning/exp_longctx_learning.py) | the position-bucketed long-context NLL probe |
220
+ | [`reasoning/thinking_training.md`](https://github.com/PursuitOfDataScience/ArgonneAI/blob/main/reasoning/thinking_training.md) | the full lab notebook for the reasoning line |
221
+
222
+ ## Inference
223
+
224
+ ```python
225
+ from transformers import AutoModelForCausalLM, AutoTokenizer
226
+ import torch
227
+
228
+ model_id = "PursuitOfDataScience/argonne-3.5-base"
229
+
230
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
231
+ model = AutoModelForCausalLM.from_pretrained(
232
+ model_id,
233
+ trust_remote_code=True,
234
+ dtype=torch.bfloat16,
235
+ )
236
+
237
+ prompt = "Write a short paragraph about scientific computing at Argonne National Laboratory."
238
+ inputs = tokenizer(prompt, return_tensors="pt")
239
+ input_ids = inputs["input_ids"].to(model.device)
240
+
241
+ output_ids = model.generate(
242
+ input_ids,
243
+ max_length=input_ids.shape[1] + 128,
244
+ temperature=0.8,
245
+ top_p=0.95,
246
+ top_k=50,
247
+ do_sample=True,
248
+ )
249
+ print(tokenizer.decode(output_ids[0], skip_special_tokens=True))
250
+ ```
251
+
252
+ ## Usage notes
253
+
254
+ - Load with `trust_remote_code=True` so the custom `ArgonneModel` / `ArgonneConfig` classes
255
+ (`model.py`) are registered. Unlike the 3.0-base card, this repo ships an `auto_map` in
256
+ `config.json`, so `from_pretrained` resolves the classes without any manual setup.
257
+ - The custom `generate` method on `ArgonneModel` takes `max_length` (total sequence length), not
258
+ `max_new_tokens`.
259
+ - Weights are 5 bf16 safetensor shards with a `model.safetensors.index.json` weight map.
260
+ - `lm_head.weight` is reported missing on load. This is expected and benign — embeddings are tied
261
+ (`tie_word_embeddings: true`), so `lm_head` takes its weights from `embed_tokens`.
262
+ - The full 13,568-token context is usable. For throughput at that length, prefer a real serving
263
+ engine (vLLM/SGLang) over `.generate()`.
264
+ - Switch to greedy decoding (`do_sample=False`) for deterministic output.
265
+
266
+ ## Limitations
267
+
268
+ - **Base model.** No instruction following, dialogue ability, or safety alignment. Outputs can be
269
+ factually wrong, biased, or unsafe. It continues text; it does not answer questions.
270
+ - **Unbenchmarked.** See "What has not been measured" above.
271
+ - **Scale.** 2.88B parameters on 88.84B tokens is far below frontier compute; expect corresponding
272
+ quality.
273
+ - The stage-2/3 mixture is reasoning/code/math-heavy. That is deliberate — this base exists to be
274
+ fine-tuned into a reasoning model — but it means the token distribution is not representative of
275
+ general web text, and general-domain behavior reflects the replay tier rather than a purely
276
+ general-purpose pretrain.
277
+ - Trained with FP8 matmuls. Weights are published in bf16 and load normally, but exact
278
+ reproduction of the training run requires the same torchao FP8 path.
279
+
280
+ ## Citation
281
+
282
+ ```bibtex
283
+ @misc{argonne35base,
284
+ author = {PursuitOfDataScience},
285
+ title = {Argonne 3.5-base},
286
+ year = {2026},
287
+ publisher = {Hugging Face},
288
+ url = {https://huggingface.co/PursuitOfDataScience/argonne-3.5-base}
289
+ }
290
+ ```
chat_template.jinja ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
27
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
28
+ {%- elif message.role == "assistant" %}
29
+ {%- set content = message.content %}
30
+ {%- set reasoning_content = '' %}
31
+ {%- if message.reasoning_content is defined and message.reasoning_content is not none %}
32
+ {%- set reasoning_content = message.reasoning_content %}
33
+ {%- else %}
34
+ {%- if '</think>' in message.content %}
35
+ {%- set content = message.content.split('</think>')[-1].lstrip('\n') %}
36
+ {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
37
+ {%- endif %}
38
+ {%- endif %}
39
+ {%- if loop.index0 > ns.last_query_index %}
40
+ {%- if loop.last or (not loop.last and reasoning_content) %}
41
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
42
+ {%- else %}
43
+ {{- '<|im_start|>' + message.role + '\n' + content }}
44
+ {%- endif %}
45
+ {%- else %}
46
+ {{- '<|im_start|>' + message.role + '\n' + content }}
47
+ {%- endif %}
48
+ {%- if message.tool_calls %}
49
+ {%- for tool_call in message.tool_calls %}
50
+ {%- if (loop.first and content) or (not loop.first) %}
51
+ {{- '\n' }}
52
+ {%- endif %}
53
+ {%- if tool_call.function %}
54
+ {%- set tool_call = tool_call.function %}
55
+ {%- endif %}
56
+ {{- '<tool_call>\n{"name": "' }}
57
+ {{- tool_call.name }}
58
+ {{- '", "arguments": ' }}
59
+ {%- if tool_call.arguments is string %}
60
+ {{- tool_call.arguments }}
61
+ {%- else %}
62
+ {{- tool_call.arguments | tojson }}
63
+ {%- endif %}
64
+ {{- '}\n</tool_call>' }}
65
+ {%- endfor %}
66
+ {%- endif %}
67
+ {{- '<|im_end|>\n' }}
68
+ {%- elif message.role == "tool" %}
69
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
70
+ {{- '<|im_start|>user' }}
71
+ {%- endif %}
72
+ {{- '\n<tool_response>\n' }}
73
+ {{- message.content }}
74
+ {{- '\n</tool_response>' }}
75
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
76
+ {{- '<|im_end|>\n' }}
77
+ {%- endif %}
78
+ {%- endif %}
79
+ {%- endfor %}
80
+ {%- if add_generation_prompt %}
81
+ {{- '<|im_start|>assistant\n' }}
82
+ {%- if enable_thinking is defined and enable_thinking is false %}
83
+ {{- '<think>\n\n</think>\n\n' }}
84
+ {%- endif %}
85
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_keep_in_fp32_modules": [],
3
+ "architectures": [
4
+ "ArgonneModel"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "block_size": 13568,
9
+ "bos_token_id": null,
10
+ "dtype": "bfloat16",
11
+ "eos_token_id": null,
12
+ "hidden_dropout": 0.0,
13
+ "hidden_size": 3072,
14
+ "interleaved_local_attention": true,
15
+ "intermediate_size": 8192,
16
+ "local_attention_window": 256,
17
+ "logit_softcap": 15.0,
18
+ "loss_chunk_size": 0,
19
+ "max_position_embeddings": 13568,
20
+ "mlp_bias": false,
21
+ "model_type": "argonne2",
22
+ "mtp_horizon": 1,
23
+ "mtp_loss_weight": 0.0,
24
+ "n_embd": 3072,
25
+ "n_head": 12,
26
+ "n_layer": 24,
27
+ "num_attention_heads": 12,
28
+ "num_hidden_layers": 24,
29
+ "num_key_value_heads": 4,
30
+ "pad_token_id": null,
31
+ "qk_norm": true,
32
+ "rms_norm_eps": 1e-06,
33
+ "rope_theta": 1000000.0,
34
+ "sandwich_norm": true,
35
+ "sliding_window": null,
36
+ "tie_word_embeddings": true,
37
+ "transformers_version": "5.6.2",
38
+ "use_flash_attention": true,
39
+ "use_gradient_checkpointing": false,
40
+ "v_norm": true,
41
+ "vocab_size": 151669,
42
+ "z_loss_weight": 0.0,
43
+ "torch_dtype": "bfloat16",
44
+ "auto_map": {
45
+ "AutoConfig": "model.ArgonneConfig",
46
+ "AutoModelForCausalLM": "model.ArgonneModel"
47
+ }
48
+ }
model-00001-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:914f305cef1638df8a09944bbed0e0080453480a2cb8ff1e438151d88e8e020f
3
+ size 1157780640
model-00002-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:addac17e153b51b445a889c2faa74fe817514ca16f97a78657983beecd9a4e59
3
+ size 1157793168
model-00003-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9df3815d7550d0b26ddf224a58e12b95557c60adbe4769db0e247357b33dbdc3
3
+ size 1157793160
model-00004-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b83bf391d8e10246b23a7563fdb0f8985911b1af9f7c626e4779865ffe255cc1
3
+ size 1182945720
model-00005-of-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40c878e5842218da37e289380bed632e2c8139545b89393e6a316ea823de25f2
3
+ size 1108047568
model.py ADDED
@@ -0,0 +1,926 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import importlib.util
3
+ import os
4
+ from typing import Optional, Tuple
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+ from transformers import (
10
+ AutoConfig,
11
+ AutoModel,
12
+ AutoModelForCausalLM,
13
+ PreTrainedModel,
14
+ PretrainedConfig,
15
+ )
16
+ from transformers.modeling_outputs import CausalLMOutput, CausalLMOutputWithPast
17
+
18
+
19
+ flash_attn_func = None
20
+ _flash_attn_available = False
21
+ if importlib.util.find_spec("flash_attn") is not None:
22
+ try:
23
+ from flash_attn.flash_attn_interface import flash_attn_func
24
+ _flash_attn_available = True
25
+ except ImportError:
26
+ _flash_attn_available = False
27
+
28
+ # One-time startup log of which attention kernel is in effect, because the
29
+ # sliding-window local attention is only implemented on the flash-attn path
30
+ # and silently degrades to full attention on the SDPA/math fallbacks.
31
+ _attention_path_logged = False
32
+
33
+
34
+ class ArgonneConfig(PretrainedConfig):
35
+ """Configuration for the Argonne v3.0 family of models."""
36
+
37
+ model_type = "argonne2"
38
+
39
+ def __init__(
40
+ self,
41
+ vocab_size: int = 151936,
42
+ hidden_size: int = 3072,
43
+ num_hidden_layers: int = 24,
44
+ num_attention_heads: int = 12,
45
+ num_key_value_heads: Optional[int] = 4,
46
+ intermediate_size: Optional[int] = 8192,
47
+ max_position_embeddings: int = 1024,
48
+ attention_dropout: float = 0.0,
49
+ hidden_dropout: float = 0.0,
50
+ rms_norm_eps: float = 1e-6,
51
+ rope_theta: float = 1000000.0,
52
+ sliding_window: Optional[int] = None,
53
+ use_flash_attention: bool = True,
54
+ use_gradient_checkpointing: bool = False,
55
+ qk_norm: bool = True,
56
+ v_norm: bool = True,
57
+ sandwich_norm: bool = True,
58
+ z_loss_weight: float = 0.0,
59
+ mtp_horizon: int = 1,
60
+ mtp_loss_weight: float = 0.0,
61
+ interleaved_local_attention: bool = True,
62
+ local_attention_window: Optional[int] = 256,
63
+ logit_softcap: float = 15.0,
64
+ loss_chunk_size: int = 0,
65
+ tie_word_embeddings: bool = True,
66
+ attention_bias: bool = False,
67
+ mlp_bias: bool = False,
68
+ pad_token_id: Optional[int] = None,
69
+ bos_token_id: Optional[int] = None,
70
+ eos_token_id: Optional[int] = None,
71
+ **kwargs,
72
+ ) -> None:
73
+ pad_token_id = pad_token_id if pad_token_id is not None else kwargs.pop("pad_token_id", None)
74
+ bos_token_id = bos_token_id if bos_token_id is not None else kwargs.pop("bos_token_id", None)
75
+ eos_token_id = eos_token_id if eos_token_id is not None else kwargs.pop("eos_token_id", None)
76
+
77
+ super().__init__(
78
+ pad_token_id=pad_token_id,
79
+ bos_token_id=bos_token_id,
80
+ eos_token_id=eos_token_id,
81
+ **kwargs,
82
+ )
83
+ # Backwards compatibility with Argonne 1.x naming.
84
+ if "n_layer" in kwargs:
85
+ num_hidden_layers = kwargs["n_layer"]
86
+ if "n_head" in kwargs:
87
+ num_attention_heads = kwargs["n_head"]
88
+ if "n_embd" in kwargs:
89
+ hidden_size = kwargs["n_embd"]
90
+ if "block_size" in kwargs:
91
+ max_position_embeddings = kwargs["block_size"]
92
+
93
+ self.vocab_size = vocab_size
94
+ self.hidden_size = hidden_size
95
+ self.num_hidden_layers = num_hidden_layers
96
+ self.num_attention_heads = num_attention_heads
97
+ self.num_key_value_heads = (
98
+ num_key_value_heads if num_key_value_heads is not None else num_attention_heads // 2
99
+ )
100
+ if self.num_key_value_heads < 1:
101
+ self.num_key_value_heads = 1
102
+ if num_attention_heads % self.num_key_value_heads != 0:
103
+ raise ValueError("num_attention_heads must be divisible by num_key_value_heads")
104
+
105
+ if intermediate_size is None:
106
+ width = int(8 * hidden_size / 3)
107
+ self.intermediate_size = ((width + 255) // 256) * 256
108
+ else:
109
+ self.intermediate_size = intermediate_size
110
+
111
+ self.max_position_embeddings = max_position_embeddings
112
+ self.attention_dropout = attention_dropout
113
+ self.hidden_dropout = hidden_dropout
114
+ self.rms_norm_eps = rms_norm_eps
115
+ self.rope_theta = rope_theta
116
+ self.sliding_window = sliding_window
117
+ self.use_flash_attention = use_flash_attention
118
+ self.use_gradient_checkpointing = use_gradient_checkpointing
119
+ self.qk_norm = qk_norm
120
+ self.v_norm = v_norm
121
+ self.sandwich_norm = sandwich_norm
122
+ self.z_loss_weight = z_loss_weight
123
+ self.mtp_horizon = max(1, int(mtp_horizon))
124
+ self.mtp_loss_weight = float(mtp_loss_weight)
125
+ self.interleaved_local_attention = bool(interleaved_local_attention)
126
+ self.local_attention_window = (
127
+ int(local_attention_window) if local_attention_window is not None and int(local_attention_window) > 0 else None
128
+ )
129
+ self.logit_softcap = float(logit_softcap)
130
+ # >0 enables chunked cross-entropy (frees the full (batch*seq, vocab) fp32 logit transient
131
+ # that caps batch at long context). 0 = off (default; unchanged full-logit path).
132
+ self.loss_chunk_size = int(loss_chunk_size)
133
+ self.tie_word_embeddings = tie_word_embeddings
134
+ self.attention_bias = attention_bias
135
+ self.mlp_bias = mlp_bias
136
+
137
+ if self.pad_token_id is None and self.eos_token_id is not None:
138
+ self.pad_token_id = self.eos_token_id
139
+
140
+ # Backwards compatibility aliases
141
+ self.n_embd = self.hidden_size
142
+ self.n_layer = self.num_hidden_layers
143
+ self.n_head = self.num_attention_heads
144
+ self.block_size = self.max_position_embeddings
145
+
146
+
147
+ class RMSNorm(nn.Module):
148
+ def __init__(self, hidden_size: int, eps: float = 1e-6) -> None:
149
+ super().__init__()
150
+ self.eps = eps
151
+ self.weight = nn.Parameter(torch.ones(hidden_size))
152
+
153
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
154
+ orig_dtype = x.dtype
155
+ x = x.to(torch.float32)
156
+ # Clamp values to prevent overflow in pow(2)
157
+ x = torch.clamp(x, min=-65504.0, max=65504.0)
158
+ variance = x.pow(2).mean(-1, keepdim=True)
159
+ x = x * torch.rsqrt(variance + self.eps)
160
+ return (self.weight * x.to(orig_dtype))
161
+
162
+
163
+ class RotaryEmbedding(nn.Module):
164
+ def __init__(
165
+ self,
166
+ dim: int,
167
+ max_position_embeddings: int = 2048,
168
+ base: float = 10000.0,
169
+ device: Optional[torch.device] = None,
170
+ ) -> None:
171
+ super().__init__()
172
+ self.dim = dim
173
+ self.max_position_embeddings = max_position_embeddings
174
+ self.base = base
175
+
176
+ # Always compute inv_freq on CPU to avoid meta-device issues during from_pretrained
177
+ # (low_cpu_mem_usage=True initializes model on meta device, which would give uninitialized values)
178
+ inv_freq = 1.0 / (
179
+ self.base
180
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device="cpu") / dim)
181
+ )
182
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
183
+ self._set_cos_sin_cache(max_position_embeddings, torch.device("cpu"), torch.float32)
184
+
185
+ def _set_cos_sin_cache(self, seq_len: int, device: torch.device, dtype: torch.dtype) -> None:
186
+ self.max_seq_len_cached = seq_len
187
+ t = torch.arange(seq_len, device=device, dtype=self.inv_freq.dtype)
188
+ freqs = torch.outer(t, self.inv_freq)
189
+ emb = torch.cat((freqs, freqs), dim=-1)
190
+ # Always store cache in float32 to avoid precision loss when model dtype is bfloat16
191
+ # (large freqs lose precision in bfloat16, corrupting cos/sin values)
192
+ self.register_buffer("cos_cached", emb.cos().to(torch.float32), persistent=False)
193
+ self.register_buffer("sin_cached", emb.sin().to(torch.float32), persistent=False)
194
+
195
+ def forward(self, x: torch.Tensor, seq_len: int) -> Tuple[torch.Tensor, torch.Tensor]:
196
+ if seq_len > self.max_seq_len_cached:
197
+ self._set_cos_sin_cache(seq_len, x.device, x.dtype)
198
+ return (
199
+ self.cos_cached[:seq_len].to(dtype=x.dtype, device=x.device),
200
+ self.sin_cached[:seq_len].to(dtype=x.dtype, device=x.device),
201
+ )
202
+
203
+ def init_buffers(self) -> None:
204
+ """Re-initialize inv_freq, cos_cached, sin_cached. Call after from_pretrained
205
+ to fix meta-device corruption (low_cpu_mem_usage=True destroys buffer values)."""
206
+ device = self.inv_freq.device
207
+ if device.type == "meta":
208
+ device = torch.device("cpu")
209
+ inv_freq = 1.0 / (
210
+ self.base
211
+ ** (torch.arange(0, self.dim, 2, dtype=torch.float32, device="cpu") / self.dim)
212
+ )
213
+ self.inv_freq = inv_freq.to(device)
214
+ self._set_cos_sin_cache(
215
+ self.max_position_embeddings,
216
+ device,
217
+ torch.float32,
218
+ )
219
+
220
+
221
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
222
+ x1 = x[..., : x.shape[-1] // 2]
223
+ x2 = x[..., x.shape[-1] // 2 :]
224
+ return torch.cat((-x2, x1), dim=-1)
225
+
226
+
227
+ def apply_rotary_pos_emb(
228
+ q: torch.Tensor,
229
+ k: torch.Tensor,
230
+ cos: torch.Tensor,
231
+ sin: torch.Tensor,
232
+ position_ids: Optional[torch.Tensor] = None,
233
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
234
+ if position_ids is None:
235
+ cos = cos.unsqueeze(0).unsqueeze(0)
236
+ sin = sin.unsqueeze(0).unsqueeze(0)
237
+ else:
238
+ cos = cos[position_ids].unsqueeze(1)
239
+ sin = sin[position_ids].unsqueeze(1)
240
+
241
+ return (
242
+ (q * cos) + (rotate_half(q) * sin),
243
+ (k * cos) + (rotate_half(k) * sin),
244
+ )
245
+
246
+
247
+ class GroupedQueryAttention(nn.Module):
248
+ def __init__(self, config: ArgonneConfig) -> None:
249
+ super().__init__()
250
+ self.hidden_size = config.hidden_size
251
+ self.num_heads = config.num_attention_heads
252
+ self.num_kv_heads = config.num_key_value_heads
253
+ self.head_dim = self.hidden_size // self.num_heads
254
+ self.num_key_value_groups = self.num_heads // self.num_kv_heads
255
+ self.sliding_window = config.sliding_window
256
+ self.qk_norm = config.qk_norm
257
+ self.v_norm = config.v_norm
258
+
259
+ self.q_proj = nn.Linear(
260
+ self.hidden_size,
261
+ self.num_heads * self.head_dim,
262
+ bias=config.attention_bias,
263
+ )
264
+ self.k_proj = nn.Linear(
265
+ self.hidden_size,
266
+ self.num_kv_heads * self.head_dim,
267
+ bias=config.attention_bias,
268
+ )
269
+ self.v_proj = nn.Linear(
270
+ self.hidden_size,
271
+ self.num_kv_heads * self.head_dim,
272
+ bias=config.attention_bias,
273
+ )
274
+ self.o_proj = nn.Linear(
275
+ self.num_heads * self.head_dim,
276
+ self.hidden_size,
277
+ bias=config.attention_bias,
278
+ )
279
+ self.o_proj._is_residual = True
280
+
281
+ self.attention_dropout = config.attention_dropout
282
+ self.use_flash_attention = config.use_flash_attention
283
+ if self.qk_norm:
284
+ self.q_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
285
+ self.k_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
286
+ if self.v_norm:
287
+ self.v_norm_layer = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
288
+
289
+ def _repeat_kv(self, x: torch.Tensor) -> torch.Tensor:
290
+ if self.num_key_value_groups == 1:
291
+ return x
292
+ bsz, num_kv, seqlen, head_dim = x.shape
293
+ x = x[:, :, None, :, :].expand(bsz, num_kv, self.num_key_value_groups, seqlen, head_dim)
294
+ return x.reshape(bsz, num_kv * self.num_key_value_groups, seqlen, head_dim)
295
+
296
+ def forward(
297
+ self,
298
+ hidden_states: torch.Tensor,
299
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
300
+ attention_mask: Optional[torch.Tensor] = None,
301
+ past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
302
+ use_cache: bool = False,
303
+ ):
304
+ bsz, seqlen, _ = hidden_states.shape
305
+
306
+ query = self.q_proj(hidden_states)
307
+ key = self.k_proj(hidden_states)
308
+ value = self.v_proj(hidden_states)
309
+
310
+ query = query.view(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2)
311
+ key = key.view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
312
+ value = value.view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)
313
+ if self.qk_norm:
314
+ query = self.q_norm(query)
315
+ key = self.k_norm(key)
316
+ if self.v_norm:
317
+ value = self.v_norm_layer(value)
318
+
319
+ cos, sin = position_embeddings
320
+ query, key = apply_rotary_pos_emb(query, key, cos, sin)
321
+
322
+ # ---- KV cache (inference only; training keeps past_kv=None/use_cache=False) ----
323
+ # Cache pre-repeat (num_kv_heads), post-rotary K/V. The SDPA/math path
324
+ # ignores the sliding window (full causal), so storing all keys and having
325
+ # the new query attend to everything reproduces the no-cache result.
326
+ is_decode = past_kv is not None
327
+ if is_decode:
328
+ past_k, past_v = past_kv
329
+ key = torch.cat([past_k, key], dim=2)
330
+ value = torch.cat([past_v, value], dim=2)
331
+ new_kv = (key, value) if use_cache else None
332
+ kv_len = key.shape[2]
333
+
334
+ # Additive mask used only when decoding with a cache: query at absolute
335
+ # position (kv_len - seqlen + i) attends to keys j <= that position.
336
+ decode_mask = None
337
+ if is_decode:
338
+ q_pos = torch.arange(kv_len - seqlen, kv_len, device=hidden_states.device)
339
+ k_pos = torch.arange(kv_len, device=hidden_states.device)
340
+ allowed = k_pos[None, :] <= q_pos[:, None]
341
+ decode_mask = torch.zeros(seqlen, kv_len, dtype=query.dtype, device=hidden_states.device)
342
+ decode_mask = decode_mask.masked_fill(~allowed, -65504.0)[None, None]
343
+
344
+ key = self._repeat_kv(key)
345
+ value = self._repeat_kv(value)
346
+
347
+ # Argonne-3.5 speedup (hardware accel, training-neutral): qk/v-norm return fp32
348
+ # (fp32 norm-weight * bf16 activation type-promotes), which trips the dtype gate below
349
+ # and forces the hand-rolled O(seq^2) math attention. Under bf16 autocast the matmuls
350
+ # already run in bf16, so casting q/k/v to the autocast dtype here is numerically
351
+ # equivalent (measured rel diff 3.7e-3 < bf16 roundoff 7.8e-3) and lets SDPA pick a fused
352
+ # FLASH/cuDNN kernel: ~2x lower attention memory + faster. Training-under-autocast only;
353
+ # inference/decode (self.training False) is untouched.
354
+ if self.training and torch.is_autocast_enabled() and query.dtype not in (torch.float16, torch.bfloat16):
355
+ _ac_dtype = torch.get_autocast_dtype("cuda") if hasattr(torch, "get_autocast_dtype") else torch.get_autocast_gpu_dtype()
356
+ query = query.to(_ac_dtype)
357
+ key = key.to(_ac_dtype)
358
+ value = value.to(_ac_dtype)
359
+
360
+ use_flash_attn_2 = (
361
+ not is_decode
362
+ and _flash_attn_available
363
+ and self.use_flash_attention
364
+ and attention_mask is None
365
+ and query.dtype in (torch.float16, torch.bfloat16)
366
+ and self.head_dim % 4 == 0
367
+ )
368
+ use_scaled_dot = (
369
+ hasattr(F, "scaled_dot_product_attention")
370
+ and self.use_flash_attention
371
+ and query.dtype in (torch.float16, torch.bfloat16)
372
+ and self.head_dim % 4 == 0
373
+ )
374
+
375
+ attn_output = None
376
+ if use_flash_attn_2:
377
+ try:
378
+ flash_dropout = self.attention_dropout if self.training else 0.0
379
+ window = (
380
+ (self.sliding_window, self.sliding_window)
381
+ if self.sliding_window is not None
382
+ else (-1, -1)
383
+ )
384
+ q = query.transpose(1, 2).contiguous()
385
+ k = key.transpose(1, 2).contiguous()
386
+ v = value.transpose(1, 2).contiguous()
387
+ attn_output = flash_attn_func(
388
+ q,
389
+ k,
390
+ v,
391
+ dropout_p=flash_dropout,
392
+ softmax_scale=None,
393
+ causal=True,
394
+ window_size=window,
395
+ ).transpose(1, 2)
396
+ except RuntimeError:
397
+ attn_output = None
398
+
399
+ if attn_output is None and use_scaled_dot:
400
+ try:
401
+ if decode_mask is not None:
402
+ attn_output = F.scaled_dot_product_attention(
403
+ query, key, value, attn_mask=decode_mask,
404
+ dropout_p=0.0, is_causal=False,
405
+ )
406
+ elif attention_mask is None:
407
+ # Prefill / training: fast causal path.
408
+ attn_output = F.scaled_dot_product_attention(
409
+ query,
410
+ key,
411
+ value,
412
+ attn_mask=None,
413
+ dropout_p=self.attention_dropout if self.training else 0.0,
414
+ is_causal=True,
415
+ )
416
+ else:
417
+ # With attention_mask: need to pass it explicitly (slower but correct)
418
+ # attention_mask should be 4D: (bsz, 1, seq, seq) or broadcastable
419
+ attn_output = F.scaled_dot_product_attention(
420
+ query,
421
+ key,
422
+ value,
423
+ attn_mask=attention_mask,
424
+ dropout_p=self.attention_dropout if self.training else 0.0,
425
+ is_causal=False, # Mask already includes causal component
426
+ )
427
+ except RuntimeError:
428
+ # Fallback to math attention when kernels are unavailable
429
+ attn_output = None
430
+
431
+ if attn_output is None:
432
+ scores = torch.matmul(query, key.transpose(2, 3)) / math.sqrt(self.head_dim)
433
+ mask_value = -65504.0 # Large negative instead of -inf
434
+ if decode_mask is not None:
435
+ scores = scores + decode_mask
436
+ else:
437
+ # Apply causal mask - use large negative instead of -inf for stability
438
+ causal_mask = torch.triu(
439
+ torch.ones(seqlen, kv_len, dtype=torch.bool, device=hidden_states.device),
440
+ diagonal=1,
441
+ )
442
+ scores = scores.masked_fill(causal_mask, mask_value)
443
+ if attention_mask is not None:
444
+ scores = scores + attention_mask
445
+ attn_weights = torch.softmax(scores, dim=-1, dtype=torch.float32).to(query.dtype)
446
+ attn_weights = F.dropout(attn_weights, p=self.attention_dropout, training=self.training)
447
+ attn_output = torch.matmul(attn_weights, value)
448
+
449
+ attn_output = (
450
+ attn_output.transpose(1, 2)
451
+ .contiguous()
452
+ .view(bsz, seqlen, self.num_heads * self.head_dim)
453
+ )
454
+ out = self.o_proj(attn_output)
455
+ if use_cache:
456
+ return out, new_kv
457
+ return out
458
+
459
+
460
+ class SwiGLUMLP(nn.Module):
461
+ def __init__(self, config: ArgonneConfig) -> None:
462
+ super().__init__()
463
+ self.gate_proj = nn.Linear(
464
+ config.hidden_size,
465
+ config.intermediate_size,
466
+ bias=config.mlp_bias,
467
+ )
468
+ self.up_proj = nn.Linear(
469
+ config.hidden_size,
470
+ config.intermediate_size,
471
+ bias=config.mlp_bias,
472
+ )
473
+ self.down_proj = nn.Linear(
474
+ config.intermediate_size,
475
+ config.hidden_size,
476
+ bias=config.mlp_bias,
477
+ )
478
+ self.down_proj._is_residual = True
479
+ self.dropout = nn.Dropout(config.hidden_dropout)
480
+
481
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
482
+ # Clamp intermediate values to prevent overflow
483
+ gate = self.gate_proj(x)
484
+ gate = torch.clamp(gate, min=-65504.0, max=65504.0)
485
+ up = self.up_proj(x)
486
+ up = torch.clamp(up, min=-65504.0, max=65504.0)
487
+ return self.dropout(self.down_proj(F.silu(gate) * up))
488
+
489
+
490
+ class Block(nn.Module):
491
+ """Transformer block with GQA attention and SwiGLU feed-forward."""
492
+
493
+ def __init__(self, config: ArgonneConfig, layer_idx: int = 0) -> None:
494
+ super().__init__()
495
+ self.layer_idx = layer_idx
496
+ self.attn = GroupedQueryAttention(config)
497
+ self.input_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
498
+ self.post_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
499
+ self.sandwich_norm = config.sandwich_norm
500
+ if self.sandwich_norm:
501
+ self.attn_out_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
502
+ self.mlp_out_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
503
+ self.mlp = SwiGLUMLP(config)
504
+
505
+ def forward(
506
+ self,
507
+ hidden_states: torch.Tensor,
508
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
509
+ attention_mask: Optional[torch.Tensor] = None,
510
+ past_kv: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
511
+ use_cache: bool = False,
512
+ ):
513
+ residual = hidden_states
514
+ hidden_states = self.input_norm(hidden_states)
515
+ attn_out = self.attn(
516
+ hidden_states, position_embeddings, attention_mask,
517
+ past_kv=past_kv, use_cache=use_cache,
518
+ )
519
+ new_kv = None
520
+ if use_cache:
521
+ hidden_states, new_kv = attn_out
522
+ else:
523
+ hidden_states = attn_out
524
+ if self.sandwich_norm:
525
+ hidden_states = self.attn_out_norm(hidden_states)
526
+ hidden_states = residual + hidden_states
527
+
528
+ residual = hidden_states
529
+ hidden_states = self.post_norm(hidden_states)
530
+ hidden_states = self.mlp(hidden_states)
531
+ if self.sandwich_norm:
532
+ hidden_states = self.mlp_out_norm(hidden_states)
533
+ hidden_states = residual + hidden_states
534
+ if use_cache:
535
+ return hidden_states, new_kv
536
+
537
+ return hidden_states
538
+
539
+
540
+ class ArgonneModel(PreTrainedModel):
541
+ config_class = ArgonneConfig
542
+ _no_split_modules = ["Block"]
543
+ _tied_weights_keys = {"lm_head.weight": "embed_tokens.weight"}
544
+
545
+ def __init__(self, config: ArgonneConfig) -> None:
546
+ super().__init__(config)
547
+ self.config = config
548
+
549
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
550
+ self.blocks = nn.ModuleList([Block(config, idx) for idx in range(config.num_hidden_layers)])
551
+ if config.interleaved_local_attention and config.local_attention_window is not None:
552
+ for idx, block in enumerate(self.blocks):
553
+ block.attn.sliding_window = config.local_attention_window if (idx % 2 == 1) else None
554
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
555
+ self.rotary_emb = RotaryEmbedding(
556
+ config.hidden_size // config.num_attention_heads,
557
+ max_position_embeddings=config.max_position_embeddings,
558
+ base=config.rope_theta,
559
+ )
560
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
561
+
562
+ if config.tie_word_embeddings:
563
+ self.lm_head.weight = self.embed_tokens.weight
564
+
565
+ self.gradient_checkpointing = config.use_gradient_checkpointing
566
+ # Selective activation checkpointing (ported from argonne4.0). Runtime-only --
567
+ # NOT part of config or state_dict, so checkpoint/resume compatibility with every
568
+ # existing argonne3.5 checkpoint is unaffected. checkpoint_stride S:
569
+ # S == 1 : checkpoint ALL layers (default; identical to prior behavior).
570
+ # S >= 2 : checkpoint every layer EXCEPT store (un-checkpoint) every Sth layer
571
+ # -> store ceil(n_layers/S), recompute the rest. Smaller S stores MORE
572
+ # (more HBM, less recompute, faster); too-small S OOMs.
573
+ # Numerically identical either way: it only chooses store-vs-recompute.
574
+ self.checkpoint_stride = 1
575
+ self._nan_loss_count = 0
576
+ self.post_init()
577
+
578
+ global _attention_path_logged
579
+ rank = os.environ.get("RANK") or os.environ.get("SLURM_PROCID") or "0"
580
+ if not _attention_path_logged and rank == "0":
581
+ _attention_path_logged = True
582
+ window = (
583
+ config.local_attention_window if config.interleaved_local_attention else None
584
+ )
585
+ if _flash_attn_available and config.use_flash_attention:
586
+ note = (
587
+ f"flash-attn-2; sliding window {window} active on odd layers"
588
+ if window is not None
589
+ else "flash-attn-2; full attention"
590
+ )
591
+ else:
592
+ reason = (
593
+ "flash-attn unavailable"
594
+ if config.use_flash_attention
595
+ else "use_flash_attention=False"
596
+ )
597
+ note = f"SDPA/math ({reason}); full attention"
598
+ if window is not None:
599
+ note += (
600
+ f" — local_attention_window={window} is configured but"
601
+ " IGNORED on this path"
602
+ )
603
+ print(f"[ArgonneModel] attention path: {note}", flush=True)
604
+
605
+ def get_input_embeddings(self) -> nn.Embedding:
606
+ return self.embed_tokens
607
+
608
+ def set_input_embeddings(self, new_embeddings: nn.Embedding) -> None:
609
+ self.embed_tokens = new_embeddings
610
+ self.config.vocab_size = new_embeddings.num_embeddings
611
+ if self.config.tie_word_embeddings:
612
+ self.lm_head.weight = self.embed_tokens.weight
613
+
614
+ def get_output_embeddings(self) -> nn.Module:
615
+ return self.lm_head
616
+
617
+ def set_output_embeddings(self, new_embeddings: nn.Module) -> None:
618
+ self.lm_head = new_embeddings
619
+ if isinstance(new_embeddings, nn.Linear):
620
+ self.config.vocab_size = new_embeddings.out_features
621
+
622
+ def tie_weights(self, **kwargs) -> None:
623
+ if self.config.tie_word_embeddings:
624
+ self.lm_head.weight = self.embed_tokens.weight
625
+
626
+ @classmethod
627
+ def from_pretrained(cls, *args, **kwargs):
628
+ """Wrap PreTrainedModel.from_pretrained to self-heal after loading.
629
+
630
+ from_pretrained may materialize the model via the meta device
631
+ (low_cpu_mem_usage), which fills the rotary embedding's non-persistent
632
+ buffers with uninitialized memory and can drop the
633
+ embed_tokens/lm_head tie. Callers previously had to remember to call
634
+ init_buffers() and tie_weights() by hand; do it here so every loader
635
+ gets a working model.
636
+ """
637
+ model = super().from_pretrained(*args, **kwargs)
638
+ for module in model.modules():
639
+ if isinstance(module, RotaryEmbedding):
640
+ module.init_buffers()
641
+ model.tie_weights()
642
+ return model
643
+
644
+ def _init_weights(self, module: nn.Module) -> None:
645
+ if isinstance(module, nn.Linear):
646
+ std = self.config.hidden_size ** -0.5
647
+ if hasattr(module, "_is_residual"):
648
+ std = (2 * self.config.num_hidden_layers) ** -0.5
649
+ nn.init.normal_(module.weight, mean=0.0, std=std)
650
+ if module.bias is not None:
651
+ nn.init.zeros_(module.bias)
652
+ elif isinstance(module, nn.Embedding):
653
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.hidden_size ** -0.5)
654
+
655
+ def set_gradient_checkpointing(self, enabled: bool = True) -> None:
656
+ self.gradient_checkpointing = enabled
657
+
658
+ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None) -> None:
659
+ self.set_gradient_checkpointing(True)
660
+
661
+ def gradient_checkpointing_disable(self) -> None:
662
+ self.set_gradient_checkpointing(False)
663
+
664
+ def forward(
665
+ self,
666
+ input_ids: torch.LongTensor,
667
+ attention_mask: Optional[torch.Tensor] = None,
668
+ labels: Optional[torch.LongTensor] = None,
669
+ position_ids: Optional[torch.LongTensor] = None,
670
+ past_key_values: Optional[list] = None,
671
+ use_cache: bool = False,
672
+ **kwargs, # Accept extra args from newer transformers (e.g., num_items_in_batch)
673
+ ) -> CausalLMOutput:
674
+ _, seq_length = input_ids.shape
675
+
676
+ device = self.embed_tokens.weight.device
677
+ if input_ids.device != device:
678
+ input_ids = input_ids.to(device)
679
+ hidden_states = self.embed_tokens(input_ids)
680
+
681
+ # The training path does not use attention masks.
682
+ attention_mask = None
683
+
684
+ # RoPE positions are offset by the cached length so incremental decode
685
+ # uses the correct absolute positions.
686
+ past_len = past_key_values[0][0].shape[2] if past_key_values else 0
687
+ cos_full, sin_full = self.rotary_emb(hidden_states, past_len + seq_length)
688
+ rotary = (cos_full[past_len:past_len + seq_length],
689
+ sin_full[past_len:past_len + seq_length])
690
+
691
+ new_cache = [] if use_cache else None
692
+ for i, layer in enumerate(self.blocks):
693
+ _skip_ckpt = (self.checkpoint_stride >= 2) and (i % self.checkpoint_stride == 0)
694
+ if self.gradient_checkpointing and self.training and not _skip_ckpt:
695
+ hidden_states = torch.utils.checkpoint.checkpoint(
696
+ layer,
697
+ hidden_states,
698
+ rotary,
699
+ attention_mask,
700
+ use_reentrant=False,
701
+ )
702
+ elif use_cache:
703
+ past_kv = past_key_values[i] if past_key_values else None
704
+ hidden_states, layer_kv = layer(
705
+ hidden_states, rotary, attention_mask,
706
+ past_kv=past_kv, use_cache=True,
707
+ )
708
+ new_cache.append(layer_kv)
709
+ else:
710
+ hidden_states = layer(hidden_states, rotary, attention_mask)
711
+
712
+ hidden_states = self.norm(hidden_states)
713
+
714
+ # Chunked cross-entropy (training only, flag-gated via config.loss_chunk_size): avoids
715
+ # materializing the full (batch*seq, vocab) fp32 logit tensor -- the HBM wall at long context.
716
+ # Early-return so the standard full-logit path below stays byte-for-byte unchanged (zero risk to
717
+ # non-chunked / default runs). Only taken when MTP + z-loss are off (both default off).
718
+ _chunk = getattr(self.config, "loss_chunk_size", 0)
719
+ if (self.training and labels is not None and _chunk > 0
720
+ and self.config.mtp_horizon == 1 and self.config.z_loss_weight == 0):
721
+ loss = self._chunked_lm_loss(hidden_states, labels, _chunk)
722
+ if torch.isnan(loss):
723
+ self._nan_loss_count += 1
724
+ if self._nan_loss_count <= 5 or self._nan_loss_count % 100 == 0:
725
+ print(f"WARNING: NaN loss detected (occurrence {self._nan_loss_count}); "
726
+ "zeroing this step's loss.", flush=True)
727
+ zero = torch.zeros((), device=loss.device, dtype=torch.float32)
728
+ for p in self.parameters():
729
+ if p.requires_grad:
730
+ zero = zero + torch.nan_to_num(p).sum().float() * 0.0
731
+ loss = zero.to(loss.dtype)
732
+ return CausalLMOutput(logits=None, loss=loss)
733
+
734
+ logits = self.lm_head(hidden_states)
735
+ if self.config.logit_softcap > 0:
736
+ cap = self.config.logit_softcap
737
+ logits = torch.tanh(logits / cap) * cap
738
+
739
+ # Sanitize logits only at inference. During training the full-tensor
740
+ # scan forces a GPU sync every step over [batch, seq, vocab]; a NaN
741
+ # would surface in the loss check below anyway.
742
+ if not self.training and torch.isnan(logits).any():
743
+ logits = torch.nan_to_num(logits, nan=0.0, posinf=65504.0, neginf=-65504.0)
744
+
745
+ loss = None
746
+ if labels is not None:
747
+ if labels.device != logits.device:
748
+ labels = labels.to(logits.device)
749
+ loss = F.cross_entropy(
750
+ logits.view(-1, logits.size(-1)),
751
+ labels.view(-1),
752
+ ignore_index=-100,
753
+ )
754
+ if self.training and self.config.mtp_horizon > 1:
755
+ mtp_terms = []
756
+ max_horizon = min(self.config.mtp_horizon, labels.shape[1])
757
+ for horizon in range(2, max_horizon + 1):
758
+ shift = horizon - 1
759
+ shifted_logits = logits[:, :-shift, :]
760
+ shifted_labels = labels[:, shift:]
761
+ if shifted_logits.numel() == 0:
762
+ continue
763
+ mtp_loss = F.cross_entropy(
764
+ shifted_logits.reshape(-1, shifted_logits.size(-1)),
765
+ shifted_labels.reshape(-1),
766
+ ignore_index=-100,
767
+ )
768
+ mtp_terms.append(mtp_loss / horizon)
769
+ if mtp_terms:
770
+ loss = loss + (self.config.mtp_loss_weight * torch.stack(mtp_terms).mean()).to(loss.dtype)
771
+ if self.config.z_loss_weight > 0:
772
+ z = torch.logsumexp(logits.float(), dim=-1)
773
+ loss = loss + (self.config.z_loss_weight * z.pow(2).mean()).to(loss.dtype)
774
+
775
+ # A NaN loss becomes a zero loss that is still connected to every
776
+ # parameter — but through the parameters directly, NOT through the
777
+ # network's (possibly NaN) activations. Backward then delivers an
778
+ # exact zero gradient to each parameter: DDP/FSDP gradient hooks
779
+ # all fire (no collective desync/hang) and the optimizer step is a
780
+ # true no-op. Warn (bounded) instead of hiding it.
781
+ if torch.isnan(loss):
782
+ self._nan_loss_count += 1
783
+ if self._nan_loss_count <= 5 or self._nan_loss_count % 100 == 0:
784
+ print(
785
+ f"WARNING: NaN loss detected (occurrence {self._nan_loss_count}); "
786
+ "zeroing this step's loss.",
787
+ flush=True,
788
+ )
789
+ zero = torch.zeros((), device=loss.device, dtype=torch.float32)
790
+ for p in self.parameters():
791
+ if p.requires_grad:
792
+ zero = zero + torch.nan_to_num(p).sum().float() * 0.0
793
+ loss = zero.to(loss.dtype)
794
+
795
+ if use_cache:
796
+ return CausalLMOutputWithPast(logits=logits, loss=loss, past_key_values=new_cache)
797
+ return CausalLMOutput(logits=logits, loss=loss)
798
+
799
+ @torch.compiler.disable
800
+ def _chunked_lm_loss(self, hidden_states, labels, chunk_size):
801
+ """Cross-entropy without ever materializing the full (batch*seq, vocab) fp32 logit tensor.
802
+ MUST run eager (@torch.compiler.disable): torch.compile/inductor otherwise fuses the chunks
803
+ back into the full (N, vocab) logit tensor, re-creating the OOM this is meant to avoid. The
804
+ transformer body still compiles (+FP8); only this loss runs eager (a small fraction of compute).
805
+ Splits the flattened rows into chunks; torch.utils.checkpoint recomputes each chunk's logits
806
+ in backward, so peak logit memory = chunk_size*vocab (not N*vocab). Numerically identical to
807
+ F.cross_entropy(full_logits, labels.view(-1), ignore_index=-100) with per-chunk softcap
808
+ (mean over non-ignored). Caller guarantees mtp_horizon==1 and z_loss_weight==0.
809
+ Uses self.lm_head(...) per chunk so the fp8 (Float8Linear) GEMM path is preserved."""
810
+ from torch.utils.checkpoint import checkpoint as _ckpt
811
+ cap = float(self.config.logit_softcap)
812
+ H = hidden_states.reshape(-1, hidden_states.size(-1))
813
+ L = labels.reshape(-1).to(H.device)
814
+ N = H.size(0)
815
+
816
+ def _seg(hc, lc):
817
+ lg = self.lm_head(hc) # (chunk, vocab); Float8Linear under fp8
818
+ if cap > 0:
819
+ lg = torch.tanh(lg / cap) * cap
820
+ return F.cross_entropy(lg, lc, ignore_index=-100, reduction="sum")
821
+
822
+ total = H.new_zeros((), dtype=torch.float32)
823
+ ntok = torch.zeros((), device=H.device, dtype=torch.float32)
824
+ cs = max(1, int(chunk_size))
825
+ for i in range(0, N, cs):
826
+ hc = H[i:i + cs]
827
+ lc = L[i:i + cs]
828
+ seg = _ckpt(_seg, hc, lc, use_reentrant=False) if self.training else _seg(hc, lc)
829
+ total = total + seg.float()
830
+ ntok = ntok + (lc != -100).sum().float()
831
+ return total / ntok.clamp(min=1.0)
832
+
833
+ @torch.no_grad()
834
+ def generate(
835
+ self,
836
+ input_ids: torch.Tensor,
837
+ max_length: int = 1024,
838
+ temperature: float = 1.0,
839
+ top_k: Optional[int] = None,
840
+ top_p: Optional[float] = None,
841
+ do_sample: bool = True,
842
+ repetition_penalty: float = 1.0,
843
+ no_repeat_ngram_size: int = 0,
844
+ ) -> torch.Tensor:
845
+ self.eval()
846
+ device = self.embed_tokens.weight.device
847
+ input_ids = input_ids.to(device)
848
+ ctx = self.config.max_position_embeddings
849
+ # KV-cache decode: prefill the prompt once, then feed a single token per
850
+ # step reusing past_key_values. This yields identical logits to the
851
+ # recompute-the-whole-prefix path (gated by verify_cache.py) but turns the
852
+ # per-step cost from O(seq_len) down to O(1). When the running sequence
853
+ # would exceed the context window we rebuild the cache from the truncated
854
+ # window, matching the original chunk = input_ids[:, -ctx:] behavior.
855
+ past = None
856
+ outputs = None
857
+ while input_ids.shape[1] < max_length:
858
+ if past is None or past[0][0].shape[2] >= ctx:
859
+ chunk = input_ids[:, -ctx:]
860
+ outputs = self.forward(chunk, use_cache=True)
861
+ past = outputs.past_key_values
862
+ logits = outputs.logits[:, -1, :] / temperature
863
+
864
+ if repetition_penalty != 1.0:
865
+ for b in range(input_ids.shape[0]):
866
+ seen_tokens = torch.unique(input_ids[b])
867
+ seen_logits = logits[b, seen_tokens]
868
+ adjusted = torch.where(
869
+ seen_logits < 0,
870
+ seen_logits * repetition_penalty,
871
+ seen_logits / repetition_penalty,
872
+ )
873
+ logits[b, seen_tokens] = adjusted
874
+
875
+ if no_repeat_ngram_size > 0 and input_ids.shape[1] + 1 >= no_repeat_ngram_size:
876
+ n = int(no_repeat_ngram_size)
877
+ for b in range(input_ids.shape[0]):
878
+ seq = input_ids[b].tolist()
879
+ ngrams = {}
880
+ for i in range(len(seq) - n + 1):
881
+ prefix = tuple(seq[i : i + n - 1]) if n > 1 else tuple()
882
+ next_token = seq[i + n - 1]
883
+ if prefix not in ngrams:
884
+ ngrams[prefix] = set()
885
+ ngrams[prefix].add(next_token)
886
+ current_prefix = tuple(seq[-(n - 1) :]) if n > 1 else tuple()
887
+ banned = ngrams.get(current_prefix, set())
888
+ if banned:
889
+ logits[b, list(banned)] = float("-inf")
890
+
891
+ if do_sample:
892
+ if top_k is not None:
893
+ top_values, _ = torch.topk(logits, min(top_k, logits.size(-1)))
894
+ logits = logits.masked_fill(logits < top_values[:, [-1]], float("-inf"))
895
+ if top_p is not None:
896
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
897
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
898
+ sorted_indices_to_remove = cumulative_probs > top_p
899
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
900
+ sorted_indices_to_remove[..., 0] = 0
901
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
902
+ logits = logits.masked_fill(indices_to_remove, float("-inf"))
903
+ probs = F.softmax(logits, dim=-1)
904
+ next_token = torch.multinomial(probs, num_samples=1)
905
+ else:
906
+ next_token = torch.argmax(logits, dim=-1, keepdim=True)
907
+
908
+ next_token = next_token.to(input_ids.device)
909
+ input_ids = torch.cat([input_ids, next_token], dim=-1)
910
+ if input_ids.shape[1] >= max_length:
911
+ break
912
+ # Advance the cache by one token unless we must rebuild it next loop
913
+ # (cache full); the top-of-loop guard re-prefills in that case.
914
+ if past[0][0].shape[2] < ctx:
915
+ outputs = self.forward(next_token, past_key_values=past, use_cache=True)
916
+ past = outputs.past_key_values
917
+ return input_ids.to(device)
918
+
919
+
920
+ AutoConfig.register("argonne2", ArgonneConfig)
921
+ AutoModel.register(ArgonneConfig, ArgonneModel)
922
+ AutoModelForCausalLM.register(ArgonneConfig, ArgonneModel)
923
+
924
+ # Backwards compatibility exports
925
+ CausalSelfAttention = GroupedQueryAttention
926
+ MLP = SwiGLUMLP
model.safetensors.index.json ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5764325376
4
+ },
5
+ "weight_map": {
6
+ "blocks.0.attn.k_norm.weight": "model-00001-of-00005.safetensors",
7
+ "blocks.0.attn.k_proj.weight": "model-00001-of-00005.safetensors",
8
+ "blocks.0.attn.o_proj.weight": "model-00001-of-00005.safetensors",
9
+ "blocks.0.attn.q_norm.weight": "model-00001-of-00005.safetensors",
10
+ "blocks.0.attn.q_proj.weight": "model-00001-of-00005.safetensors",
11
+ "blocks.0.attn.v_norm_layer.weight": "model-00001-of-00005.safetensors",
12
+ "blocks.0.attn.v_proj.weight": "model-00001-of-00005.safetensors",
13
+ "blocks.0.attn_out_norm.weight": "model-00001-of-00005.safetensors",
14
+ "blocks.0.input_norm.weight": "model-00001-of-00005.safetensors",
15
+ "blocks.0.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
16
+ "blocks.0.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
17
+ "blocks.0.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
18
+ "blocks.0.mlp_out_norm.weight": "model-00001-of-00005.safetensors",
19
+ "blocks.0.post_norm.weight": "model-00001-of-00005.safetensors",
20
+ "blocks.1.attn.k_norm.weight": "model-00001-of-00005.safetensors",
21
+ "blocks.1.attn.k_proj.weight": "model-00001-of-00005.safetensors",
22
+ "blocks.1.attn.o_proj.weight": "model-00001-of-00005.safetensors",
23
+ "blocks.1.attn.q_norm.weight": "model-00001-of-00005.safetensors",
24
+ "blocks.1.attn.q_proj.weight": "model-00001-of-00005.safetensors",
25
+ "blocks.1.attn.v_norm_layer.weight": "model-00001-of-00005.safetensors",
26
+ "blocks.1.attn.v_proj.weight": "model-00001-of-00005.safetensors",
27
+ "blocks.1.attn_out_norm.weight": "model-00001-of-00005.safetensors",
28
+ "blocks.1.input_norm.weight": "model-00001-of-00005.safetensors",
29
+ "blocks.1.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
30
+ "blocks.1.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
31
+ "blocks.1.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
32
+ "blocks.1.mlp_out_norm.weight": "model-00001-of-00005.safetensors",
33
+ "blocks.1.post_norm.weight": "model-00001-of-00005.safetensors",
34
+ "blocks.10.attn.k_norm.weight": "model-00001-of-00005.safetensors",
35
+ "blocks.10.attn.k_proj.weight": "model-00001-of-00005.safetensors",
36
+ "blocks.10.attn.o_proj.weight": "model-00001-of-00005.safetensors",
37
+ "blocks.10.attn.q_norm.weight": "model-00001-of-00005.safetensors",
38
+ "blocks.10.attn.q_proj.weight": "model-00001-of-00005.safetensors",
39
+ "blocks.10.attn.v_norm_layer.weight": "model-00001-of-00005.safetensors",
40
+ "blocks.10.attn.v_proj.weight": "model-00001-of-00005.safetensors",
41
+ "blocks.10.attn_out_norm.weight": "model-00001-of-00005.safetensors",
42
+ "blocks.10.input_norm.weight": "model-00001-of-00005.safetensors",
43
+ "blocks.10.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
44
+ "blocks.10.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
45
+ "blocks.10.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
46
+ "blocks.10.mlp_out_norm.weight": "model-00001-of-00005.safetensors",
47
+ "blocks.10.post_norm.weight": "model-00001-of-00005.safetensors",
48
+ "blocks.11.attn.k_norm.weight": "model-00001-of-00005.safetensors",
49
+ "blocks.11.attn.k_proj.weight": "model-00001-of-00005.safetensors",
50
+ "blocks.11.attn.o_proj.weight": "model-00001-of-00005.safetensors",
51
+ "blocks.11.attn.q_norm.weight": "model-00001-of-00005.safetensors",
52
+ "blocks.11.attn.q_proj.weight": "model-00001-of-00005.safetensors",
53
+ "blocks.11.attn.v_norm_layer.weight": "model-00001-of-00005.safetensors",
54
+ "blocks.11.attn.v_proj.weight": "model-00001-of-00005.safetensors",
55
+ "blocks.11.attn_out_norm.weight": "model-00001-of-00005.safetensors",
56
+ "blocks.11.input_norm.weight": "model-00001-of-00005.safetensors",
57
+ "blocks.11.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
58
+ "blocks.11.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
59
+ "blocks.11.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
60
+ "blocks.11.mlp_out_norm.weight": "model-00001-of-00005.safetensors",
61
+ "blocks.11.post_norm.weight": "model-00001-of-00005.safetensors",
62
+ "blocks.12.attn.k_norm.weight": "model-00001-of-00005.safetensors",
63
+ "blocks.12.attn.k_proj.weight": "model-00001-of-00005.safetensors",
64
+ "blocks.12.attn.o_proj.weight": "model-00001-of-00005.safetensors",
65
+ "blocks.12.attn.q_norm.weight": "model-00001-of-00005.safetensors",
66
+ "blocks.12.attn.q_proj.weight": "model-00001-of-00005.safetensors",
67
+ "blocks.12.attn.v_norm_layer.weight": "model-00001-of-00005.safetensors",
68
+ "blocks.12.attn.v_proj.weight": "model-00001-of-00005.safetensors",
69
+ "blocks.12.attn_out_norm.weight": "model-00001-of-00005.safetensors",
70
+ "blocks.12.input_norm.weight": "model-00001-of-00005.safetensors",
71
+ "blocks.12.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
72
+ "blocks.12.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
73
+ "blocks.12.mlp.up_proj.weight": "model-00001-of-00005.safetensors",
74
+ "blocks.12.mlp_out_norm.weight": "model-00001-of-00005.safetensors",
75
+ "blocks.12.post_norm.weight": "model-00001-of-00005.safetensors",
76
+ "blocks.13.attn.k_norm.weight": "model-00001-of-00005.safetensors",
77
+ "blocks.13.attn.k_proj.weight": "model-00001-of-00005.safetensors",
78
+ "blocks.13.attn.o_proj.weight": "model-00001-of-00005.safetensors",
79
+ "blocks.13.attn.q_norm.weight": "model-00001-of-00005.safetensors",
80
+ "blocks.13.attn.q_proj.weight": "model-00001-of-00005.safetensors",
81
+ "blocks.13.attn.v_norm_layer.weight": "model-00001-of-00005.safetensors",
82
+ "blocks.13.attn.v_proj.weight": "model-00001-of-00005.safetensors",
83
+ "blocks.13.attn_out_norm.weight": "model-00001-of-00005.safetensors",
84
+ "blocks.13.input_norm.weight": "model-00001-of-00005.safetensors",
85
+ "blocks.13.mlp.down_proj.weight": "model-00001-of-00005.safetensors",
86
+ "blocks.13.mlp.gate_proj.weight": "model-00001-of-00005.safetensors",
87
+ "blocks.13.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
88
+ "blocks.13.mlp_out_norm.weight": "model-00002-of-00005.safetensors",
89
+ "blocks.13.post_norm.weight": "model-00002-of-00005.safetensors",
90
+ "blocks.14.attn.k_norm.weight": "model-00002-of-00005.safetensors",
91
+ "blocks.14.attn.k_proj.weight": "model-00002-of-00005.safetensors",
92
+ "blocks.14.attn.o_proj.weight": "model-00002-of-00005.safetensors",
93
+ "blocks.14.attn.q_norm.weight": "model-00002-of-00005.safetensors",
94
+ "blocks.14.attn.q_proj.weight": "model-00002-of-00005.safetensors",
95
+ "blocks.14.attn.v_norm_layer.weight": "model-00002-of-00005.safetensors",
96
+ "blocks.14.attn.v_proj.weight": "model-00002-of-00005.safetensors",
97
+ "blocks.14.attn_out_norm.weight": "model-00002-of-00005.safetensors",
98
+ "blocks.14.input_norm.weight": "model-00002-of-00005.safetensors",
99
+ "blocks.14.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
100
+ "blocks.14.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
101
+ "blocks.14.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
102
+ "blocks.14.mlp_out_norm.weight": "model-00002-of-00005.safetensors",
103
+ "blocks.14.post_norm.weight": "model-00002-of-00005.safetensors",
104
+ "blocks.15.attn.k_norm.weight": "model-00002-of-00005.safetensors",
105
+ "blocks.15.attn.k_proj.weight": "model-00002-of-00005.safetensors",
106
+ "blocks.15.attn.o_proj.weight": "model-00002-of-00005.safetensors",
107
+ "blocks.15.attn.q_norm.weight": "model-00002-of-00005.safetensors",
108
+ "blocks.15.attn.q_proj.weight": "model-00002-of-00005.safetensors",
109
+ "blocks.15.attn.v_norm_layer.weight": "model-00002-of-00005.safetensors",
110
+ "blocks.15.attn.v_proj.weight": "model-00002-of-00005.safetensors",
111
+ "blocks.15.attn_out_norm.weight": "model-00002-of-00005.safetensors",
112
+ "blocks.15.input_norm.weight": "model-00002-of-00005.safetensors",
113
+ "blocks.15.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
114
+ "blocks.15.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
115
+ "blocks.15.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
116
+ "blocks.15.mlp_out_norm.weight": "model-00002-of-00005.safetensors",
117
+ "blocks.15.post_norm.weight": "model-00002-of-00005.safetensors",
118
+ "blocks.16.attn.k_norm.weight": "model-00002-of-00005.safetensors",
119
+ "blocks.16.attn.k_proj.weight": "model-00002-of-00005.safetensors",
120
+ "blocks.16.attn.o_proj.weight": "model-00002-of-00005.safetensors",
121
+ "blocks.16.attn.q_norm.weight": "model-00002-of-00005.safetensors",
122
+ "blocks.16.attn.q_proj.weight": "model-00002-of-00005.safetensors",
123
+ "blocks.16.attn.v_norm_layer.weight": "model-00002-of-00005.safetensors",
124
+ "blocks.16.attn.v_proj.weight": "model-00002-of-00005.safetensors",
125
+ "blocks.16.attn_out_norm.weight": "model-00002-of-00005.safetensors",
126
+ "blocks.16.input_norm.weight": "model-00002-of-00005.safetensors",
127
+ "blocks.16.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
128
+ "blocks.16.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
129
+ "blocks.16.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
130
+ "blocks.16.mlp_out_norm.weight": "model-00002-of-00005.safetensors",
131
+ "blocks.16.post_norm.weight": "model-00002-of-00005.safetensors",
132
+ "blocks.17.attn.k_norm.weight": "model-00002-of-00005.safetensors",
133
+ "blocks.17.attn.k_proj.weight": "model-00002-of-00005.safetensors",
134
+ "blocks.17.attn.o_proj.weight": "model-00002-of-00005.safetensors",
135
+ "blocks.17.attn.q_norm.weight": "model-00002-of-00005.safetensors",
136
+ "blocks.17.attn.q_proj.weight": "model-00002-of-00005.safetensors",
137
+ "blocks.17.attn.v_norm_layer.weight": "model-00002-of-00005.safetensors",
138
+ "blocks.17.attn.v_proj.weight": "model-00002-of-00005.safetensors",
139
+ "blocks.17.attn_out_norm.weight": "model-00002-of-00005.safetensors",
140
+ "blocks.17.input_norm.weight": "model-00002-of-00005.safetensors",
141
+ "blocks.17.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
142
+ "blocks.17.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
143
+ "blocks.17.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
144
+ "blocks.17.mlp_out_norm.weight": "model-00002-of-00005.safetensors",
145
+ "blocks.17.post_norm.weight": "model-00002-of-00005.safetensors",
146
+ "blocks.18.attn.k_norm.weight": "model-00002-of-00005.safetensors",
147
+ "blocks.18.attn.k_proj.weight": "model-00002-of-00005.safetensors",
148
+ "blocks.18.attn.o_proj.weight": "model-00002-of-00005.safetensors",
149
+ "blocks.18.attn.q_norm.weight": "model-00002-of-00005.safetensors",
150
+ "blocks.18.attn.q_proj.weight": "model-00002-of-00005.safetensors",
151
+ "blocks.18.attn.v_norm_layer.weight": "model-00002-of-00005.safetensors",
152
+ "blocks.18.attn.v_proj.weight": "model-00002-of-00005.safetensors",
153
+ "blocks.18.attn_out_norm.weight": "model-00002-of-00005.safetensors",
154
+ "blocks.18.input_norm.weight": "model-00002-of-00005.safetensors",
155
+ "blocks.18.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
156
+ "blocks.18.mlp.gate_proj.weight": "model-00002-of-00005.safetensors",
157
+ "blocks.18.mlp.up_proj.weight": "model-00002-of-00005.safetensors",
158
+ "blocks.18.mlp_out_norm.weight": "model-00002-of-00005.safetensors",
159
+ "blocks.18.post_norm.weight": "model-00002-of-00005.safetensors",
160
+ "blocks.19.attn.k_norm.weight": "model-00002-of-00005.safetensors",
161
+ "blocks.19.attn.k_proj.weight": "model-00002-of-00005.safetensors",
162
+ "blocks.19.attn.o_proj.weight": "model-00002-of-00005.safetensors",
163
+ "blocks.19.attn.q_norm.weight": "model-00002-of-00005.safetensors",
164
+ "blocks.19.attn.q_proj.weight": "model-00002-of-00005.safetensors",
165
+ "blocks.19.attn.v_norm_layer.weight": "model-00002-of-00005.safetensors",
166
+ "blocks.19.attn.v_proj.weight": "model-00002-of-00005.safetensors",
167
+ "blocks.19.attn_out_norm.weight": "model-00002-of-00005.safetensors",
168
+ "blocks.19.input_norm.weight": "model-00002-of-00005.safetensors",
169
+ "blocks.19.mlp.down_proj.weight": "model-00002-of-00005.safetensors",
170
+ "blocks.19.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
171
+ "blocks.19.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
172
+ "blocks.19.mlp_out_norm.weight": "model-00003-of-00005.safetensors",
173
+ "blocks.19.post_norm.weight": "model-00003-of-00005.safetensors",
174
+ "blocks.2.attn.k_norm.weight": "model-00003-of-00005.safetensors",
175
+ "blocks.2.attn.k_proj.weight": "model-00003-of-00005.safetensors",
176
+ "blocks.2.attn.o_proj.weight": "model-00003-of-00005.safetensors",
177
+ "blocks.2.attn.q_norm.weight": "model-00003-of-00005.safetensors",
178
+ "blocks.2.attn.q_proj.weight": "model-00003-of-00005.safetensors",
179
+ "blocks.2.attn.v_norm_layer.weight": "model-00003-of-00005.safetensors",
180
+ "blocks.2.attn.v_proj.weight": "model-00003-of-00005.safetensors",
181
+ "blocks.2.attn_out_norm.weight": "model-00003-of-00005.safetensors",
182
+ "blocks.2.input_norm.weight": "model-00003-of-00005.safetensors",
183
+ "blocks.2.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
184
+ "blocks.2.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
185
+ "blocks.2.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
186
+ "blocks.2.mlp_out_norm.weight": "model-00003-of-00005.safetensors",
187
+ "blocks.2.post_norm.weight": "model-00003-of-00005.safetensors",
188
+ "blocks.20.attn.k_norm.weight": "model-00003-of-00005.safetensors",
189
+ "blocks.20.attn.k_proj.weight": "model-00003-of-00005.safetensors",
190
+ "blocks.20.attn.o_proj.weight": "model-00003-of-00005.safetensors",
191
+ "blocks.20.attn.q_norm.weight": "model-00003-of-00005.safetensors",
192
+ "blocks.20.attn.q_proj.weight": "model-00003-of-00005.safetensors",
193
+ "blocks.20.attn.v_norm_layer.weight": "model-00003-of-00005.safetensors",
194
+ "blocks.20.attn.v_proj.weight": "model-00003-of-00005.safetensors",
195
+ "blocks.20.attn_out_norm.weight": "model-00003-of-00005.safetensors",
196
+ "blocks.20.input_norm.weight": "model-00003-of-00005.safetensors",
197
+ "blocks.20.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
198
+ "blocks.20.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
199
+ "blocks.20.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
200
+ "blocks.20.mlp_out_norm.weight": "model-00003-of-00005.safetensors",
201
+ "blocks.20.post_norm.weight": "model-00003-of-00005.safetensors",
202
+ "blocks.21.attn.k_norm.weight": "model-00003-of-00005.safetensors",
203
+ "blocks.21.attn.k_proj.weight": "model-00003-of-00005.safetensors",
204
+ "blocks.21.attn.o_proj.weight": "model-00003-of-00005.safetensors",
205
+ "blocks.21.attn.q_norm.weight": "model-00003-of-00005.safetensors",
206
+ "blocks.21.attn.q_proj.weight": "model-00003-of-00005.safetensors",
207
+ "blocks.21.attn.v_norm_layer.weight": "model-00003-of-00005.safetensors",
208
+ "blocks.21.attn.v_proj.weight": "model-00003-of-00005.safetensors",
209
+ "blocks.21.attn_out_norm.weight": "model-00003-of-00005.safetensors",
210
+ "blocks.21.input_norm.weight": "model-00003-of-00005.safetensors",
211
+ "blocks.21.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
212
+ "blocks.21.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
213
+ "blocks.21.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
214
+ "blocks.21.mlp_out_norm.weight": "model-00003-of-00005.safetensors",
215
+ "blocks.21.post_norm.weight": "model-00003-of-00005.safetensors",
216
+ "blocks.22.attn.k_norm.weight": "model-00003-of-00005.safetensors",
217
+ "blocks.22.attn.k_proj.weight": "model-00003-of-00005.safetensors",
218
+ "blocks.22.attn.o_proj.weight": "model-00003-of-00005.safetensors",
219
+ "blocks.22.attn.q_norm.weight": "model-00003-of-00005.safetensors",
220
+ "blocks.22.attn.q_proj.weight": "model-00003-of-00005.safetensors",
221
+ "blocks.22.attn.v_norm_layer.weight": "model-00003-of-00005.safetensors",
222
+ "blocks.22.attn.v_proj.weight": "model-00003-of-00005.safetensors",
223
+ "blocks.22.attn_out_norm.weight": "model-00003-of-00005.safetensors",
224
+ "blocks.22.input_norm.weight": "model-00003-of-00005.safetensors",
225
+ "blocks.22.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
226
+ "blocks.22.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
227
+ "blocks.22.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
228
+ "blocks.22.mlp_out_norm.weight": "model-00003-of-00005.safetensors",
229
+ "blocks.22.post_norm.weight": "model-00003-of-00005.safetensors",
230
+ "blocks.23.attn.k_norm.weight": "model-00003-of-00005.safetensors",
231
+ "blocks.23.attn.k_proj.weight": "model-00003-of-00005.safetensors",
232
+ "blocks.23.attn.o_proj.weight": "model-00003-of-00005.safetensors",
233
+ "blocks.23.attn.q_norm.weight": "model-00003-of-00005.safetensors",
234
+ "blocks.23.attn.q_proj.weight": "model-00003-of-00005.safetensors",
235
+ "blocks.23.attn.v_norm_layer.weight": "model-00003-of-00005.safetensors",
236
+ "blocks.23.attn.v_proj.weight": "model-00003-of-00005.safetensors",
237
+ "blocks.23.attn_out_norm.weight": "model-00003-of-00005.safetensors",
238
+ "blocks.23.input_norm.weight": "model-00003-of-00005.safetensors",
239
+ "blocks.23.mlp.down_proj.weight": "model-00003-of-00005.safetensors",
240
+ "blocks.23.mlp.gate_proj.weight": "model-00003-of-00005.safetensors",
241
+ "blocks.23.mlp.up_proj.weight": "model-00003-of-00005.safetensors",
242
+ "blocks.23.mlp_out_norm.weight": "model-00003-of-00005.safetensors",
243
+ "blocks.23.post_norm.weight": "model-00003-of-00005.safetensors",
244
+ "blocks.3.attn.k_norm.weight": "model-00003-of-00005.safetensors",
245
+ "blocks.3.attn.k_proj.weight": "model-00003-of-00005.safetensors",
246
+ "blocks.3.attn.o_proj.weight": "model-00003-of-00005.safetensors",
247
+ "blocks.3.attn.q_norm.weight": "model-00003-of-00005.safetensors",
248
+ "blocks.3.attn.q_proj.weight": "model-00003-of-00005.safetensors",
249
+ "blocks.3.attn.v_norm_layer.weight": "model-00003-of-00005.safetensors",
250
+ "blocks.3.attn.v_proj.weight": "model-00003-of-00005.safetensors",
251
+ "blocks.3.attn_out_norm.weight": "model-00003-of-00005.safetensors",
252
+ "blocks.3.input_norm.weight": "model-00003-of-00005.safetensors",
253
+ "blocks.3.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
254
+ "blocks.3.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
255
+ "blocks.3.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
256
+ "blocks.3.mlp_out_norm.weight": "model-00004-of-00005.safetensors",
257
+ "blocks.3.post_norm.weight": "model-00004-of-00005.safetensors",
258
+ "blocks.4.attn.k_norm.weight": "model-00004-of-00005.safetensors",
259
+ "blocks.4.attn.k_proj.weight": "model-00004-of-00005.safetensors",
260
+ "blocks.4.attn.o_proj.weight": "model-00004-of-00005.safetensors",
261
+ "blocks.4.attn.q_norm.weight": "model-00004-of-00005.safetensors",
262
+ "blocks.4.attn.q_proj.weight": "model-00004-of-00005.safetensors",
263
+ "blocks.4.attn.v_norm_layer.weight": "model-00004-of-00005.safetensors",
264
+ "blocks.4.attn.v_proj.weight": "model-00004-of-00005.safetensors",
265
+ "blocks.4.attn_out_norm.weight": "model-00004-of-00005.safetensors",
266
+ "blocks.4.input_norm.weight": "model-00004-of-00005.safetensors",
267
+ "blocks.4.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
268
+ "blocks.4.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
269
+ "blocks.4.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
270
+ "blocks.4.mlp_out_norm.weight": "model-00004-of-00005.safetensors",
271
+ "blocks.4.post_norm.weight": "model-00004-of-00005.safetensors",
272
+ "blocks.5.attn.k_norm.weight": "model-00004-of-00005.safetensors",
273
+ "blocks.5.attn.k_proj.weight": "model-00004-of-00005.safetensors",
274
+ "blocks.5.attn.o_proj.weight": "model-00004-of-00005.safetensors",
275
+ "blocks.5.attn.q_norm.weight": "model-00004-of-00005.safetensors",
276
+ "blocks.5.attn.q_proj.weight": "model-00004-of-00005.safetensors",
277
+ "blocks.5.attn.v_norm_layer.weight": "model-00004-of-00005.safetensors",
278
+ "blocks.5.attn.v_proj.weight": "model-00004-of-00005.safetensors",
279
+ "blocks.5.attn_out_norm.weight": "model-00004-of-00005.safetensors",
280
+ "blocks.5.input_norm.weight": "model-00004-of-00005.safetensors",
281
+ "blocks.5.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
282
+ "blocks.5.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
283
+ "blocks.5.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
284
+ "blocks.5.mlp_out_norm.weight": "model-00004-of-00005.safetensors",
285
+ "blocks.5.post_norm.weight": "model-00004-of-00005.safetensors",
286
+ "blocks.6.attn.k_norm.weight": "model-00004-of-00005.safetensors",
287
+ "blocks.6.attn.k_proj.weight": "model-00004-of-00005.safetensors",
288
+ "blocks.6.attn.o_proj.weight": "model-00004-of-00005.safetensors",
289
+ "blocks.6.attn.q_norm.weight": "model-00004-of-00005.safetensors",
290
+ "blocks.6.attn.q_proj.weight": "model-00004-of-00005.safetensors",
291
+ "blocks.6.attn.v_norm_layer.weight": "model-00004-of-00005.safetensors",
292
+ "blocks.6.attn.v_proj.weight": "model-00004-of-00005.safetensors",
293
+ "blocks.6.attn_out_norm.weight": "model-00004-of-00005.safetensors",
294
+ "blocks.6.input_norm.weight": "model-00004-of-00005.safetensors",
295
+ "blocks.6.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
296
+ "blocks.6.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
297
+ "blocks.6.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
298
+ "blocks.6.mlp_out_norm.weight": "model-00004-of-00005.safetensors",
299
+ "blocks.6.post_norm.weight": "model-00004-of-00005.safetensors",
300
+ "blocks.7.attn.k_norm.weight": "model-00004-of-00005.safetensors",
301
+ "blocks.7.attn.k_proj.weight": "model-00004-of-00005.safetensors",
302
+ "blocks.7.attn.o_proj.weight": "model-00004-of-00005.safetensors",
303
+ "blocks.7.attn.q_norm.weight": "model-00004-of-00005.safetensors",
304
+ "blocks.7.attn.q_proj.weight": "model-00004-of-00005.safetensors",
305
+ "blocks.7.attn.v_norm_layer.weight": "model-00004-of-00005.safetensors",
306
+ "blocks.7.attn.v_proj.weight": "model-00004-of-00005.safetensors",
307
+ "blocks.7.attn_out_norm.weight": "model-00004-of-00005.safetensors",
308
+ "blocks.7.input_norm.weight": "model-00004-of-00005.safetensors",
309
+ "blocks.7.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
310
+ "blocks.7.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
311
+ "blocks.7.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
312
+ "blocks.7.mlp_out_norm.weight": "model-00004-of-00005.safetensors",
313
+ "blocks.7.post_norm.weight": "model-00004-of-00005.safetensors",
314
+ "blocks.8.attn.k_norm.weight": "model-00004-of-00005.safetensors",
315
+ "blocks.8.attn.k_proj.weight": "model-00004-of-00005.safetensors",
316
+ "blocks.8.attn.o_proj.weight": "model-00004-of-00005.safetensors",
317
+ "blocks.8.attn.q_norm.weight": "model-00004-of-00005.safetensors",
318
+ "blocks.8.attn.q_proj.weight": "model-00004-of-00005.safetensors",
319
+ "blocks.8.attn.v_norm_layer.weight": "model-00004-of-00005.safetensors",
320
+ "blocks.8.attn.v_proj.weight": "model-00004-of-00005.safetensors",
321
+ "blocks.8.attn_out_norm.weight": "model-00004-of-00005.safetensors",
322
+ "blocks.8.input_norm.weight": "model-00004-of-00005.safetensors",
323
+ "blocks.8.mlp.down_proj.weight": "model-00004-of-00005.safetensors",
324
+ "blocks.8.mlp.gate_proj.weight": "model-00004-of-00005.safetensors",
325
+ "blocks.8.mlp.up_proj.weight": "model-00004-of-00005.safetensors",
326
+ "blocks.8.mlp_out_norm.weight": "model-00004-of-00005.safetensors",
327
+ "blocks.8.post_norm.weight": "model-00004-of-00005.safetensors",
328
+ "blocks.9.attn.k_norm.weight": "model-00004-of-00005.safetensors",
329
+ "blocks.9.attn.k_proj.weight": "model-00004-of-00005.safetensors",
330
+ "blocks.9.attn.o_proj.weight": "model-00004-of-00005.safetensors",
331
+ "blocks.9.attn.q_norm.weight": "model-00004-of-00005.safetensors",
332
+ "blocks.9.attn.q_proj.weight": "model-00005-of-00005.safetensors",
333
+ "blocks.9.attn.v_norm_layer.weight": "model-00005-of-00005.safetensors",
334
+ "blocks.9.attn.v_proj.weight": "model-00005-of-00005.safetensors",
335
+ "blocks.9.attn_out_norm.weight": "model-00005-of-00005.safetensors",
336
+ "blocks.9.input_norm.weight": "model-00005-of-00005.safetensors",
337
+ "blocks.9.mlp.down_proj.weight": "model-00005-of-00005.safetensors",
338
+ "blocks.9.mlp.gate_proj.weight": "model-00005-of-00005.safetensors",
339
+ "blocks.9.mlp.up_proj.weight": "model-00005-of-00005.safetensors",
340
+ "blocks.9.mlp_out_norm.weight": "model-00005-of-00005.safetensors",
341
+ "blocks.9.post_norm.weight": "model-00005-of-00005.safetensors",
342
+ "embed_tokens.weight": "model-00005-of-00005.safetensors",
343
+ "norm.weight": "model-00005-of-00005.safetensors"
344
+ }
345
+ }
plots/loss_plot.png ADDED

Git LFS Details

  • SHA256: 7559123ebb1b29d0638ce98a1090d5d35aa0bf34a08c297a63a5e38454177a1c
  • Pointer size: 131 Bytes
  • Size of remote file: 174 kB
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506
3
+ size 11422650
tokenizer_config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|endoftext|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": [
9
+ "<|im_start|>",
10
+ "<|im_end|>",
11
+ "<|object_ref_start|>",
12
+ "<|object_ref_end|>",
13
+ "<|box_start|>",
14
+ "<|box_end|>",
15
+ "<|quad_start|>",
16
+ "<|quad_end|>",
17
+ "<|vision_start|>",
18
+ "<|vision_end|>",
19
+ "<|vision_pad|>",
20
+ "<|image_pad|>",
21
+ "<|video_pad|>"
22
+ ],
23
+ "is_local": true,
24
+ "local_files_only": false,
25
+ "model_max_length": 131072,
26
+ "pad_token": "<|endoftext|>",
27
+ "split_special_tokens": false,
28
+ "tokenizer_class": "Qwen2Tokenizer",
29
+ "unk_token": null
30
+ }