kerzgrr commited on
Commit
08b963f
·
verified ·
1 Parent(s): 3ec5c38

Upload Senryu-2.1-1B (EMA weights)

Browse files
README.md ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - text-generation
7
+ - causal-lm
8
+ - pytorch
9
+ - sft
10
+ - instruction-tuned
11
+ - chat
12
+ - reasoning
13
+ - tool-use
14
+ - system-prompt
15
+ - hybrid
16
+ - gated-deltanet-2
17
+ - parallax-attention
18
+ - n-gram-memory
19
+ - engram
20
+ - senryu
21
+ - senryu-2
22
+ - senryu-2.1
23
+ pipeline_tag: text-generation
24
+ library_name: tiny_gdn
25
+ base_model: KerzgrAI/Senryu-2-1B
26
+ base_model_relation: finetune
27
+ datasets:
28
+ - HuggingFaceTB/smoltalk2
29
+ - HuggingFaceTB/smoltalk
30
+ - nvidia/Nemotron-Cascade-2-SFT-Data
31
+ - nvidia/Nemotron-Post-Training-Dataset-v1
32
+ - nvidia/Nemotron-Agentic-v1
33
+ - nvidia/Nemotron-SFT-Agentic-v2
34
+ - nvidia/Nemotron-SFT-Agentic-v4
35
+ - nvidia/Nemotron-SFT-Instruction-Following-Chat-v2
36
+ - nvidia/Nemotron-Instruction-Following-Chat-v1
37
+ - nvidia/OpenMathReasoning
38
+ - nvidia/OpenCodeReasoning
39
+ - nvidia/When2Call
40
+ - Agent-Ark/Toucan-1.5M
41
+ - interstellarninja/hermes_reasoning_tool_use
42
+ - interstellarninja/tool-use-multiturn-reasoning
43
+ - NousResearch/Hermes-3-Dataset
44
+ - glaiveai/glaive-function-calling-v2
45
+ - allenai/WildChat-4.8M
46
+ - OpenLeecher/lmsys_chat_1m_clean
47
+ - oumi-ai/lmsys_chat_1m_clean_R1
48
+ - lmarena-ai/arena-human-preference-140k
49
+ - kaist-ai/Multifaceted-Collection
50
+ - QuixiAI/SystemChat-2.0
51
+ - ZeroAgency/QuixiAI-SystemChat-2.0-filtered
52
+ - abacusai/SystemChat-1.1
53
+ - normster/SystemCheck
54
+ - EricLu/System-Prompt-Instruction-Real-world-Implementation-Training-set
55
+ - Open-Orca/SlimOrca
56
+ - HuggingFaceH4/ultrachat_200k
57
+ - ise-uiuc/Magicoder-Evol-Instruct-110K
58
+ - bigcode/self-oss-instruct-sc2-exec-filter-50k
59
+ - OpenAssistant/oasst2
60
+ - allenai/tulu-3-sft-personas-instruction-following
61
+ - HuggingFaceH4/no_robots
62
+ - mrfakename/identity
63
+ - modelscope/self-cognition
64
+ ---
65
+
66
+ <div align="center">
67
+
68
+ # Senryu-2.1-1B
69
+
70
+ ### Hybrid Gated DeltaNet-2 + Parallax chat model (1.09B) with 2.17B parameters of n-gram memory
71
+
72
+ [![Model](https://img.shields.io/badge/Model-1.09B_core_params-blue)](.)
73
+ [![Memory](https://img.shields.io/badge/N--gram_memory-2.17B_params-blue)](.)
74
+ [![License](https://img.shields.io/badge/License-Apache_2.0-green.svg)](https://www.apache.org/licenses/LICENSE-2.0)
75
+ [![Demo](https://img.shields.io/badge/Demo-ZeroGPU_Space-orange.svg)](https://huggingface.co/spaces/KerzgrAI/senryu-2.1-1b-demo)
76
+
77
+ *By [KerzgrAI](https://huggingface.co/KerzgrAI): [Senryu-2-1B](https://huggingface.co/KerzgrAI/Senryu-2-1B) trained on 2.06B more tokens, ending on a mix that is half new distillation from Ling 3.1 Flash at maximum reasoning*
78
+
79
+ </div>
80
+
81
+ ---
82
+
83
+ ## What's new in 2.1
84
+
85
+ **Senryu-2.1-1B** is the second model on the Senryu-2 architecture. It continues [Senryu-2-1B](https://huggingface.co/KerzgrAI/Senryu-2-1B) with the same architecture, tokenizer and chat template, so it is a drop-in replacement.
86
+
87
+ - **Improved reasoning.** Its last 827M training tokens are half new distillation from Ling 3.1 Flash at maximum reasoning effort, with the full reasoning trace in each turn's `<think>` block.
88
+ - **Much better system prompt following.** 119,137 of those conversations were answered under their own system prompts (personas, output formats, rules and constraints from Multifaceted-Collection, SystemChat 2.0 and SystemChat 1.1), and the earlier steps added system-prompt datasets such as SystemCheck.
89
+ - **A default system prompt and default tools.** 36,929 conversations trained it under one Senryu system prompt with three tools, `web-search`, `fetch-page` and `calculator`, and rules to call them only when needed. `inference.py` and the [demo](https://huggingface.co/spaces/KerzgrAI/senryu-2.1-1b-demo) start every chat with both.
90
+
91
+ ---
92
+
93
+ ## Default system prompt
94
+
95
+ Conversations without a system prompt of their own were trained under this one, dated the day they were written. `inference.py` and the demo fill in today's date in the same format, such as `Monday, October 26, 2026`:
96
+
97
+ ```text
98
+ You are Senryu-2.1, a large language model from KerzgrAI. Today's date is {Weekday, Month D, YYYY}.
99
+
100
+ Tool Rules:
101
+ - Answer from your own knowledge whenever you can. Most requests need no tools.
102
+ - **Use web search sparingly, only when it is absolutely necessary:** for news and events after your training, live data such as prices, scores or weather, or a precise fact the user needs and you don't know. Never search for things you can answer yourself, such as explanations, definitions, how-tos, code, math, writing or advice, and never search just to double-check what you already know.
103
+ - When you must search, use one focused query and answer from its results. Search again only if they leave the question unanswered.
104
+ - Fetch a page only when the user links one or a search result you need is cut short.
105
+ - Use the calculator for arithmetic you can't reliably do in your head.
106
+
107
+ Formatting Rules:
108
+ - Use Markdown for lists, tables, and styling.
109
+ - Use ```code fences``` for all code blocks.
110
+ - Format file names, paths, and function names with `inline code` backticks.
111
+ - **For all mathematical expressions, you must use dollar-sign delimiters. Use $...$ for inline math and $$...$$ for block math. Do not use \(...\) or \[...\] delimiters.**
112
+ - For responses with many sections where some are more important than others, use collapsible sections (HTML details/summary tags) to highlight key information while allowing users to expand less critical details.
113
+ ```
114
+
115
+ In Python, `tiny_gdn.senryu_chat.senryu_system_prompt()` returns it dated today. Your own system prompt works too, since most of the new conversations were answered under their own; pass `--system ""` or clear the demo's box to chat without any.
116
+
117
+ ---
118
+
119
+ ## Default tools
120
+
121
+ Every conversation under the default prompt offered these three tools, in this order. The model called them sparingly: about 4% of those conversations call a tool at all.
122
+
123
+ | Tool | Arguments | Result, as trained |
124
+ |------|-----------|--------------------|
125
+ | `web-search` | `query` (string, required) | Tavily search JSON: `query`, `answer`, and `results` with each hit's `url`, `title` and `content` |
126
+ | `fetch-page` | `url` (string, required), `offset` (integer) | `URL:` and `Title:` lines, then the page or PDF as Markdown, 12,000 characters at a time, ending with the `offset` to read on |
127
+ | `calculator` | `expression` (string, required) | The value, for example `452093301` |
128
+
129
+ The schemas, one per line as the system turn carries them:
130
+
131
+ ```text
132
+ {"type": "function", "function": {"name": "web-search", "description": "Search the web for a query.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "Search query."}}, "required": ["query"]}}}
133
+ {"type": "function", "function": {"name": "fetch-page", "description": "Fetch a web page or PDF by URL and return its readable text as Markdown.", "parameters": {"type": "object", "properties": {"url": {"type": "string", "description": "The http or https URL to fetch."}, "offset": {"type": "integer", "description": "Character offset to start reading from, for pages longer than one result."}}, "required": ["url"]}}}
134
+ {"type": "function", "function": {"name": "calculator", "description": "Evaluate a math expression and return the result.", "parameters": {"type": "object", "properties": {"expression": {"type": "string", "description": "A math expression in standard calculator notation, for example (3 + 4)^2 * sqrt(2) / ln(10). Use + - * / ^ (power), % (remainder), ! (factorial) and parentheses; the constants pi and e; and functions such as sqrt, cbrt, exp, ln, log (natural, or log(x, base)), log10, log2, sin, cos, tan, asin, acos, atan (radians), abs, round, floor, ceil, factorial, comb, perm, gcd, lcm, min, max, sum, mean and median."}}, "required": ["expression"]}}}
135
+ ```
136
+
137
+ They are `tiny_gdn.senryu_chat.SENRYU_TOOLS`. Other Hermes-style tools work the same way: list them in the `<tools>` block (`--tools-json` in the CLI), and run each call yourself.
138
+
139
+ ---
140
+
141
+ ## Prompt format
142
+
143
+ A tool round exactly as training laid it out, and as `tiny_gdn.chatml.encode_chatml_messages` builds it (the system prompt is shortened here):
144
+
145
+ ```text
146
+ <|begin_of_text|><|im_start|>system
147
+ You are Senryu-2.1, a large language model from KerzgrAI. Today's date is Monday, October 26, 2026.
148
+
149
+ Tool Rules:
150
+ …
151
+ - For responses with many sections where some are more important than others, use collapsible sections (HTML details/summary tags) to highlight key information while allowing users to expand less critical details.
152
+
153
+ You may call one or more functions to assist with the user query.
154
+ You are provided with function signatures within <tools></tools> XML tags:
155
+ <tools>
156
+ {"type": "function", "function": {"name": "web-search", …}}
157
+ {"type": "function", "function": {"name": "fetch-page", …}}
158
+ {"type": "function", "function": {"name": "calculator", …}}
159
+ </tools>
160
+
161
+ For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
162
+ <tool_call>
163
+ {"name": <function-name>, "arguments": <args-json-object>}
164
+ </tool_call><|im_end|>
165
+ <|im_start|>user
166
+ What is 48213 * 9377?<|im_end|>
167
+ <|im_start|>assistant
168
+ <|think|>
169
+ <think>
170
+ That's a five-digit product; the calculator is safer than mental arithmetic.
171
+ </think>
172
+
173
+ <tool_call>
174
+ {"name": "calculator", "arguments": {"expression": "48213 * 9377"}}
175
+ </tool_call><|im_end|>
176
+ <|im_start|>user
177
+ <|tool_response|>
178
+ 452093301<|im_end|>
179
+ <|im_start|>assistant
180
+ <|think|>
181
+ ```
182
+
183
+ - **Thinking.** Each assistant turn starts with a control token: `<|think|>\n`, then a `<think>…</think>` block and the answer, or `<|no_think|>\n` and the answer only.
184
+ - **Tools.** The `<tools>` block follows the system prompt after a blank line. With no tools, the system turn is the prompt alone.
185
+ - **Calls.** The model writes any text first, then one `<tool_call>` block per call, each a JSON object with `name` and `arguments`. Independent calls share one turn.
186
+ - **Results.** All results of a turn go back in one `user` turn, in call order, each starting with `<|tool_response|>\n` and separated by a newline. The model then answers in a new assistant turn, or calls again. With `tiny_gdn`, send each result as a `{"role": "tool", "content": …}` message and the encoder lays them out this way.
187
+
188
+ ---
189
+
190
+ ## Install & run
191
+
192
+ ```bash
193
+ pip install torch safetensors tokenizers huggingface_hub
194
+ hf download KerzgrAI/Senryu-2.1-1B inference.py --local-dir .
195
+ python inference.py
196
+ ```
197
+
198
+ ```bash
199
+ python inference.py --prompt "Explain recursion in two sentences."
200
+ python inference.py --prompt "What's in the news about fusion power this week?"
201
+ python inference.py --tools none --system ""
202
+ python inference.py --no-think --prompt "Reply in one sentence."
203
+ python inference.py --ngram-device cpu
204
+ ```
205
+
206
+ `inference.py` downloads the weights, n-gram tables, tokenizer and `tiny_gdn/`, installs `flash-linear-attention` from git at the pinned commit (so Git must be on `PATH`) and installs the page readers `fetch-page` needs. A CUDA GPU is required: Gated DeltaNet-2 and Parallax run on Triton kernels.
207
+
208
+ The three default tools run automatically. `web-search` uses [Tavily](https://tavily.com) when `TAVILY_API_KEY` is set, and DuckDuckGo with Wikipedia otherwise, in the same JSON shape. `fetch-page` reads public `http`/`https` pages and PDFs only.
209
+
210
+ | Flag | Default | Description |
211
+ |------|---------|-------------|
212
+ | `--prompt` | — | One-shot user message |
213
+ | `--system` | the Senryu-2.1 prompt, dated today | System prompt, used verbatim; `""` for none |
214
+ | `--think` / `--no-think` | think | Assistant control prefix |
215
+ | `--tools` | `web-search,fetch-page,calculator` | Built-ins, comma-separated: `web-search`, `fetch-page`, `calculator`, `python`; `none` for no tools |
216
+ | `--tools-json` | — | Extra tool schemas (JSON list) for the `<tools>` block |
217
+ | `--max-tool-rounds` | `8` | Tool rounds per reply |
218
+ | `--temperature` | `0.6` | Sampling temperature (0.3 suits tool-calling turns) |
219
+ | `--top-p` | `0.95` | Nucleus sampling |
220
+ | `--top-k` | `50` | Top-k sampling |
221
+ | `--repetition-penalty` | `1.08` | On content tokens seen twice in the last `--repetition-window` (256) tokens |
222
+ | `--dry-multiplier` | `0.8` | DRY penalty on verbatim loops and re-pasted replies; `0` disables |
223
+ | `--dry-base` | `1.75` | How fast the DRY penalty grows per repeated token |
224
+ | `--dry-allowed-length` | `2` | Tokens a phrase may repeat before DRY starts |
225
+ | `--max-new-tokens` | `4096` | Max generation length |
226
+ | `--context-length` | `32768` | Conversation tokens kept (oldest dropped first) |
227
+ | `--device` | `cuda` | CUDA device, e.g. `cuda:1` |
228
+ | `--ngram-device` | same as `--device` | Where the n-gram tables live; `cpu` saves 4.3 GB of VRAM |
229
+
230
+ Sampling matches the KerzgrAI API: the repetition penalty leaves Markdown and punctuation alone, and DRY breaks verbatim loops but stays off inside code fences and tool calls.
231
+
232
+ Interactive commands: `/think` `/no_think` `/system …` `/reset` `/exit`. Ctrl+C stops the current reply.
233
+
234
+ ---
235
+
236
+ ## Model architecture
237
+
238
+ | | |
239
+ |--|--|
240
+ | **Core parameters** | 1,094,961,660 (embeddings included) |
241
+ | **N-gram memory** | 2,166,398,464 table parameters: 2- and 3-gram hashes, four hash heads per order |
242
+ | **Layers** | 28: 7 × (3 Gated DeltaNet-2 + 1 Parallax attention) |
243
+ | **Hidden** | 1,536 |
244
+ | **MLP** | SiTU-GLU 3,584 |
245
+ | **Attention** | Parallax: 12 query and 4 KV heads of 128, RoPE on half of each head (θ = 10⁶) |
246
+ | **Linear** | Gated DeltaNet-2, 12 heads × 128, with a short convolution |
247
+ | **Residuals** | Four-branch gated residual stream (rank-128 gate) |
248
+ | **Memory read** | Before block 1, with a context-aware gate per residual branch, as in Engram |
249
+ | **Vocab** | 65,536 BPE, tied embeddings |
250
+ | **Context** | 32,768 |
251
+
252
+ ---
253
+
254
+ ## Training
255
+
256
+ Continued from Senryu-2-1B's final SFT checkpoint (EMA weights) for 3,920 steps of 16 sequences × 32,768 tokens: 2.06B tokens, 1.41B of them assistant targets, in about 50 hours on one RTX PRO 6000 Blackwell GPU. Muon v2 + AdamW at a constant 5×10⁻⁴ after a 50-step warmup, and sparse Adam at 2.5×10⁻³ for the n-gram tables.
257
+
258
+ 1. **Steps 1–2,230:** Senryu-2-1B's SFT mixture, refreshed with more system-prompt, chat and agentic data.
259
+ 2. **Steps 2,230–3,920:** half new distillation, half replay of that mixture. The final mix, 289,976 conversations and 826.6M tokens, was trained once through:
260
+
261
+ | Part | Conversations | Tokens | What it is |
262
+ |------|--------------:|-------:|------------|
263
+ | System prompts | 119,137 | 225.0M | Ling 3.1 Flash at maximum reasoning answers Multifaceted-Collection, SystemChat 2.0 and SystemChat 1.1 openings under their own system prompts |
264
+ | Default prompt and tools | 36,929 | 188.3M | Ling 3.1 Flash at maximum reasoning answers smol-magpie-ultra openings as Senryu-2.1, under the default system prompt with the three default tools; Claude Haiku 5.5 writes a follow-up user turn a quarter of the time |
265
+ | Replay | 133,910 | 413.3M | The refreshed SFT mixture from steps 1–2,230, filtered of other models' self-descriptions |
266
+
267
+ Only assistant turns are trained. The released EMA weights reach a loss of 1.433 on the final mix's held-out split, against 1.498 for the raw weights. `sft_config.json` holds the run's settings.
268
+
269
+ ---
270
+
271
+ ## Files
272
+
273
+ | File | Contents |
274
+ |------|----------|
275
+ | `model.safetensors` | Core weights (EMA), bfloat16 |
276
+ | `ngram_tables.safetensors` | N-gram tables (bfloat16), canonical ids and hash multipliers |
277
+ | `config.json` | Architecture |
278
+ | `tokenizer.json`, `special_token_ids.json` | Tokenizer and control-token ids |
279
+ | `inference.py`, `requirements.txt`, `tiny_gdn/` | Standalone chat CLI and the model code it imports |
280
+ | `sft_config.json` | Training settings |
281
+ | `windows_fla_patches/` | Import patches `inference.py` applies to fla on Windows |
282
+
283
+ ---
284
+
285
+ ## Limitations
286
+
287
+ - **Scale.** 1.09B core parameters and no pretraining stage: expect thin world knowledge, factual errors and invented details.
288
+ - **Page fetches.** Only 0.3% of the default-prompt training conversations call `fetch-page`, and in our tests the model answered questions about a linked page from memory, inventing its contents, instead of fetching it. Paste the text in when a page matters.
289
+ - **Search.** Results depend on the backend, and the model can misread or over-trust what it retrieves. Check anything that matters.
290
+ - **Language.** Training data is mostly English.
291
+ - **Hardware.** A CUDA GPU is required.
292
+
293
+ Weights are Apache-2.0. Each training dataset keeps its own license; some carry attribution or non-commercial terms, so check them before commercial use.
294
+
295
+ ---
296
+
297
+ ## Model family
298
+
299
+ | Model | Notes | Hub |
300
+ |-------|-------|-----|
301
+ | **Senryu-2.1-1B** | **Senryu-2 architecture: better reasoning and system prompt following, default prompt and tools** | **this repo** |
302
+ | Senryu-2-1B | First Senryu-2 model | [`KerzgrAI/Senryu-2-1B`](https://huggingface.co/KerzgrAI/Senryu-2-1B) |
303
+ | Senryu | Previous generation (803M) | [`kerzgrr/Senryu`](https://huggingface.co/kerzgrr/Senryu) |
304
+ | Haiku | Earlier generation (~655M) | [`kerzgrr/Haiku`](https://huggingface.co/kerzgrr/Haiku) |
305
+
306
+ ---
307
+
308
+ ## References
309
+
310
+ - Gated DeltaNet-2: <https://arxiv.org/abs/2605.22791>
311
+ - Parallax attention: <https://arxiv.org/abs/2605.29157>
312
+ - Engram conditional memory: <https://arxiv.org/abs/2601.07372>
313
+ - flash-linear-attention, pinned at [`cbb0a72`](https://github.com/fla-org/flash-linear-attention/tree/cbb0a72efb55c18ca0ef4f298298317573ad2cb3)
314
+
315
+ ```bibtex
316
+ @misc{senryu2_1_1b_2026,
317
+ title={Senryu-2.1-1B: A 1.1B Hybrid Gated DeltaNet-2 + Parallax Chat Model with Hashed N-gram Memory},
318
+ author={KerzgrAI},
319
+ year={2026},
320
+ url={https://huggingface.co/KerzgrAI/Senryu-2.1-1B}
321
+ }
322
+ ```
chat_template.jinja ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set ns = namespace(xml_tools=none, tools_emitted=false) -%}
2
+ {%- if xml_tools is defined and xml_tools -%}
3
+ {%- set ns.xml_tools = xml_tools -%}
4
+ {%- elif tools is defined and tools -%}
5
+ {%- set ns.xml_tools = tools -%}
6
+ {%- endif -%}
7
+ {%- set tools_preamble = 'You may call one or more functions to assist with the user query.\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>\n' -%}
8
+ {%- set tools_epilogue = '</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>' -%}
9
+ {%- for message in messages -%}
10
+ {%- if loop.first -%}{{- bos_token -}}{%- endif -%}
11
+ {%- if loop.first and ns.xml_tools and message['role'] != 'system' -%}
12
+ {{- '<|im_start|>system\n' + tools_preamble -}}
13
+ {%- for tool in ns.xml_tools -%}
14
+ {%- if tool is string -%}{{- (tool | replace('<tools>', '') | replace('</tools>', '') | trim) + '\n' -}}
15
+ {%- else -%}{{- tool | tojson + '\n' -}}
16
+ {%- endif -%}
17
+ {%- endfor -%}
18
+ {{- tools_epilogue + '<|im_end|>\n' -}}
19
+ {%- set ns.tools_emitted = true -%}
20
+ {%- endif -%}
21
+ {%- set raw_role = message['role'] -%}
22
+ {%- set role = 'user' if raw_role == 'tool' or raw_role == 'function' else raw_role -%}
23
+ {%- set content_text = namespace(value='') -%}
24
+ {%- if message['content'] is string -%}
25
+ {%- set content_text.value = message['content'] -%}
26
+ {%- elif message['content'] is iterable -%}
27
+ {%- for item in message['content'] -%}
28
+ {%- if item['type'] == 'text' -%}{%- set content_text.value = content_text.value + item['text'] -%}{%- endif -%}
29
+ {%- endfor -%}
30
+ {%- endif -%}
31
+ {%- set is_tool = raw_role == 'tool' or raw_role == 'function' -%}
32
+ {%- set prev_is_tool = loop.previtem is defined and (loop.previtem['role'] == 'tool' or loop.previtem['role'] == 'function') -%}
33
+ {%- set next_is_tool = loop.nextitem is defined and (loop.nextitem['role'] == 'tool' or loop.nextitem['role'] == 'function') -%}
34
+ {%- if raw_role == 'system' and not (content_text.value | trim) and not (ns.xml_tools and not ns.tools_emitted) -%}
35
+ {%- else -%}
36
+ {%- if is_tool and prev_is_tool -%}
37
+ {{- '\n' -}}
38
+ {%- else -%}
39
+ {{- '<|im_start|>' + role + '\n' -}}
40
+ {%- endif -%}
41
+ {%- if raw_role == 'assistant' and enable_thinking is defined -%}
42
+ {{- ('<|think|>\n' if enable_thinking else '<|no_think|>\n') -}}
43
+ {%- endif -%}
44
+ {%- if is_tool -%}
45
+ {{- '<|tool_response|>\n' + (content_text.value | replace('<tool_response>', '') | replace('</tool_response>', '') | trim) -}}
46
+ {%- elif raw_role == 'system' -%}
47
+ {{- content_text.value | replace('/system_override', '') | replace('/no_think', '') | replace('/think', '') | trim -}}
48
+ {%- else -%}
49
+ {{- content_text.value -}}
50
+ {%- endif -%}
51
+ {%- if raw_role == 'system' and ns.xml_tools and not ns.tools_emitted and '<tools>' not in content_text.value -%}
52
+ {%- if content_text.value | trim -%}{{- '\n\n' -}}{%- endif -%}
53
+ {{- tools_preamble -}}
54
+ {%- for tool in ns.xml_tools -%}
55
+ {%- if tool is string -%}{{- (tool | replace('<tools>', '') | replace('</tools>', '') | trim) + '\n' -}}
56
+ {%- else -%}{{- tool | tojson + '\n' -}}
57
+ {%- endif -%}
58
+ {%- endfor -%}
59
+ {{- tools_epilogue -}}
60
+ {%- set ns.tools_emitted = true -%}
61
+ {%- endif -%}
62
+ {%- if raw_role == 'assistant' and message['tool_calls'] is defined and message['tool_calls'] -%}
63
+ {%- if '<tool_call>' not in content_text.value -%}
64
+ {%- for tool_call in message['tool_calls'] -%}
65
+ {%- set fn = tool_call['function'] if tool_call['function'] is defined else tool_call -%}
66
+ {%- if loop.first and not (content_text.value | trim) -%}
67
+ {{- '<tool_call>\n{"name": "' + fn['name'] + '", "arguments": ' -}}
68
+ {%- else -%}
69
+ {{- '\n<tool_call>\n{"name": "' + fn['name'] + '", "arguments": ' -}}
70
+ {%- endif -%}
71
+ {%- if fn['arguments'] is string -%}{{- fn['arguments'] -}}
72
+ {%- else -%}{{- fn['arguments'] | tojson -}}
73
+ {%- endif -%}
74
+ {{- '}\n</tool_call>' -}}
75
+ {%- endfor -%}
76
+ {%- endif -%}
77
+ {%- endif -%}
78
+ {%- if not (is_tool and next_is_tool) -%}
79
+ {{- '<|im_end|>\n' -}}
80
+ {%- endif -%}
81
+ {%- endif -%}
82
+ {%- endfor -%}
83
+ {%- if add_generation_prompt -%}
84
+ {{- '<|im_start|>assistant\n' -}}
85
+ {%- if enable_thinking is defined -%}{{- ('<|think|>\n' if enable_thinking else '<|no_think|>\n') -}}{%- endif -%}
86
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "allow_negative_eigenvalues": false,
3
+ "architecture": "Senryu2ForCausalLM",
4
+ "attention_dropout": 0.0,
5
+ "attention_head_dim": 128,
6
+ "attention_layer_type": "parallax",
7
+ "bos_token_id": 0,
8
+ "eos_token_id": 1,
9
+ "full_attention_interval": 4,
10
+ "hidden_size": 1536,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 3584,
13
+ "kda_lower_bound": -5.0,
14
+ "kda_safe_gate": true,
15
+ "layer_types": [
16
+ "gdn2",
17
+ "gdn2",
18
+ "gdn2",
19
+ "parallax",
20
+ "gdn2",
21
+ "gdn2",
22
+ "gdn2",
23
+ "parallax",
24
+ "gdn2",
25
+ "gdn2",
26
+ "gdn2",
27
+ "parallax",
28
+ "gdn2",
29
+ "gdn2",
30
+ "gdn2",
31
+ "parallax",
32
+ "gdn2",
33
+ "gdn2",
34
+ "gdn2",
35
+ "parallax",
36
+ "gdn2",
37
+ "gdn2",
38
+ "gdn2",
39
+ "parallax",
40
+ "gdn2",
41
+ "gdn2",
42
+ "gdn2",
43
+ "parallax"
44
+ ],
45
+ "linear_conv_kernel_dim": 4,
46
+ "linear_expand_v": 1.0,
47
+ "linear_full_rank_gate": true,
48
+ "linear_head_dim": 128,
49
+ "linear_layer_type": "gdn2",
50
+ "linear_num_heads": 12,
51
+ "linear_num_value_heads": 12,
52
+ "max_position_embeddings": 32768,
53
+ "mla_kv_lora_rank": 256,
54
+ "mla_q_lora_rank": 512,
55
+ "mla_qk_nope_head_dim": 128,
56
+ "mla_v_head_dim": 128,
57
+ "mlp_activation": "situ_glu",
58
+ "model_type": "senryu2",
59
+ "mtp_adapter_rank": 128,
60
+ "mtp_loss_weight": 0.0,
61
+ "mtp_num_heads": 0,
62
+ "ngram_conv_kernel": 4,
63
+ "ngram_embedding_dim": 128,
64
+ "ngram_heads_per_order": 4,
65
+ "ngram_layer_index": 1,
66
+ "ngram_orders": [
67
+ 2,
68
+ 3
69
+ ],
70
+ "ngram_table_rows": 2097152,
71
+ "num_attention_heads": 12,
72
+ "num_hidden_layers": 28,
73
+ "num_key_value_heads": 4,
74
+ "pad_token_id": 2,
75
+ "partial_rotary_factor": 0.5,
76
+ "residual_branches": 4,
77
+ "residual_gate_rank": 128,
78
+ "residual_mode": "gated_residual",
79
+ "rms_norm_eps": 1e-06,
80
+ "rope_theta": 1000000.0,
81
+ "shared_layer_indices": [],
82
+ "situ_gate_cap": 4.0,
83
+ "situ_up_cap": 25.0,
84
+ "tie_word_embeddings": true,
85
+ "training_sequence_length": 32768,
86
+ "unk_token_id": 3,
87
+ "use_block_attn_res": false,
88
+ "vocab_size": 65536,
89
+ "architectures": [
90
+ "Senryu2ForCausalLM"
91
+ ],
92
+ "torch_dtype": "bfloat16",
93
+ "model_name": "Senryu-2.1-1B",
94
+ "model_family": "Senryu-2",
95
+ "developer": "KerzgrAI",
96
+ "weights": "ema",
97
+ "core_parameters": 1094961660,
98
+ "ngram_table_parameters": 2166398464,
99
+ "chat_template": "smollm3",
100
+ "reasoning": true,
101
+ "tool_calls": "hermes_json"
102
+ }
inference.py ADDED
@@ -0,0 +1,723 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Standalone chat inference for KerzgrAI/Senryu-2.1-1B.
3
+
4
+ Streams a live reasoning trace (`<think>` / `<|think|>`) and runs Hermes JSON
5
+ tool-call rounds. By default the chat starts the way Senryu-2.1 trained: its
6
+ Senryu system prompt, dated today, and the `web-search`, `fetch-page` and
7
+ `calculator` tools, which run automatically like the built-in `python` tool.
8
+ Other observations are pasted back and sent as `<|tool_response|>`.
9
+
10
+ Examples:
11
+ python inference.py --prompt "Explain recursion in two sentences."
12
+ python inference.py --tools none --system "" # no tools, no system prompt
13
+ python inference.py --tools web-search,fetch-page,calculator,python
14
+ python inference.py --no-think --prompt "Reply in one sentence."
15
+ python inference.py --ngram-device cpu # keep the 4.3 GB n-gram tables in host RAM
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import importlib
22
+ import importlib.util
23
+ import json
24
+ import os
25
+ import platform
26
+ import shutil
27
+ import subprocess
28
+ import sys
29
+ import time
30
+ import warnings
31
+ from pathlib import Path
32
+ from types import SimpleNamespace
33
+ from typing import Any
34
+
35
+ import torch
36
+ from huggingface_hub import hf_hub_download
37
+ from safetensors.torch import load_file
38
+ from tokenizers import Tokenizer
39
+
40
+
41
+ def _silence_runtime_warnings() -> None:
42
+ patterns = (
43
+ r"tl\.make_block_ptr is deprecated",
44
+ r"Memory efficient kernel not used because",
45
+ r"Memory Efficient attention has been runtime disabled",
46
+ r"Flash attention kernel not used because",
47
+ r"Torch was not compiled with flash attention",
48
+ r"cuDNN attention kernel not used because",
49
+ r"cuDNN attention has been runtime disabled",
50
+ )
51
+ for pattern in patterns:
52
+ warnings.filterwarnings("ignore", message=pattern)
53
+
54
+
55
+ REPO_ID = "KerzgrAI/Senryu-2.1-1B"
56
+ MODEL_NAME = "Senryu-2.1-1B"
57
+ # The name the model knows itself by in its trained system prompt.
58
+ PROMPT_NAME = "Senryu-2.1"
59
+ # fetch-page's HTML and PDF readers, by import name.
60
+ TOOL_PACKAGES = {
61
+ "trafilatura": "trafilatura>=2.0",
62
+ "bs4": "beautifulsoup4>=4.12",
63
+ "pypdf": "pypdf>=5.0",
64
+ "urllib3": "urllib3>=2.0",
65
+ }
66
+ FLA_COMMIT = "cbb0a72efb55c18ca0ef4f298298317573ad2cb3"
67
+ FLA_REPO = "https://github.com/fla-org/flash-linear-attention.git"
68
+ FLA_RUNTIME_REQUIREMENT = "transformers>=4.45.0"
69
+ # Parallax attention is not in a flash-linear-attention release yet, so fla
70
+ # installs from git at the commit the model was trained with.
71
+ FLA_MODULES = (
72
+ "fla.layers.gdn2",
73
+ "fla.models.utils",
74
+ "fla.modules.rotary",
75
+ "fla.ops.parallax.parallel",
76
+ "fla.ops.parallax.decode",
77
+ )
78
+ PATCH_FILES = (
79
+ "fla/__init__.py",
80
+ "fla/ops/__init__.py",
81
+ "fla/layers/__init__.py",
82
+ "fla/ops/simple_gla/__init__.py",
83
+ )
84
+ TINY_GDN_FILES = (
85
+ "tiny_gdn/__init__.py",
86
+ "tiny_gdn/config.py",
87
+ "tiny_gdn/model.py",
88
+ "tiny_gdn/haiku_layers.py",
89
+ "tiny_gdn/nn_common.py",
90
+ "tiny_gdn/fused_ops.py",
91
+ "tiny_gdn/senryu2.py",
92
+ "tiny_gdn/parallax_ops.py",
93
+ "tiny_gdn/gated_residual_ops.py",
94
+ "tiny_gdn/ngram.py",
95
+ "tiny_gdn/tools.py",
96
+ "tiny_gdn/smoltalk_chat.py",
97
+ "tiny_gdn/chatml.py",
98
+ "tiny_gdn/cli_chat.py",
99
+ "tiny_gdn/detokenize.py",
100
+ "tiny_gdn/repetition.py",
101
+ "tiny_gdn/code_exec.py",
102
+ "tiny_gdn/paths.py",
103
+ "tiny_gdn/token_file.py",
104
+ "tiny_gdn/web_search.py",
105
+ "tiny_gdn/web_fetch.py",
106
+ "tiny_gdn/senryu_chat.py",
107
+ )
108
+ NGRAM_TABLES_FILE = "ngram_tables.safetensors"
109
+
110
+
111
+ def _download(filename: str, local_dir: Path | None) -> Path:
112
+ return Path(
113
+ hf_hub_download(
114
+ repo_id=REPO_ID,
115
+ filename=filename,
116
+ local_dir=str(local_dir) if local_dir else None,
117
+ )
118
+ )
119
+
120
+
121
+ def _run(cmd: list[str], *, cwd: Path | None = None, env: dict | None = None) -> None:
122
+ print("+", " ".join(cmd), flush=True)
123
+ merged = os.environ.copy()
124
+ if env:
125
+ merged.update(env)
126
+ merged.setdefault("PYTHONUTF8", "1")
127
+ merged.setdefault("PYTHONIOENCODING", "utf-8")
128
+ subprocess.check_call(cmd, cwd=str(cwd) if cwd else None, env=merged)
129
+
130
+
131
+ def _pip_install(*args: str) -> None:
132
+ _run([sys.executable, "-m", "pip", "install", *args])
133
+
134
+
135
+ def _fla_importable() -> tuple[bool, str]:
136
+ try:
137
+ for name in FLA_MODULES:
138
+ importlib.import_module(name)
139
+ except Exception as error: # noqa: BLE001
140
+ return False, str(error)
141
+ return True, ""
142
+
143
+
144
+ def _cache_root() -> Path:
145
+ override = os.environ.get("SENRYU_CACHE")
146
+ if override:
147
+ path = Path(override).expanduser().resolve()
148
+ else:
149
+ path = Path.home() / ".cache" / "senryu"
150
+ path.mkdir(parents=True, exist_ok=True)
151
+ return path
152
+
153
+
154
+ def _ensure_git() -> None:
155
+ if shutil.which("git") is None:
156
+ raise RuntimeError(
157
+ "git is required to auto-install flash-linear-attention. "
158
+ "Install Git and ensure it is on PATH."
159
+ )
160
+
161
+
162
+ def _apply_windows_fla_patches(fla_root: Path, local_dir: Path | None) -> None:
163
+ print("Applying Windows FLA import patches from the Hub …", flush=True)
164
+ for relative in PATCH_FILES:
165
+ source = _download(f"windows_fla_patches/{relative}", local_dir)
166
+ target = fla_root / relative
167
+ target.parent.mkdir(parents=True, exist_ok=True)
168
+ shutil.copy2(source, target)
169
+ print(f" patched {relative}", flush=True)
170
+
171
+
172
+ def _install_fla(local_dir: Path | None) -> None:
173
+ print("flash-linear-attention missing/broken — installing automatically …", flush=True)
174
+ _pip_install("einops", "numpy", FLA_RUNTIME_REQUIREMENT)
175
+ if platform.system() != "Windows":
176
+ _pip_install("--no-deps", "--force-reinstall", f"git+{FLA_REPO}@{FLA_COMMIT}")
177
+ return
178
+
179
+ _ensure_git()
180
+ fla_root = _cache_root() / "flash-linear-attention"
181
+ if (fla_root / ".git").is_dir():
182
+ _run(["git", "fetch", "--depth", "1", "origin", FLA_COMMIT], cwd=fla_root)
183
+ _run(["git", "checkout", "--force", FLA_COMMIT], cwd=fla_root)
184
+ else:
185
+ if fla_root.exists():
186
+ shutil.rmtree(fla_root)
187
+ _run(["git", "clone", "--filter=blob:none", FLA_REPO, str(fla_root)])
188
+ _run(["git", "fetch", "--depth", "1", "origin", FLA_COMMIT], cwd=fla_root)
189
+ _run(["git", "checkout", "--force", FLA_COMMIT], cwd=fla_root)
190
+
191
+ _apply_windows_fla_patches(fla_root, local_dir)
192
+ _pip_install("--no-build-isolation", "--no-deps", "-e", str(fla_root))
193
+
194
+
195
+ def _ensure_fla(local_dir: Path | None) -> None:
196
+ ok, error = _fla_importable()
197
+ if ok:
198
+ return
199
+ print(f"FLA not ready ({error})", flush=True)
200
+ try:
201
+ _install_fla(local_dir)
202
+ except Exception as install_error: # noqa: BLE001
203
+ raise RuntimeError(
204
+ "Automatic flash-linear-attention install failed.\n"
205
+ f"Original import error: {error}\n"
206
+ f"Install error: {install_error}"
207
+ ) from install_error
208
+
209
+ for name in list(sys.modules):
210
+ if name == "fla" or name.startswith("fla."):
211
+ del sys.modules[name]
212
+ importlib.invalidate_caches()
213
+
214
+ ok, error = _fla_importable()
215
+ if not ok:
216
+ raise RuntimeError(
217
+ "flash-linear-attention installed but still failed to import "
218
+ f"Gated DeltaNet-2, Parallax attention and the decode cache: {error}"
219
+ )
220
+ print("flash-linear-attention ready.", flush=True)
221
+
222
+
223
+ def _ensure_tool_packages() -> None:
224
+ missing = [
225
+ requirement
226
+ for module, requirement in TOOL_PACKAGES.items()
227
+ if importlib.util.find_spec(module) is None
228
+ ]
229
+ if not missing:
230
+ return
231
+ print("Installing the fetch-page readers …", flush=True)
232
+ _pip_install(*missing)
233
+ importlib.invalidate_caches()
234
+
235
+
236
+ def _has_tiny_gdn(root: Path) -> bool:
237
+ return all((root / name).is_file() for name in TINY_GDN_FILES)
238
+
239
+
240
+ def _ensure_tiny_gdn(local_dir: Path | None) -> Path:
241
+ here = Path(__file__).resolve().parent
242
+ if _has_tiny_gdn(here):
243
+ return here
244
+ if local_dir and _has_tiny_gdn(local_dir):
245
+ return local_dir
246
+ for name in TINY_GDN_FILES:
247
+ _download(name, local_dir)
248
+ return _download("tiny_gdn/__init__.py", local_dir).parent.parent
249
+
250
+
251
+ def _import_chat_stack() -> SimpleNamespace:
252
+ # tiny_gdn is fetched from the Hub and FLA may be installed at runtime, so
253
+ # these modules only become importable after _ensure_tiny_gdn/_ensure_fla.
254
+ config = importlib.import_module("tiny_gdn.config")
255
+ senryu2 = importlib.import_module("tiny_gdn.senryu2")
256
+ chatml = importlib.import_module("tiny_gdn.chatml")
257
+ cli_chat = importlib.import_module("tiny_gdn.cli_chat")
258
+ detokenize = importlib.import_module("tiny_gdn.detokenize")
259
+ repetition = importlib.import_module("tiny_gdn.repetition")
260
+ tools = importlib.import_module("tiny_gdn.tools")
261
+ senryu_chat = importlib.import_module("tiny_gdn.senryu_chat")
262
+ return SimpleNamespace(
263
+ TinyGDNConfig=config.TinyGDNConfig,
264
+ Senryu2ForCausalLM=senryu2.Senryu2ForCausalLM,
265
+ encode_chatml_messages=chatml.encode_chatml_messages,
266
+ ChatLoopState=cli_chat.ChatLoopState,
267
+ LiveReasoningStreamer=cli_chat.LiveReasoningStreamer,
268
+ append_tool_round=cli_chat.append_tool_round,
269
+ apply_slash_command=cli_chat.apply_slash_command,
270
+ prompt_tool_results=cli_chat.prompt_tool_results,
271
+ resolve_cli_tools=cli_chat.resolve_cli_tools,
272
+ IncrementalUtf8Decoder=detokenize.IncrementalUtf8Decoder,
273
+ apply_repetition_penalty=repetition.apply_repetition_penalty,
274
+ apply_dry_penalty=repetition.apply_dry_penalty,
275
+ cached_structural_token_flags=repetition.cached_structural_token_flags,
276
+ cached_dry_vocabulary=repetition.cached_dry_vocabulary,
277
+ parse_tool_calls=tools.parse_tool_calls,
278
+ senryu_system_prompt=senryu_chat.senryu_system_prompt,
279
+ SENRYU_TOOL_SPEC=senryu_chat.SENRYU_TOOL_SPEC,
280
+ )
281
+
282
+
283
+ def _sample(
284
+ logits: torch.Tensor,
285
+ *,
286
+ temperature: float,
287
+ top_p: float,
288
+ top_k: int,
289
+ generator: torch.Generator,
290
+ ) -> int:
291
+ logits = logits.float()
292
+ if temperature <= 1e-5:
293
+ return int(torch.argmax(logits).item())
294
+ logits = logits / temperature
295
+ if 0 < top_k < logits.shape[-1]:
296
+ threshold = torch.topk(logits, top_k).values[-1]
297
+ logits = logits.masked_fill(logits < threshold, -torch.inf)
298
+ if top_p < 1.0:
299
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
300
+ probs = torch.softmax(sorted_logits, dim=-1)
301
+ remove = torch.cumsum(probs, dim=-1) > top_p
302
+ remove[1:] = remove[:-1].clone()
303
+ remove[0] = False
304
+ sorted_logits = sorted_logits.masked_fill(remove, -torch.inf)
305
+ logits = torch.full_like(logits, -torch.inf)
306
+ logits.scatter_(0, sorted_indices, sorted_logits)
307
+ probs = torch.softmax(logits, dim=-1).cpu()
308
+ return int(torch.multinomial(probs, 1, generator=generator).item())
309
+
310
+
311
+ def _penalize_repeats(
312
+ logits: torch.Tensor,
313
+ token_ids: list[int],
314
+ stack: SimpleNamespace,
315
+ tokenizer: Tokenizer,
316
+ *,
317
+ repetition_penalty: float,
318
+ repetition_window: int,
319
+ dry_multiplier: float,
320
+ dry_base: float,
321
+ dry_allowed_length: int,
322
+ ) -> torch.Tensor:
323
+ """The KerzgrAI API's repetition control: a Markdown-safe penalty, then DRY."""
324
+
325
+ logits = logits.float()
326
+ if repetition_penalty != 1.0:
327
+ stack.apply_repetition_penalty(
328
+ logits,
329
+ token_ids,
330
+ penalty=repetition_penalty,
331
+ window=repetition_window,
332
+ structural=stack.cached_structural_token_flags(tokenizer),
333
+ )
334
+ if dry_multiplier != 0:
335
+ stack.apply_dry_penalty(
336
+ logits,
337
+ token_ids,
338
+ multiplier=dry_multiplier,
339
+ base=dry_base,
340
+ allowed_length=dry_allowed_length,
341
+ window=0,
342
+ vocabulary=stack.cached_dry_vocabulary(tokenizer),
343
+ )
344
+ return logits
345
+
346
+
347
+ @torch.inference_mode()
348
+ def generate_turn(
349
+ model,
350
+ tokenizer: Tokenizer,
351
+ stack: SimpleNamespace,
352
+ streamer,
353
+ messages: list[dict[str, Any]],
354
+ *,
355
+ tools: Any | None,
356
+ enable_thinking: bool,
357
+ max_new_tokens: int,
358
+ context_length: int,
359
+ temperature: float,
360
+ top_p: float,
361
+ top_k: int,
362
+ repetition_penalty: float,
363
+ repetition_window: int,
364
+ dry_multiplier: float,
365
+ dry_base: float,
366
+ dry_allowed_length: int,
367
+ seed: int,
368
+ device: torch.device,
369
+ ) -> tuple[str, tuple]:
370
+ prompt_ids = stack.encode_chatml_messages(
371
+ tokenizer,
372
+ messages,
373
+ tools=tools,
374
+ enable_thinking=enable_thinking,
375
+ )
376
+ if len(prompt_ids) > context_length:
377
+ print(
378
+ f"[warn] conversation is {len(prompt_ids)} tokens; "
379
+ f"keeping the last {context_length} (--context-length)",
380
+ file=sys.stderr,
381
+ flush=True,
382
+ )
383
+ eos_id = int(model.config.eos_token_id)
384
+ im_end = tokenizer.token_to_id("<|im_end|>")
385
+ stop = {eos_id}
386
+ if im_end is not None:
387
+ stop.add(im_end)
388
+
389
+ token_ids = list(prompt_ids[-context_length:])
390
+ generated: list[int] = []
391
+ decoder = stack.IncrementalUtf8Decoder(tokenizer)
392
+ stop_reason = "max_new_tokens"
393
+ generator = torch.Generator(device="cpu")
394
+ generator.manual_seed(seed)
395
+ started = time.perf_counter()
396
+
397
+ try:
398
+ input_ids = torch.tensor([token_ids], dtype=torch.long, device=device)
399
+ output = model(
400
+ input_ids,
401
+ return_logits=True,
402
+ logits_to_keep=1,
403
+ use_cache=True,
404
+ )
405
+
406
+ for step in range(max_new_tokens):
407
+ if output.logits is None:
408
+ raise RuntimeError("Model returned no logits")
409
+ next_logits = _penalize_repeats(
410
+ output.logits[0, -1],
411
+ token_ids,
412
+ stack,
413
+ tokenizer,
414
+ repetition_penalty=repetition_penalty,
415
+ repetition_window=repetition_window,
416
+ dry_multiplier=dry_multiplier,
417
+ dry_base=dry_base,
418
+ dry_allowed_length=dry_allowed_length,
419
+ )
420
+ next_id = _sample(
421
+ next_logits,
422
+ temperature=temperature,
423
+ top_p=top_p,
424
+ top_k=top_k,
425
+ generator=generator,
426
+ )
427
+ if next_id in stop:
428
+ stop_reason = "stop"
429
+ break
430
+ token_ids.append(next_id)
431
+ generated.append(next_id)
432
+ decoder.push(next_id)
433
+ if streamer is not None:
434
+ streamer.update(decoder.text)
435
+ if step + 1 < max_new_tokens:
436
+ if output.past_key_values is None:
437
+ raise RuntimeError("Model returned no decode cache")
438
+ if output.past_key_values.length + 1 > model.config.max_position_embeddings:
439
+ stop_reason = "context_full"
440
+ break
441
+ input_ids = torch.tensor([[next_id]], dtype=torch.long, device=device)
442
+ output = model(
443
+ input_ids,
444
+ return_logits=True,
445
+ logits_to_keep=1,
446
+ past_key_values=output.past_key_values,
447
+ use_cache=True,
448
+ )
449
+ except KeyboardInterrupt:
450
+ stop_reason = "interrupted"
451
+
452
+ decoded = decoder.finalize()
453
+ if streamer is not None:
454
+ streamer.finish()
455
+ elapsed = time.perf_counter() - started
456
+ tps = len(generated) / max(elapsed, 1e-9)
457
+ print(
458
+ f"[done] tokens={len(generated)} stop={stop_reason} {tps:.1f} tok/s",
459
+ file=sys.stderr,
460
+ flush=True,
461
+ )
462
+ if stop_reason == "interrupted":
463
+ return decoded, ()
464
+ return decoded, tuple(stack.parse_tool_calls(decoded))
465
+
466
+
467
+ def parse_args() -> argparse.Namespace:
468
+ parser = argparse.ArgumentParser(description=f"{MODEL_NAME} chat inference")
469
+ parser.add_argument("--prompt", default=None, help="Single user prompt")
470
+ parser.add_argument(
471
+ "--system",
472
+ default=None,
473
+ help=f"System prompt (default: the {PROMPT_NAME} prompt the model trained with, dated today; '' for none)",
474
+ )
475
+ parser.add_argument(
476
+ "--think",
477
+ dest="enable_thinking",
478
+ action="store_true",
479
+ default=True,
480
+ )
481
+ parser.add_argument(
482
+ "--no-think",
483
+ dest="enable_thinking",
484
+ action="store_false",
485
+ )
486
+ parser.add_argument(
487
+ "--tools",
488
+ default=None,
489
+ help=(
490
+ "Built-in tools, comma-separated: web-search, fetch-page, calculator, python "
491
+ "(default: web-search,fetch-page,calculator, the tools the model trained with; none for no tools)"
492
+ ),
493
+ )
494
+ parser.add_argument("--tools-json", default=None)
495
+ parser.add_argument("--max-tool-rounds", type=int, default=8)
496
+ parser.add_argument("--max-new-tokens", type=int, default=4096)
497
+ parser.add_argument("--temperature", type=float, default=0.6)
498
+ parser.add_argument("--top-p", type=float, default=0.95)
499
+ parser.add_argument("--top-k", type=int, default=50)
500
+ parser.add_argument("--repetition-penalty", type=float, default=1.08)
501
+ parser.add_argument("--repetition-window", type=int, default=256)
502
+ parser.add_argument(
503
+ "--dry-multiplier",
504
+ type=float,
505
+ default=0.8,
506
+ help="DRY penalty on verbatim loops and re-pasted replies (default 0.8; 0 disables)",
507
+ )
508
+ parser.add_argument(
509
+ "--dry-base",
510
+ type=float,
511
+ default=1.75,
512
+ help="How fast the DRY penalty grows per repeated token (default 1.75)",
513
+ )
514
+ parser.add_argument(
515
+ "--dry-allowed-length",
516
+ type=int,
517
+ default=2,
518
+ help="Tokens a phrase may repeat before DRY starts (default 2)",
519
+ )
520
+ parser.add_argument("--context-length", type=int, default=32768)
521
+ parser.add_argument("--seed", type=int, default=42)
522
+ parser.add_argument(
523
+ "--device",
524
+ default="cuda",
525
+ help=f"CUDA device (cuda, cuda:1, …); {MODEL_NAME} needs a GPU",
526
+ )
527
+ parser.add_argument(
528
+ "--ngram-device",
529
+ default=None,
530
+ help="Where the n-gram tables live: the GPU (default, --device) or cpu (host RAM, slower decode)",
531
+ )
532
+ parser.add_argument("--no-stream", action="store_true")
533
+ parser.add_argument("--no-color", action="store_true")
534
+ parser.add_argument("--local-dir", default=None)
535
+ parser.add_argument("--repo-id", default=REPO_ID)
536
+ return parser.parse_args()
537
+
538
+
539
+ def main() -> int:
540
+ _silence_runtime_warnings()
541
+ args = parse_args()
542
+ global REPO_ID
543
+ REPO_ID = args.repo_id
544
+ local_dir = Path(args.local_dir).resolve() if args.local_dir else None
545
+
546
+ try:
547
+ device = torch.device(args.device)
548
+ ngram_device = torch.device(args.ngram_device) if args.ngram_device else device
549
+ except RuntimeError as error:
550
+ print(f"Invalid device: {error}", file=sys.stderr)
551
+ return 1
552
+ if device.type != "cuda" or not torch.cuda.is_available():
553
+ print(
554
+ f"{MODEL_NAME} needs a CUDA GPU: its Gated DeltaNet-2 and Parallax "
555
+ "layers run on flash-linear-attention Triton kernels. "
556
+ f"torch {torch.__version__} reports CUDA available={torch.cuda.is_available()}.",
557
+ file=sys.stderr,
558
+ )
559
+ return 1
560
+ if ngram_device.type not in {"cuda", "cpu"}:
561
+ print("--ngram-device must be a CUDA device or cpu", file=sys.stderr)
562
+ return 1
563
+
564
+ print(f"Loading {MODEL_NAME} from huggingface.co/{REPO_ID} …", flush=True)
565
+ try:
566
+ package_root = _ensure_tiny_gdn(local_dir)
567
+ except Exception as error: # noqa: BLE001
568
+ print(f"Failed to resolve tiny_gdn package: {error}", file=sys.stderr)
569
+ return 1
570
+
571
+ if str(package_root) not in sys.path:
572
+ sys.path.insert(0, str(package_root))
573
+
574
+ try:
575
+ _ensure_fla(local_dir)
576
+ _ensure_tool_packages()
577
+ except Exception as error: # noqa: BLE001
578
+ print(str(error), file=sys.stderr)
579
+ return 1
580
+
581
+ try:
582
+ stack = _import_chat_stack()
583
+ except ImportError as error:
584
+ print(f"Could not import tiny_gdn chat stack: {error}", file=sys.stderr)
585
+ return 1
586
+
587
+ try:
588
+ raw_json = (
589
+ Path(args.tools_json).read_text(encoding="utf-8")
590
+ if args.tools_json
591
+ else None
592
+ )
593
+ tools = stack.resolve_cli_tools(
594
+ stack.SENRYU_TOOL_SPEC if args.tools is None else args.tools,
595
+ raw_json,
596
+ )
597
+ except (OSError, ValueError, json.JSONDecodeError) as error:
598
+ print(error, file=sys.stderr)
599
+ return 1
600
+
601
+ weights_path = _download("model.safetensors", local_dir)
602
+ tables_path = _download(NGRAM_TABLES_FILE, local_dir)
603
+ tok_path = _download("tokenizer.json", local_dir)
604
+ cfg_path = _download("config.json", local_dir)
605
+
606
+ config = stack.TinyGDNConfig.from_json(cfg_path)
607
+ print(
608
+ f"Building {MODEL_NAME} ({config.num_hidden_layers}L / {config.hidden_size}d) "
609
+ f"on {device}, n-gram tables on {ngram_device} …",
610
+ flush=True,
611
+ )
612
+ with torch.device(device):
613
+ model = stack.Senryu2ForCausalLM(config)
614
+ model = model.to(dtype=torch.bfloat16)
615
+ model.load_state_dict(load_file(str(weights_path), device=str(device)), strict=True)
616
+ if model.ngram is not None:
617
+ model.ngram.load_tables(tables_path, device=ngram_device, dtype=torch.bfloat16)
618
+ model.eval()
619
+ model.requires_grad_(False)
620
+
621
+ tokenizer = Tokenizer.from_file(str(tok_path))
622
+ context_length = min(args.context_length, config.max_position_embeddings)
623
+ color = not args.no_color and sys.stdout.isatty()
624
+
625
+ def read_line(prompt: str) -> str:
626
+ return input(prompt)
627
+
628
+ def run_turn(state) -> None:
629
+ for round_index in range(max(1, args.max_tool_rounds + 1)):
630
+ streamer = (
631
+ None
632
+ if args.no_stream
633
+ else stack.LiveReasoningStreamer(sys.stdout, color=color)
634
+ )
635
+ if streamer is not None:
636
+ print("assistant> ", end="", flush=True)
637
+ text, calls = generate_turn(
638
+ model,
639
+ tokenizer,
640
+ stack,
641
+ streamer,
642
+ state.messages,
643
+ tools=state.tools,
644
+ enable_thinking=state.enable_thinking,
645
+ max_new_tokens=args.max_new_tokens,
646
+ context_length=context_length,
647
+ temperature=args.temperature,
648
+ top_p=args.top_p,
649
+ top_k=args.top_k,
650
+ repetition_penalty=args.repetition_penalty,
651
+ repetition_window=args.repetition_window,
652
+ dry_multiplier=args.dry_multiplier,
653
+ dry_base=args.dry_base,
654
+ dry_allowed_length=args.dry_allowed_length,
655
+ seed=args.seed,
656
+ device=device,
657
+ )
658
+ if args.no_stream:
659
+ print(f"assistant> {text}")
660
+ if not calls or round_index >= args.max_tool_rounds:
661
+ state.messages.append({"role": "assistant", "content": text})
662
+ return
663
+ results = stack.prompt_tool_results(calls, read_line=read_line)
664
+ stack.append_tool_round(state.messages, text, results)
665
+
666
+ system = stack.senryu_system_prompt(PROMPT_NAME) if args.system is None else args.system
667
+ state = stack.ChatLoopState(
668
+ system=system,
669
+ enable_thinking=args.enable_thinking,
670
+ tools=tools,
671
+ )
672
+ state.reset()
673
+
674
+ if args.prompt is not None:
675
+ state.add_user(args.prompt)
676
+ try:
677
+ run_turn(state)
678
+ except KeyboardInterrupt:
679
+ print("\n(interrupted)", file=sys.stderr)
680
+ return 130
681
+ return 0
682
+
683
+ tool_names = ", ".join(tool["function"]["name"] for tool in tools or []) or "none"
684
+ system_label = (
685
+ f"the {PROMPT_NAME} default, dated today"
686
+ if args.system is None
687
+ else ("none" if not system.strip() else "custom")
688
+ )
689
+ print(
690
+ f"Interactive {MODEL_NAME} chat. "
691
+ "Commands: /think /no_think /system … /reset /exit\n"
692
+ f"System prompt: {system_label}. Tools: {tool_names}.\n"
693
+ "web-search, fetch-page, calculator and python run automatically when enabled. "
694
+ "Other <tool_call> observations can be pasted at the prompt. "
695
+ "Ctrl+C stops a reply.",
696
+ flush=True,
697
+ )
698
+ while True:
699
+ try:
700
+ user_input = input("user> ")
701
+ except (EOFError, KeyboardInterrupt):
702
+ print()
703
+ return 0
704
+ text = user_input.strip()
705
+ if not text:
706
+ continue
707
+ status = stack.apply_slash_command(state, text)
708
+ if status == "exit":
709
+ return 0
710
+ if status is not None:
711
+ print(f"({status})", flush=True)
712
+ continue
713
+ state.add_user(text)
714
+ try:
715
+ run_turn(state)
716
+ except KeyboardInterrupt:
717
+ print("\n(interrupted)", flush=True)
718
+ print(flush=True)
719
+ return 0
720
+
721
+
722
+ if __name__ == "__main__":
723
+ raise SystemExit(main())
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04a4c91acdd1238f517b836c233a47b504c5b82a44e62e7817528626e924a664
3
+ size 2190000672
ngram_tables.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:45f22cd07bfafd4f4f52f20f2f05d34bd8b172ea989ceba1559abbcc6d0ba64b
3
+ size 4333321792
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.7.0
2
+ triton>=3.3
3
+ safetensors>=0.4.0
4
+ tokenizers>=0.20.0
5
+ huggingface_hub>=0.26.0
6
+ transformers>=4.45.0
7
+ einops>=0.8.0
8
+ numpy>=1.26.0
9
+ sympy>=1.13.0
10
+ trafilatura>=2.0
11
+ beautifulsoup4>=4.12
12
+ pypdf>=5.0
13
+ urllib3>=2.0
14
+
15
+ # flash-linear-attention (commit cbb0a72, which has Parallax attention) is
16
+ # auto-installed by inference.py on first run, as are the fetch-page readers
17
+ # (trafilatura, beautifulsoup4, pypdf, urllib3) when they are missing.
sft_config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adam_beta1": 0.9,
3
+ "adam_beta2": 0.95,
4
+ "adam_epsilon": 1e-08,
5
+ "continue_on_new_dataset": true,
6
+ "cpu_prefetch_factor": 2,
7
+ "cpu_workers": 2,
8
+ "dataset_manifest": "/media/nvidia/4TB2/haiku/tokenized/senryu-2.1-ling-mix-v3/manifest.json",
9
+ "ema_inv_gamma": 1.0,
10
+ "ema_max_decay": 0.9999,
11
+ "ema_power": 0.75,
12
+ "enable_gradient_checkpointing": true,
13
+ "exclude_components": [],
14
+ "fp32_master_weights": true,
15
+ "full_shuffle": true,
16
+ "gradient_accumulation_steps": 16,
17
+ "gradient_checkpointing_layers": null,
18
+ "gradient_clip_norm": 1.0,
19
+ "initial_run_dir": "/media/nvidia/4TB2/llm-runs/senryu-2-1b/sft-v1",
20
+ "initial_weights": "ema",
21
+ "learning_rate": 0.0005,
22
+ "learning_rate_decay_start_step": null,
23
+ "learning_rate_schedule": "constant",
24
+ "log_every_optimizer_steps": 1,
25
+ "logit_z_loss_coefficient": 0.0001,
26
+ "maximum_checkpoints": 4,
27
+ "maximum_consecutive_skipped_steps": 8,
28
+ "maximum_optimizer_steps": null,
29
+ "micro_batch_size": 1,
30
+ "minimum_learning_rate_ratio": 0.1,
31
+ "model_config": null,
32
+ "muon_learning_rate": null,
33
+ "muon_lr_adjustment": "match_rms_adamw",
34
+ "muon_momentum": 0.95,
35
+ "ngram_device": "cpu",
36
+ "ngram_learning_rate_multiplier": 5.0,
37
+ "optimizer": "muon_v2",
38
+ "output_dir": "/media/nvidia/4TB2/llm-runs/senryu-2.1-1b/sft-v1",
39
+ "require_complete_pretraining": false,
40
+ "require_complete_sft_source": false,
41
+ "rewrite_empty_think": true,
42
+ "save_every_optimizer_steps": 100,
43
+ "seed": 20261024,
44
+ "sequence_length": 32768,
45
+ "shuffle_block_sequences": 2048,
46
+ "skip_nonfinite_steps": true,
47
+ "stream_download_threads": 8,
48
+ "stream_english_share": null,
49
+ "stream_open_languages": null,
50
+ "stream_pairs_per_row": 1,
51
+ "tokenizer": null,
52
+ "unclosed_think": "mask_end",
53
+ "validation_batches": 16,
54
+ "warmup_ratio": 0.0,
55
+ "warmup_steps": 50,
56
+ "weight_decay": 0.1
57
+ }
special_token_ids.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|begin_of_text|>",
3
+ "eos_token": "<|end_of_text|>",
4
+ "pad_token": "<|padding|>",
5
+ "unk_token": "<|unknown|>",
6
+ "bos_token_id": 0,
7
+ "eos_token_id": 1,
8
+ "pad_token_id": 2,
9
+ "unk_token_id": 3,
10
+ "im_start": "<|im_start|>",
11
+ "im_start_id": 4,
12
+ "im_end": "<|im_end|>",
13
+ "im_end_id": 5,
14
+ "think_control": "<|think|>",
15
+ "think_control_id": 15,
16
+ "no_think_control": "<|no_think|>",
17
+ "no_think_control_id": 14,
18
+ "tool_response": "<|tool_response|>",
19
+ "tool_response_id": 7,
20
+ "think_open": "<think>",
21
+ "think_open_id": 8,
22
+ "think_close": "</think>",
23
+ "think_close_id": 9
24
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|begin_of_text|>",
3
+ "eos_token": "<|end_of_text|>",
4
+ "pad_token": "<|padding|>",
5
+ "unk_token": "<|unknown|>",
6
+ "additional_special_tokens": [
7
+ "<|im_start|>",
8
+ "<|im_end|>",
9
+ "<|tool_call|>",
10
+ "<|tool_response|>",
11
+ "<think>",
12
+ "</think>",
13
+ "<|fim_prefix|>",
14
+ "<|fim_middle|>",
15
+ "<|fim_suffix|>",
16
+ "<|fim_pad|>",
17
+ "<|no_think|>",
18
+ "<|think|>",
19
+ "<|reserved_002|>",
20
+ "<|reserved_003|>",
21
+ "<|reserved_004|>",
22
+ "<|reserved_005|>",
23
+ "<|reserved_006|>",
24
+ "<|reserved_007|>",
25
+ "<|reserved_008|>",
26
+ "<|reserved_009|>",
27
+ "<|reserved_010|>",
28
+ "<|reserved_011|>",
29
+ "<|reserved_012|>",
30
+ "<|reserved_013|>",
31
+ "<|reserved_014|>",
32
+ "<|reserved_015|>",
33
+ "<|reserved_016|>",
34
+ "<|reserved_017|>",
35
+ "<|reserved_018|>",
36
+ "<|reserved_019|>",
37
+ "<|reserved_020|>",
38
+ "<|reserved_021|>",
39
+ "<|reserved_022|>",
40
+ "<|reserved_023|>",
41
+ "<|reserved_024|>",
42
+ "<|reserved_025|>",
43
+ "<|reserved_026|>",
44
+ "<|reserved_027|>",
45
+ "<|reserved_028|>",
46
+ "<|reserved_029|>",
47
+ "<|reserved_030|>",
48
+ "<|reserved_031|>",
49
+ "<|reserved_032|>",
50
+ "<|reserved_033|>",
51
+ "<|reserved_034|>",
52
+ "<|reserved_035|>",
53
+ "<|reserved_036|>",
54
+ "<|reserved_037|>",
55
+ "<|reserved_038|>",
56
+ "<|reserved_039|>",
57
+ "<|reserved_040|>",
58
+ "<|reserved_041|>",
59
+ "<|reserved_042|>",
60
+ "<|reserved_043|>",
61
+ "<|reserved_044|>",
62
+ "<|reserved_045|>",
63
+ "<|reserved_046|>",
64
+ "<|reserved_047|>",
65
+ "<|reserved_048|>",
66
+ "<|reserved_049|>"
67
+ ]
68
+ }
tiny_gdn/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tiny_gdn.config import (
2
+ TinyGDNConfig,
3
+ haiku_config,
4
+ haiku_kdn_config,
5
+ prompttercet_config,
6
+ senryu2_1b_config,
7
+ senryu_config,
8
+ )
9
+ from tiny_gdn.model import TinyGDNForCausalLM, TinyGDNOutput
10
+
11
+ __all__ = [
12
+ "TinyGDNConfig",
13
+ "TinyGDNForCausalLM",
14
+ "TinyGDNOutput",
15
+ "haiku_config",
16
+ "haiku_kdn_config",
17
+ "prompttercet_config",
18
+ "senryu2_1b_config",
19
+ "senryu_config",
20
+ ]
tiny_gdn/chatml.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from tiny_gdn.smoltalk_chat import (
6
+ NO_THINK_PREFIX,
7
+ THINK_CONTROL_PREFIX,
8
+ ToolFormatChoice,
9
+ kwargs_from_inference_request,
10
+ materialize_smoltalk_messages,
11
+ merge_kwargs_with_system_message,
12
+ resolve_reasoning_mode,
13
+ )
14
+ from tiny_gdn.tools import prepare_inference_messages
15
+
16
+ THINK_START = "<think>"
17
+ THINK_END = "</think>"
18
+ # A prompter writes the template's user turns: clients send its own turns as
19
+ # "assistant" and the replies it gets as "user", and the template swaps them.
20
+ PROMPTER_TEMPLATE_ROLES = {"system": "system", "assistant": "user", "user": "assistant"}
21
+
22
+
23
+ def decode_chat_completion(tokenizer: Any, token_ids: list[int]) -> str:
24
+ return tokenizer.decode(token_ids, skip_special_tokens=False)
25
+
26
+
27
+ def append_assistant_generation_prompt(
28
+ tokenizer: Any,
29
+ token_ids: list[int],
30
+ *,
31
+ enable_thinking: bool | None = None,
32
+ ) -> None:
33
+ im_start = tokenizer.token_to_id("<|im_start|>")
34
+ if im_start is None:
35
+ raise RuntimeError("Tokenizer is missing <|im_start|>")
36
+ token_ids.append(im_start)
37
+ token_ids.extend(
38
+ tokenizer.encode("assistant\n", add_special_tokens=False).ids
39
+ )
40
+ if enable_thinking is True:
41
+ token_ids.extend(
42
+ tokenizer.encode(THINK_CONTROL_PREFIX, add_special_tokens=False).ids
43
+ )
44
+ elif enable_thinking is False:
45
+ token_ids.extend(
46
+ tokenizer.encode(NO_THINK_PREFIX, add_special_tokens=False).ids
47
+ )
48
+
49
+
50
+ def encode_chatml_messages(
51
+ tokenizer: Any,
52
+ messages: list[dict[str, Any]],
53
+ *,
54
+ tools: Any | None = None,
55
+ enable_thinking: bool | None = None,
56
+ xml_tools: Any | None = None,
57
+ python_tools: Any | None = None,
58
+ tool_format: ToolFormatChoice = "json",
59
+ ) -> list[int]:
60
+ """``tool_format`` picks the SmolTalk tool layout; models without the thinking toggle only know XML."""
61
+
62
+ if not messages:
63
+ raise ValueError("A chat needs at least one message")
64
+ if enable_thinking is None:
65
+ prepared = prepare_inference_messages(messages, tools=tools)
66
+ assistant_thinking_control = None
67
+ else:
68
+ kwargs = kwargs_from_inference_request(
69
+ enable_thinking=enable_thinking,
70
+ xml_tools=xml_tools,
71
+ python_tools=python_tools,
72
+ tools=tools,
73
+ tool_format=tool_format,
74
+ )
75
+ prepared = materialize_smoltalk_messages(messages, kwargs)
76
+ _, resolved = merge_kwargs_with_system_message(messages, kwargs)
77
+ assistant_thinking_control = (
78
+ resolve_reasoning_mode(
79
+ resolved.enable_thinking,
80
+ resolved.custom_instructions,
81
+ )
82
+ == "/think"
83
+ )
84
+ required_tokens = {
85
+ token: tokenizer.token_to_id(token)
86
+ for token in (
87
+ "<|begin_of_text|>",
88
+ "<|im_start|>",
89
+ "<|im_end|>",
90
+ )
91
+ }
92
+ if any(token_id is None for token_id in required_tokens.values()):
93
+ raise RuntimeError("Tokenizer is missing ChatML special tokens")
94
+ bos_id = required_tokens["<|begin_of_text|>"]
95
+ im_start_id = required_tokens["<|im_start|>"]
96
+ im_end_id = required_tokens["<|im_end|>"]
97
+ if bos_id is None or im_start_id is None or im_end_id is None:
98
+ raise RuntimeError("Tokenizer ChatML IDs could not be resolved")
99
+
100
+ token_ids = [bos_id]
101
+ newline_ids = tokenizer.encode("\n", add_special_tokens=False).ids
102
+ allowed_roles = {"system", "user", "assistant"}
103
+ for message_index, message in enumerate(prepared):
104
+ role = message["role"]
105
+ content = message["content"]
106
+ masked_prefix = message.get("masked_prefix", "")
107
+ if role not in allowed_roles:
108
+ raise ValueError(
109
+ f"Unsupported chat role at index {message_index}: {role!r}"
110
+ )
111
+ if not isinstance(masked_prefix, str):
112
+ raise ValueError(
113
+ f"Masked prefix at index {message_index} must be a string"
114
+ )
115
+ if not content.strip():
116
+ raise ValueError(
117
+ f"Chat content at index {message_index} must be non-empty"
118
+ )
119
+ token_ids.append(im_start_id)
120
+ token_ids.extend(
121
+ tokenizer.encode(f"{role}\n", add_special_tokens=False).ids
122
+ )
123
+ if masked_prefix:
124
+ token_ids.extend(
125
+ tokenizer.encode(masked_prefix, add_special_tokens=False).ids
126
+ )
127
+ token_ids.extend(
128
+ tokenizer.encode(content, add_special_tokens=False).ids
129
+ )
130
+ token_ids.append(im_end_id)
131
+ token_ids.extend(newline_ids)
132
+ if prepared[-1]["role"] != "user":
133
+ raise ValueError("The final chat message must have role 'user'")
134
+ append_assistant_generation_prompt(
135
+ tokenizer,
136
+ token_ids,
137
+ enable_thinking=assistant_thinking_control,
138
+ )
139
+ return token_ids
140
+
141
+
142
+ def encode_prompter_messages(tokenizer: Any, messages: list[dict[str, Any]]) -> list[int]:
143
+ """Render a conversation for a prompter, a model that writes the user's side of a chat.
144
+
145
+ Clients keep ordinary roles: ``assistant`` messages are the prompter's
146
+ earlier turns and ``user`` messages the replies it got. The template swaps
147
+ them, renders each reply as a non-reasoning assistant turn as in the
148
+ prompter's training data, and prompts for the next user turn. With no
149
+ messages, or only a system prompt, the prompter opens the conversation.
150
+ The system prompt is the one the replying assistant would have had; it
151
+ steers what the prompter asks about.
152
+ """
153
+
154
+ special_ids = [tokenizer.token_to_id(token) for token in ("<|begin_of_text|>", "<|im_start|>", "<|im_end|>")]
155
+ if any(token_id is None for token_id in special_ids):
156
+ raise RuntimeError("Tokenizer is missing ChatML special tokens")
157
+ bos_id, im_start_id, im_end_id = special_ids
158
+ newline_ids = tokenizer.encode("\n", add_special_tokens=False).ids
159
+ token_ids = [bos_id]
160
+ for index, message in enumerate(messages):
161
+ role = message["role"]
162
+ content = message["content"]
163
+ template_role = PROMPTER_TEMPLATE_ROLES.get(role)
164
+ if template_role is None:
165
+ raise ValueError(f"Prompters take system, user and assistant messages, not {role!r} (index {index})")
166
+ if role == "system" and index != 0:
167
+ raise ValueError("A prompter takes a system prompt only as the first message")
168
+ if not isinstance(content, str) or not content.strip():
169
+ raise ValueError(f"Chat content at index {index} must be non-empty")
170
+ token_ids.append(im_start_id)
171
+ token_ids.extend(tokenizer.encode(f"{template_role}\n", add_special_tokens=False).ids)
172
+ if template_role == "assistant":
173
+ token_ids.extend(tokenizer.encode(NO_THINK_PREFIX, add_special_tokens=False).ids)
174
+ token_ids.extend(tokenizer.encode(content, add_special_tokens=False).ids)
175
+ token_ids.append(im_end_id)
176
+ token_ids.extend(newline_ids)
177
+ if messages and messages[-1]["role"] == "assistant":
178
+ raise ValueError(
179
+ "A prompter writes the turn after a reply: end with a 'user' message, or send none for its opening"
180
+ )
181
+ token_ids.append(im_start_id)
182
+ token_ids.extend(tokenizer.encode("user\n", add_special_tokens=False).ids)
183
+ return token_ids
tiny_gdn/cli_chat.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Terminal chat: live reasoning stream plus SmolTalk tool-call rounds.
2
+
3
+ Tercet-R assistant turns may contain:
4
+
5
+ - a zero-loss `<|think|>` / `<|no_think|>` control prefix
6
+ - a `<think>…</think>` reasoning block
7
+ - one or more SmolTalk JSON `<tool_call>` blocks (NVIDIA XML is also parsed)
8
+
9
+ This module colours those regions as tokens arrive and, after a completed
10
+ turn, collects tool observations (prefixed with `<|tool_response|>`) so the
11
+ model can continue the same conversation.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import sys
18
+ from collections.abc import Callable, Sequence
19
+ from dataclasses import dataclass, field
20
+ from typing import Any, Literal, TextIO
21
+
22
+ from tiny_gdn.smoltalk_chat import (
23
+ TOOL_RESPONSE_TOKEN,
24
+ format_smoltalk_tool_call,
25
+ wrap_smoltalk_tool_result,
26
+ )
27
+ from tiny_gdn.code_exec import (
28
+ CALCULATOR_TOOL,
29
+ NEMOTRON_PYTHON_EXEC_TOOL,
30
+ execute_math_tool,
31
+ is_auto_math_tool_name,
32
+ reset_default_python_session,
33
+ )
34
+ from tiny_gdn.tools import ParsedToolCall, parse_tool_calls
35
+ from tiny_gdn.web_fetch import (
36
+ FETCH_PAGE_TOOL,
37
+ fetch_page,
38
+ is_fetch_page_tool_name,
39
+ offset_from_arguments,
40
+ url_from_arguments,
41
+ )
42
+ from tiny_gdn.web_search import (
43
+ NEMOTRON_WEB_SEARCH_TOOL,
44
+ is_web_search_tool_name,
45
+ query_from_arguments,
46
+ search_web,
47
+ )
48
+
49
+
50
+ SegmentKind = Literal["answer", "think", "tool_call"]
51
+ MarkerKind = Literal[
52
+ "think_open",
53
+ "think_close",
54
+ "think_control",
55
+ "no_think",
56
+ "tool_open",
57
+ "tool_close",
58
+ ]
59
+
60
+ THINK_OPEN = "<think>"
61
+ THINK_CLOSE = "</think>"
62
+ TOOL_CALL_OPEN = "<tool_call>"
63
+ TOOL_CALL_CLOSE = "</tool_call>"
64
+ THINK_CONTROL = "<|think|>"
65
+ NO_THINK_CONTROL = "<|no_think|>"
66
+
67
+ MARKERS: tuple[tuple[str, MarkerKind], ...] = (
68
+ (THINK_CLOSE, "think_close"),
69
+ (TOOL_CALL_CLOSE, "tool_close"),
70
+ (THINK_OPEN, "think_open"),
71
+ (TOOL_CALL_OPEN, "tool_open"),
72
+ (NO_THINK_CONTROL, "no_think"),
73
+ (THINK_CONTROL, "think_control"),
74
+ )
75
+
76
+ ANSI = {
77
+ "think": "\033[2;33m",
78
+ "tool_call": "\033[36m",
79
+ "answer": "\033[0m",
80
+ "reset": "\033[0m",
81
+ }
82
+
83
+ DEFAULT_MAX_TOOL_ROUNDS = 8
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class ContentSegment:
88
+ kind: SegmentKind
89
+ text: str
90
+ open: bool = False
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class GeneratedTurn:
95
+ text: str
96
+ token_count: int
97
+ stop_reason: str
98
+ tool_calls: tuple[ParsedToolCall, ...]
99
+
100
+
101
+ def first_marker(text: str) -> tuple[int, str, MarkerKind] | None:
102
+ best: tuple[int, str, MarkerKind] | None = None
103
+ for marker, kind in MARKERS:
104
+ at = text.find(marker)
105
+ if at < 0:
106
+ continue
107
+ if (
108
+ best is None
109
+ or at < best[0]
110
+ or (at == best[0] and len(marker) > len(best[1]))
111
+ ):
112
+ best = (at, marker, kind)
113
+ return best
114
+
115
+
116
+ def holdback_prefix_length(text: str) -> int:
117
+ if not text:
118
+ return 0
119
+ keep = 0
120
+ for marker, _kind in MARKERS:
121
+ limit = min(len(marker) - 1, len(text))
122
+ for size in range(1, limit + 1):
123
+ if marker.startswith(text[-size:]):
124
+ keep = max(keep, size)
125
+ return keep
126
+
127
+
128
+ def mode_after_marker(kind: MarkerKind, current: SegmentKind) -> SegmentKind:
129
+ if kind in {"think_open", "think_control"}:
130
+ return "think"
131
+ if kind in {"think_close", "no_think", "tool_close"}:
132
+ return "answer"
133
+ if kind == "tool_open":
134
+ return "tool_call"
135
+ return current
136
+
137
+
138
+ def _segment_text(segment: ContentSegment) -> str:
139
+ return segment.text.strip()
140
+
141
+
142
+ def format_assistant_markdown(source: str) -> str:
143
+ """Render a streamed assistant turn as a single markdown block."""
144
+
145
+ think_parts: list[str] = []
146
+ answer_parts: list[str] = []
147
+ tool_parts: list[str] = []
148
+ for segment in split_assistant_segments(source):
149
+ text = _segment_text(segment)
150
+ if not text:
151
+ continue
152
+ if segment.kind == "think":
153
+ think_parts.append(text)
154
+ elif segment.kind == "tool_call":
155
+ tool_parts.append(text)
156
+ else:
157
+ answer_parts.append(text)
158
+ blocks: list[str] = []
159
+ if think_parts:
160
+ blocks.append("**Reasoning**\n\n" + "\n\n".join(think_parts))
161
+ if answer_parts:
162
+ blocks.append("\n\n".join(answer_parts))
163
+ for tool in tool_parts:
164
+ blocks.append(f"```tool_call\n{tool}\n```")
165
+ return "\n\n".join(blocks).strip()
166
+
167
+
168
+ def format_assistant_chat_messages(source: str) -> list[dict[str, Any]]:
169
+ """Split a turn into Gradio thoughts plus a normal assistant chat message.
170
+
171
+ Messages with ``metadata.title`` render as collapsible thoughts. The reply
172
+ has no metadata so Gradio shows it as the chat bubble.
173
+ """
174
+
175
+ think_parts: list[str] = []
176
+ answer_parts: list[str] = []
177
+ tool_parts: list[str] = []
178
+ think_pending = False
179
+ for segment in split_assistant_segments(source):
180
+ text = _segment_text(segment)
181
+ if segment.kind == "think":
182
+ think_pending = segment.open
183
+ if text:
184
+ think_parts.append(text)
185
+ continue
186
+ think_pending = False
187
+ if not text:
188
+ continue
189
+ if segment.kind == "tool_call":
190
+ tool_parts.append(text)
191
+ else:
192
+ answer_parts.append(text)
193
+
194
+ messages: list[dict[str, Any]] = []
195
+ if think_parts:
196
+ messages.append(
197
+ {
198
+ "role": "assistant",
199
+ "content": "\n\n".join(think_parts),
200
+ "metadata": {
201
+ "title": "Reasoning",
202
+ "status": "pending" if think_pending else "done",
203
+ },
204
+ }
205
+ )
206
+ for tool in tool_parts:
207
+ messages.append(
208
+ {
209
+ "role": "assistant",
210
+ "content": f"```json\n{tool}\n```",
211
+ "metadata": {"title": "Tool call", "status": "done"},
212
+ }
213
+ )
214
+ answer = "\n\n".join(answer_parts)
215
+ if answer or not messages:
216
+ messages.append({"role": "assistant", "content": answer})
217
+ return messages
218
+
219
+
220
+ def split_assistant_segments(source: str) -> list[ContentSegment]:
221
+ """Split a completed (or in-progress) assistant turn for tests / replay."""
222
+
223
+ segments: list[ContentSegment] = []
224
+ mode: SegmentKind = "answer"
225
+ cursor = 0
226
+ while cursor < len(source):
227
+ found = first_marker(source[cursor:])
228
+ if found is None:
229
+ tail = source[cursor:]
230
+ if tail:
231
+ segments.append(ContentSegment(kind=mode, text=tail, open=True))
232
+ break
233
+ at, marker, kind = found
234
+ at += cursor
235
+ if at > cursor:
236
+ segments.append(
237
+ ContentSegment(kind=mode, text=source[cursor:at], open=False)
238
+ )
239
+ mode = mode_after_marker(kind, mode)
240
+ cursor = at + len(marker)
241
+ return [segment for segment in segments if segment.text]
242
+
243
+
244
+ class LiveReasoningStreamer:
245
+ """Colour reasoning and tool-call regions as decoded text grows."""
246
+
247
+ def __init__(
248
+ self,
249
+ writer: TextIO | None = None,
250
+ *,
251
+ color: bool | None = None,
252
+ ) -> None:
253
+ self.writer = writer if writer is not None else sys.stdout
254
+ if color is None:
255
+ color = bool(getattr(self.writer, "isatty", lambda: False)())
256
+ self.color = color
257
+ self._seen = ""
258
+ self._hold = ""
259
+ self._mode: SegmentKind = "answer"
260
+ self._style: SegmentKind | None = None
261
+ self._emitted_think_label = False
262
+ self._emitted_tool_label = False
263
+
264
+ def update(self, decoded: str) -> None:
265
+ if decoded.startswith(self._seen):
266
+ delta = decoded[len(self._seen) :]
267
+ else:
268
+ delta = decoded
269
+ self._seen = decoded
270
+ if delta:
271
+ self._consume(delta, final=False)
272
+
273
+ def finish(self) -> str:
274
+ if self._hold:
275
+ self._emit(self._hold)
276
+ self._hold = ""
277
+ self._set_style(None)
278
+ self.writer.write("\n")
279
+ self.writer.flush()
280
+ return self._seen
281
+
282
+ def _consume(self, delta: str, *, final: bool) -> None:
283
+ buffer = self._hold + delta
284
+ self._hold = ""
285
+ while buffer:
286
+ found = first_marker(buffer)
287
+ if found is None:
288
+ keep = 0 if final else holdback_prefix_length(buffer)
289
+ if keep:
290
+ self._emit(buffer[:-keep])
291
+ self._hold = buffer[-keep:]
292
+ else:
293
+ self._emit(buffer)
294
+ return
295
+ at, marker, kind = found
296
+ if at:
297
+ self._emit(buffer[:at])
298
+ self._switch(kind)
299
+ buffer = buffer[at + len(marker) :]
300
+ if final:
301
+ return
302
+
303
+ def _switch(self, kind: MarkerKind) -> None:
304
+ nxt = mode_after_marker(kind, self._mode)
305
+ if nxt != self._mode and nxt == "answer":
306
+ self._emit_plain("\n")
307
+ self._mode = nxt
308
+ if nxt == "think" and not self._emitted_think_label:
309
+ self._emit_plain("\n")
310
+ self._set_style("think")
311
+ self._emit_plain("reasoning ")
312
+ self._emitted_think_label = True
313
+ elif nxt == "tool_call" and not self._emitted_tool_label:
314
+ self._emit_plain("\n")
315
+ self._set_style("tool_call")
316
+ self._emit_plain("tool_call ")
317
+ self._emitted_tool_label = True
318
+ elif nxt == "answer":
319
+ self._set_style("answer")
320
+
321
+ def _emit(self, text: str) -> None:
322
+ if not text:
323
+ return
324
+ self._set_style(self._mode)
325
+ self.writer.write(text)
326
+ self.writer.flush()
327
+
328
+ def _emit_plain(self, text: str) -> None:
329
+ if not text:
330
+ return
331
+ self._set_style(None)
332
+ self.writer.write(text)
333
+ self.writer.flush()
334
+
335
+ def _set_style(self, kind: SegmentKind | None) -> None:
336
+ if not self.color:
337
+ self._style = kind
338
+ return
339
+ if kind == self._style:
340
+ return
341
+ self.writer.write(ANSI["reset"])
342
+ if kind in {"think", "tool_call"}:
343
+ self.writer.write(ANSI[kind])
344
+ self._style = kind
345
+
346
+
347
+ def prompt_tool_results(
348
+ calls: Sequence[ParsedToolCall],
349
+ *,
350
+ read_line: Callable[[str], str],
351
+ writer: TextIO | None = None,
352
+ execute_web_search: bool = True,
353
+ ) -> list[str]:
354
+ """Run the built-in tools and ask for the other observations, in call order.
355
+
356
+ ``execute_web_search`` covers both web tools, web-search and fetch-page.
357
+ """
358
+
359
+ out = writer if writer is not None else sys.stdout
360
+ results: list[str] = []
361
+ auto_search = sum(
362
+ 1
363
+ for call in calls
364
+ if execute_web_search and is_web_search_tool_name(call.name)
365
+ )
366
+ auto_fetch = sum(
367
+ 1
368
+ for call in calls
369
+ if execute_web_search and is_fetch_page_tool_name(call.name)
370
+ )
371
+ auto_math = sum(1 for call in calls if is_auto_math_tool_name(call.name))
372
+ if auto_search:
373
+ out.write(
374
+ f"\n{auto_search} web-search call(s) will run automatically "
375
+ f"(Tavily JSON, sent as {TOOL_RESPONSE_TOKEN}).\n"
376
+ )
377
+ out.flush()
378
+ if auto_fetch:
379
+ out.write(
380
+ f"\n{auto_fetch} fetch-page call(s) will run automatically "
381
+ f"(page text as Markdown, sent as {TOOL_RESPONSE_TOKEN}).\n"
382
+ )
383
+ out.flush()
384
+ if auto_math:
385
+ out.write(
386
+ f"\n{auto_math} python/calculator call(s) will run automatically "
387
+ f"(sent as {TOOL_RESPONSE_TOKEN}).\n"
388
+ )
389
+ out.flush()
390
+ manual = len(calls) - auto_search - auto_fetch - auto_math
391
+ if manual:
392
+ out.write(
393
+ f"\n{manual} tool call(s). Paste each observation; "
394
+ f"it is sent as {TOOL_RESPONSE_TOKEN}.\n"
395
+ )
396
+ out.flush()
397
+ for index, call in enumerate(calls, start=1):
398
+ out.write(
399
+ f"\n[{index}/{len(calls)}] "
400
+ f"{format_smoltalk_tool_call(call.name, call.arguments)}\n"
401
+ )
402
+ out.flush()
403
+ if execute_web_search and is_web_search_tool_name(call.name):
404
+ query = query_from_arguments(call.arguments)
405
+ out.write(f"searching {query!r}…\n")
406
+ out.flush()
407
+ results.append(search_web(query))
408
+ continue
409
+ if execute_web_search and is_fetch_page_tool_name(call.name):
410
+ url = url_from_arguments(call.arguments)
411
+ out.write(f"fetching {url!r}…\n")
412
+ out.flush()
413
+ results.append(fetch_page(url, offset=offset_from_arguments(call.arguments)).observation)
414
+ continue
415
+ if is_auto_math_tool_name(call.name):
416
+ out.write("running python…\n")
417
+ out.flush()
418
+ try:
419
+ results.append(execute_math_tool(call.name, call.arguments))
420
+ except Exception as error:
421
+ results.append(f"Error: {error}")
422
+ continue
423
+ results.append(read_line(f"result[{call.name}]> "))
424
+ return results
425
+
426
+
427
+ def append_tool_round(
428
+ messages: list[dict[str, Any]],
429
+ assistant_text: str,
430
+ raw_results: Sequence[str],
431
+ ) -> None:
432
+ messages.append({"role": "assistant", "content": assistant_text})
433
+ for raw in raw_results:
434
+ wrapped = wrap_smoltalk_tool_result(raw)
435
+ if not wrapped:
436
+ raise ValueError("Tool result cannot be empty")
437
+ messages.append({"role": "tool", "content": raw})
438
+
439
+
440
+ def resolve_cli_tools(spec: str | None, tools_json: str | None) -> list[dict[str, Any]] | None:
441
+ tools: list[dict[str, Any]] = []
442
+ if spec:
443
+ for name in spec.split(","):
444
+ key = name.strip().lower()
445
+ if not key or key in {"none", "off"}:
446
+ continue
447
+ if is_web_search_tool_name(key):
448
+ tools.append(NEMOTRON_WEB_SEARCH_TOOL)
449
+ continue
450
+ if is_fetch_page_tool_name(key) or key == "fetch":
451
+ tools.append(FETCH_PAGE_TOOL)
452
+ continue
453
+ if key in {"python", "python-exec", "code-interpreter"}:
454
+ tools.append(NEMOTRON_PYTHON_EXEC_TOOL)
455
+ continue
456
+ if key in {"calculator", "calc"}:
457
+ tools.append(CALCULATOR_TOOL)
458
+ continue
459
+ raise ValueError(
460
+ f"Unknown built-in tool {name!r}. "
461
+ "Use web-search, fetch-page, python, calculator, or --tools-json."
462
+ )
463
+ if tools_json:
464
+ payload = json.loads(tools_json)
465
+ if isinstance(payload, dict):
466
+ tools.append(payload)
467
+ elif isinstance(payload, list):
468
+ tools.extend(payload)
469
+ else:
470
+ raise ValueError("tools JSON must be an object or array")
471
+ return tools or None
472
+
473
+
474
+ @dataclass
475
+ class ChatLoopState:
476
+ messages: list[dict[str, Any]] = field(default_factory=list)
477
+ system: str = ""
478
+ enable_thinking: bool = True
479
+ tools: list[dict[str, Any]] | None = None
480
+
481
+ def reset(self) -> None:
482
+ self.messages = []
483
+ reset_default_python_session()
484
+ if self.system.strip():
485
+ self.messages.append({"role": "system", "content": self.system.strip()})
486
+
487
+ def add_user(self, text: str) -> None:
488
+ self.messages.append({"role": "user", "content": text})
489
+
490
+
491
+ def apply_slash_command(state: ChatLoopState, text: str) -> str | None:
492
+ """Return a status string if `text` is a slash command, else None."""
493
+
494
+ command = text.strip()
495
+ lowered = command.lower()
496
+ if lowered in {"/exit", "/quit"}:
497
+ return "exit"
498
+ if lowered == "/reset":
499
+ state.reset()
500
+ return "history cleared"
501
+ if lowered == "/think":
502
+ if state.messages:
503
+ return "thinking can only be changed on a fresh conversation (/reset first)"
504
+ state.enable_thinking = True
505
+ return "thinking on — next assistant turn is prefixed with <|think|>"
506
+ if lowered in {"/no_think", "/nothink"}:
507
+ if state.messages:
508
+ return "thinking can only be changed on a fresh conversation (/reset first)"
509
+ state.enable_thinking = False
510
+ return "thinking off — next assistant turn is prefixed with <|no_think|>"
511
+ if lowered.startswith("/system"):
512
+ rest = command[len("/system") :].strip()
513
+ state.system = rest
514
+ state.reset()
515
+ return "system prompt updated" if rest else "system prompt cleared"
516
+ return None
tiny_gdn/code_exec.py ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Restricted stateful Python for Nemotron Cascade-2 math tool calls.
2
+
3
+ Tercet-R saw `stateful_python_code_exec` on `math/math_tool.jsonl` during
4
+ the Cascade-2 SFT stage. Observations are the Jupyter-style stdout / last
5
+ expression value, not a JSON envelope.
6
+
7
+ The worker process only allows a math-oriented import whitelist and rejects
8
+ dunder access, so a tool call cannot read the filesystem or start a shell.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import ast
14
+ import io
15
+ import itertools
16
+ import json
17
+ import math
18
+ import os
19
+ import re
20
+ import statistics
21
+ import subprocess
22
+ import sys
23
+ import threading
24
+ from collections.abc import Iterable, Iterator, Mapping
25
+ from pathlib import Path
26
+ from queue import Empty, Queue
27
+ from typing import Any
28
+
29
+
30
+ NEMOTRON_PYTHON_EXEC_TOOL: dict[str, Any] = {
31
+ "type": "function",
32
+ "function": {
33
+ "name": "stateful_python_code_exec",
34
+ "description": (
35
+ "Call this function to execute Python code in a stateful Jupyter "
36
+ "notebook environment. Python will respond with the output of the "
37
+ "execution or time out after 120.0 seconds."
38
+ ),
39
+ "parameters": {
40
+ "type": "object",
41
+ "properties": {
42
+ "code": {
43
+ "type": "string",
44
+ "description": "Code to execute",
45
+ }
46
+ },
47
+ "required": ["code"],
48
+ },
49
+ },
50
+ }
51
+
52
+ CALCULATOR_TOOL: dict[str, Any] = {
53
+ "type": "function",
54
+ "function": {
55
+ "name": "calculator",
56
+ "description": "Evaluate a math expression and return the result.",
57
+ "parameters": {
58
+ "type": "object",
59
+ "properties": {
60
+ "expression": {
61
+ "type": "string",
62
+ "description": (
63
+ "A math expression in standard calculator notation, for example "
64
+ "(3 + 4)^2 * sqrt(2) / ln(10). Use + - * / ^ (power), % (remainder), "
65
+ "! (factorial) and parentheses; the constants pi and e; and functions "
66
+ "such as sqrt, cbrt, exp, ln, log (natural, or log(x, base)), log10, "
67
+ "log2, sin, cos, tan, asin, acos, atan (radians), abs, round, floor, "
68
+ "ceil, factorial, comb, perm, gcd, lcm, min, max, sum, mean and median."
69
+ ),
70
+ }
71
+ },
72
+ "required": ["expression"],
73
+ },
74
+ },
75
+ }
76
+
77
+ PYTHON_EXEC_TOOL_NAMES = frozenset(
78
+ {
79
+ "stateful_python_code_exec",
80
+ "python_code_exec",
81
+ "code_interpreter",
82
+ "python_exec",
83
+ "python",
84
+ }
85
+ )
86
+ CALCULATOR_TOOL_NAMES = frozenset({"calculator", "calc"})
87
+ DEFAULT_EXEC_TIMEOUT_SECONDS = 30.0
88
+ _SRC_ROOT = Path(__file__).resolve().parents[1]
89
+
90
+ _session_lock = threading.Lock()
91
+ _default_session: StatefulPythonSession | None = None
92
+
93
+
94
+ def _normalize_tool_name(name: str) -> str:
95
+ return name.strip().lower().replace("-", "_")
96
+
97
+
98
+ def is_python_exec_tool_name(name: str) -> bool:
99
+ return _normalize_tool_name(name) in PYTHON_EXEC_TOOL_NAMES
100
+
101
+
102
+ def is_calculator_tool_name(name: str) -> bool:
103
+ return _normalize_tool_name(name) in CALCULATOR_TOOL_NAMES
104
+
105
+
106
+ def is_auto_math_tool_name(name: str) -> bool:
107
+ return is_python_exec_tool_name(name) or is_calculator_tool_name(name)
108
+
109
+
110
+ def is_calculator_expression(source: str) -> bool:
111
+ """A one-line calculator call runs in the calculator; several statements run as notebook code."""
112
+ return "\n" not in source.strip() and ";" not in source
113
+
114
+
115
+ def code_from_arguments(arguments: Mapping[str, Any] | None) -> str:
116
+ if not arguments:
117
+ return ""
118
+ for key in ("code", "expression", "expr", "source"):
119
+ raw = arguments.get(key)
120
+ if isinstance(raw, str) and raw.strip():
121
+ return raw
122
+ if raw is not None and key != "code":
123
+ return str(raw)
124
+ return ""
125
+
126
+
127
+ class CodeExecError(ValueError):
128
+ """Rejected or failed tool code."""
129
+
130
+
131
+ class CalculatorError(CodeExecError):
132
+ """An expression the calculator cannot evaluate. The message says how to fix it."""
133
+
134
+
135
+ class StatefulPythonSession:
136
+ """One long-lived restricted interpreter, matching the training tool."""
137
+
138
+ def __init__(self, *, timeout_seconds: float = DEFAULT_EXEC_TIMEOUT_SECONDS) -> None:
139
+ self.timeout_seconds = timeout_seconds
140
+ self._lock = threading.Lock()
141
+ self._process: subprocess.Popen[str] | None = None
142
+
143
+ def close(self) -> None:
144
+ with self._lock:
145
+ self._kill_locked()
146
+
147
+ def reset(self) -> None:
148
+ with self._lock:
149
+ self._kill_locked()
150
+
151
+ def run(self, code: str) -> str:
152
+ text = code.strip()
153
+ if not text:
154
+ raise CodeExecError("code is empty")
155
+ with self._lock:
156
+ return self._run_locked(text)
157
+
158
+ def _run_locked(self, code: str) -> str:
159
+ process = self._ensure_process_locked()
160
+ try:
161
+ process.stdin.write(json.dumps({"code": code}, ensure_ascii=False) + "\n")
162
+ process.stdin.flush()
163
+ line = self._readline_locked(process, self.timeout_seconds)
164
+ except (BrokenPipeError, OSError) as error:
165
+ self._kill_locked()
166
+ raise CodeExecError(f"python worker died: {error}") from error
167
+ if not line:
168
+ stderr = ""
169
+ if process.stderr is not None:
170
+ try:
171
+ stderr = process.stderr.read()
172
+ except OSError:
173
+ stderr = ""
174
+ self._kill_locked()
175
+ detail = stderr.strip() or "python worker closed stdout"
176
+ raise CodeExecError(detail)
177
+ try:
178
+ payload = json.loads(line)
179
+ except json.JSONDecodeError as error:
180
+ self._kill_locked()
181
+ raise CodeExecError(f"python worker returned invalid JSON: {line!r}") from error
182
+ if not isinstance(payload, dict):
183
+ raise CodeExecError("python worker returned a non-object")
184
+ output = str(payload.get("output") or "")
185
+ if payload.get("ok") is True:
186
+ return output if output else "None"
187
+ raise CodeExecError(output or "execution failed")
188
+
189
+ def _readline_locked(self, process: subprocess.Popen[str], timeout: float) -> str:
190
+ if process.stdout is None:
191
+ raise CodeExecError("python worker has no stdout")
192
+ lines: Queue[str] = Queue()
193
+
194
+ def _read() -> None:
195
+ lines.put(process.stdout.readline() if process.stdout is not None else "")
196
+
197
+ reader = threading.Thread(target=_read, daemon=True)
198
+ reader.start()
199
+ reader.join(timeout)
200
+ if reader.is_alive():
201
+ self._kill_locked()
202
+ raise CodeExecError(f"timed out after {timeout:g}s")
203
+ try:
204
+ return lines.get_nowait()
205
+ except Empty:
206
+ return ""
207
+
208
+ def _ensure_process_locked(self) -> subprocess.Popen[str]:
209
+ process = self._process
210
+ if process is not None and process.poll() is None:
211
+ return process
212
+ env = os.environ.copy()
213
+ pythonpath = env.get("PYTHONPATH", "")
214
+ env["PYTHONPATH"] = (
215
+ str(_SRC_ROOT) if not pythonpath else f"{_SRC_ROOT}{os.pathsep}{pythonpath}"
216
+ )
217
+ self._process = subprocess.Popen(
218
+ [sys.executable, "-m", "tiny_gdn.code_exec"],
219
+ stdin=subprocess.PIPE,
220
+ stdout=subprocess.PIPE,
221
+ stderr=subprocess.PIPE,
222
+ text=True,
223
+ bufsize=1,
224
+ env=env,
225
+ )
226
+ if self._process.stdin is None or self._process.stdout is None:
227
+ self._kill_locked()
228
+ raise CodeExecError("failed to start python worker")
229
+ return self._process
230
+
231
+ def _kill_locked(self) -> None:
232
+ process = self._process
233
+ self._process = None
234
+ if process is None:
235
+ return
236
+ try:
237
+ process.kill()
238
+ process.wait(timeout=2)
239
+ except (OSError, subprocess.TimeoutExpired):
240
+ pass
241
+
242
+
243
+ def default_python_session() -> StatefulPythonSession:
244
+ global _default_session
245
+ with _session_lock:
246
+ if _default_session is None:
247
+ _default_session = StatefulPythonSession()
248
+ return _default_session
249
+
250
+
251
+ def reset_default_python_session() -> None:
252
+ global _default_session
253
+ with _session_lock:
254
+ session = _default_session
255
+ _default_session = None
256
+ if session is not None:
257
+ session.close()
258
+
259
+
260
+ MAX_EXPRESSION_CHARS = 10_000
261
+ # Exact integer powers past this many bits are computed as floats, and overflow there.
262
+ _MAX_EXACT_POWER_BITS = 100_000
263
+ _MAX_FACTORIAL = 100_000
264
+ _MAX_LISTED_ITEMS = 1_000
265
+ # About 3,600 digits, inside the 4,300 that Python's int-to-str conversion allows.
266
+ _MAX_EXACT_INTEGER_BITS = 12_000
267
+ _POWER = "_calculator_power"
268
+ _SYMBOLS = str.maketrans(
269
+ {"×": "*", "·": "*", "÷": "/", "−": "-", "–": "-", "π": "pi", "∞": "inf", "²": "**2", "³": "**3"}
270
+ )
271
+
272
+
273
+ def calculate(expression: str, variables: Mapping[str, Any] | None = None) -> str:
274
+ """Evaluate one expression in calculator notation and format its result.
275
+
276
+ `^` is a power and `n!` a factorial, as on a calculator, and functions
277
+ such as sqrt, ln and sin need no `math.` prefix. Python's `**`, `math.`
278
+ names and comprehensions work as well. `variables` are names that a
279
+ notebook in the same conversation defined.
280
+ """
281
+ text = _calculator_text(expression)
282
+ try:
283
+ tree = ast.parse(text, mode="eval")
284
+ except SyntaxError as error:
285
+ raise CalculatorError(
286
+ f"could not read the expression ({error.msg}). "
287
+ "Write every operator out, for example 2*pi or 3*(4 + 5)."
288
+ ) from None
289
+ _reject_unsafe_ast(tree)
290
+ tree = ast.fix_missing_locations(_GuardedPower().visit(tree))
291
+ # One dict as globals, so generator expressions see the functions too.
292
+ namespace: dict[str, Any] = {"__builtins__": {}, **_calculator_functions(), **(variables or {}), _POWER: _power}
293
+ try:
294
+ value = eval(compile(tree, "<calculator>", "eval"), namespace) # noqa: S307 — AST already rejected unsafe nodes
295
+ return _calculator_result(value)
296
+ except CodeExecError:
297
+ raise
298
+ except NameError as error:
299
+ raise CalculatorError(
300
+ f"unknown name {error.name or str(error)!r}. Call functions by name, such as sqrt(2), "
301
+ "ln(5) or sin(pi/6), and use the constants pi and e."
302
+ ) from None
303
+ except ZeroDivisionError:
304
+ raise CalculatorError("division by zero") from None
305
+ except OverflowError:
306
+ raise CalculatorError("the result is too large") from None
307
+ except ValueError as error:
308
+ if "domain" in str(error):
309
+ raise CalculatorError(
310
+ "math domain error: an input is outside the function's domain, "
311
+ "such as the square root or log of a negative number"
312
+ ) from None
313
+ raise CalculatorError(str(error)) from None
314
+ except Exception as error: # noqa: BLE001 — every failure goes back to the model as text
315
+ raise CalculatorError(str(error) or type(error).__name__) from None
316
+
317
+
318
+ def execute_calculator(expression: str) -> str:
319
+ return calculate(expression)
320
+
321
+
322
+ def execute_math_tool(name: str, arguments: Mapping[str, Any] | None) -> str:
323
+ source = code_from_arguments(arguments)
324
+ if is_calculator_tool_name(name) and is_calculator_expression(source):
325
+ return calculate(source)
326
+ return default_python_session().run(source)
327
+
328
+
329
+ def _calculator_text(expression: str) -> str:
330
+ """Calculator notation as Python: ^ as **, n! as factorial(n), √, π, × and ÷ spelled out."""
331
+ text = expression.strip().translate(_SYMBOLS)
332
+ if text.endswith("=") and not text.endswith("=="):
333
+ text = text[:-1].rstrip()
334
+ if not text:
335
+ raise CalculatorError("the expression is empty")
336
+ if len(text) > MAX_EXPRESSION_CHARS:
337
+ raise CalculatorError(f"the expression is longer than {MAX_EXPRESSION_CHARS:,} characters")
338
+ text = re.sub(r"√\s*(?=\()", "sqrt", text)
339
+ text = re.sub(r"√\s*(\d+(?:\.\d*)?|[A-Za-z_]\w*)", r"sqrt(\1)", text)
340
+ text = re.sub(r"\bmod\b", "%", text)
341
+ return _expand_factorials(text.replace("^", "**"))
342
+
343
+
344
+ def _expand_factorials(text: str) -> str:
345
+ """Rewrite postfix factorials, 5! or (n + 1)!, as factorial() calls. != stays a comparison."""
346
+ position = 0
347
+ while (index := text.find("!", position)) >= 0:
348
+ if text.startswith("!=", index):
349
+ position = index + 2
350
+ continue
351
+ start = _operand_start(text, index)
352
+ if start is None:
353
+ raise CalculatorError("! needs a number, a name or a parenthesized expression before it, as in 5! or (n + 1)!")
354
+ text = f"{text[:start]}factorial({text[start:index].strip()}){text[index + 1:]}"
355
+ position = start
356
+ return text
357
+
358
+
359
+ def _operand_start(text: str, end: int) -> int | None:
360
+ """Where the operand that ends just before `end` starts: a number, a name, a call or a parenthesized group."""
361
+ index = end
362
+ while index > 0 and text[index - 1].isspace():
363
+ index -= 1
364
+ stop = index
365
+ if index > 0 and text[index - 1] == ")":
366
+ depth = 0
367
+ cursor = index - 1
368
+ while cursor >= 0:
369
+ if text[cursor] == ")":
370
+ depth += 1
371
+ elif text[cursor] == "(":
372
+ depth -= 1
373
+ if depth == 0:
374
+ break
375
+ cursor -= 1
376
+ if cursor < 0:
377
+ return None
378
+ index = cursor
379
+ while index > 0 and (text[index - 1].isalnum() or text[index - 1] in "_."):
380
+ index -= 1
381
+ return index if index < stop else None
382
+
383
+
384
+ class _GuardedPower(ast.NodeTransformer):
385
+ """Send every power through `_power`, which keeps huge exact integers from stalling the worker."""
386
+
387
+ def visit_BinOp(self, node: ast.BinOp) -> ast.AST:
388
+ self.generic_visit(node)
389
+ if isinstance(node.op, ast.Pow):
390
+ return ast.Call(func=ast.Name(id=_POWER, ctx=ast.Load()), args=[node.left, node.right], keywords=[])
391
+ return node
392
+
393
+
394
+ def _power(base: Any, exponent: Any, modulus: Any = None) -> Any:
395
+ if modulus is not None:
396
+ return pow(base, exponent, modulus)
397
+ if (
398
+ type(base) is int
399
+ and type(exponent) is int
400
+ and exponent > 0
401
+ and abs(base) > 1
402
+ and exponent * math.log2(abs(base)) > _MAX_EXACT_POWER_BITS
403
+ ):
404
+ return float(base) ** exponent
405
+ return base**exponent
406
+
407
+
408
+ def _factorial(value: Any) -> Any:
409
+ if isinstance(value, float) and value.is_integer():
410
+ value = int(value)
411
+ if isinstance(value, int) and not isinstance(value, bool):
412
+ if value < 0:
413
+ raise CalculatorError("factorial is not defined for negative integers")
414
+ if value > _MAX_FACTORIAL:
415
+ raise CalculatorError(f"factorial({value}) is too large; lgamma({value} + 1) gives its natural log")
416
+ return math.factorial(value)
417
+ return math.gamma(value + 1)
418
+
419
+
420
+ def _values(arguments: tuple[Any, ...]) -> list[Any]:
421
+ """An aggregate's numbers, given separately or as one list: mean(1, 2, 3) or mean([1, 2, 3])."""
422
+ if len(arguments) == 1 and isinstance(arguments[0], Iterable) and not isinstance(arguments[0], (str, bytes)):
423
+ return list(arguments[0])
424
+ return list(arguments)
425
+
426
+
427
+ def _root(value: Any, degree: Any) -> Any:
428
+ """The real nth root, so root(-8, 3) is -2."""
429
+ if isinstance(value, (int, float)) and value < 0 and float(degree).is_integer() and int(degree) % 2 == 1:
430
+ return -((-value) ** (1 / degree))
431
+ return value ** (1 / degree)
432
+
433
+
434
+ def _calculator_functions() -> dict[str, Any]:
435
+ names: dict[str, Any] = {key: getattr(math, key) for key in dir(math) if not key.startswith("_")}
436
+ names.update(
437
+ {
438
+ "ln": lambda value: math.log(value),
439
+ "arcsin": math.asin,
440
+ "arccos": math.acos,
441
+ "arctan": math.atan,
442
+ "arctan2": math.atan2,
443
+ "sec": lambda value: 1 / math.cos(value),
444
+ "csc": lambda value: 1 / math.sin(value),
445
+ "cot": lambda value: 1 / math.tan(value),
446
+ "sign": lambda value: (value > 0) - (value < 0),
447
+ "sgn": lambda value: (value > 0) - (value < 0),
448
+ "root": _root,
449
+ "factorial": _factorial,
450
+ "fact": _factorial,
451
+ "nCr": math.comb,
452
+ "choose": math.comb,
453
+ "nPr": math.perm,
454
+ "pow": _power,
455
+ "abs": abs,
456
+ "round": round,
457
+ "int": int,
458
+ "float": float,
459
+ "divmod": divmod,
460
+ "range": range,
461
+ "len": len,
462
+ "sorted": sorted,
463
+ "list": list,
464
+ "tuple": tuple,
465
+ "sum": lambda *values: sum(_values(values)),
466
+ "min": lambda *values: min(_values(values)),
467
+ "max": lambda *values: max(_values(values)),
468
+ "prod": lambda *values: math.prod(_values(values)),
469
+ "product": lambda *values: math.prod(_values(values)),
470
+ "mean": lambda *values: statistics.fmean(_values(values)),
471
+ "avg": lambda *values: statistics.fmean(_values(values)),
472
+ "average": lambda *values: statistics.fmean(_values(values)),
473
+ "median": lambda *values: statistics.median(_values(values)),
474
+ "mode": lambda *values: statistics.mode(_values(values)),
475
+ "stdev": lambda *values: statistics.stdev(_values(values)),
476
+ "std": lambda *values: statistics.stdev(_values(values)),
477
+ "pstdev": lambda *values: statistics.pstdev(_values(values)),
478
+ "variance": lambda *values: statistics.variance(_values(values)),
479
+ "var": lambda *values: statistics.variance(_values(values)),
480
+ "pvariance": lambda *values: statistics.pvariance(_values(values)),
481
+ "phi": (1 + math.sqrt(5)) / 2,
482
+ "deg": math.pi / 180,
483
+ "math": math,
484
+ }
485
+ )
486
+ return names
487
+
488
+
489
+ def _calculator_result(value: Any) -> str:
490
+ if value is None or isinstance(value, bool):
491
+ return str(value)
492
+ if isinstance(value, int):
493
+ return _exact_integer(value)
494
+ if isinstance(value, float):
495
+ if math.isnan(value):
496
+ return "nan"
497
+ if math.isinf(value):
498
+ return "inf" if value > 0 else "-inf"
499
+ if value.is_integer() and abs(value) < 1e15:
500
+ return str(int(value))
501
+ return format(value, ".12g")
502
+ if isinstance(value, complex):
503
+ if value.imag == 0:
504
+ return _calculator_result(value.real)
505
+ if value.real == 0:
506
+ return f"{_calculator_result(value.imag)}i"
507
+ sign = "-" if value.imag < 0 else "+"
508
+ return f"{_calculator_result(value.real)} {sign} {_calculator_result(abs(value.imag))}i"
509
+ if isinstance(value, (list, tuple, set, frozenset, range, Iterator)):
510
+ items = list(itertools.islice(iter(value), _MAX_LISTED_ITEMS + 1))
511
+ shown = ", ".join(_calculator_result(item) for item in items[:_MAX_LISTED_ITEMS])
512
+ if len(items) > _MAX_LISTED_ITEMS:
513
+ hidden = f"{len(value) - _MAX_LISTED_ITEMS:,} more" if isinstance(value, (list, tuple, set, frozenset, range)) else "more"
514
+ shown = f"{shown}, … ({hidden})"
515
+ return f"({shown})" if isinstance(value, tuple) else f"[{shown}]"
516
+ return str(value)
517
+
518
+
519
+ def _exact_integer(value: int) -> str:
520
+ if value.bit_length() <= _MAX_EXACT_INTEGER_BITS:
521
+ return str(value)
522
+ magnitude = abs(value)
523
+ shift = max(int(math.log10(magnitude)) - 12, 0)
524
+ head = str(magnitude // 10**shift)
525
+ digits = len(head) + shift
526
+ mantissa = f"{head[0]}.{head[1:13]}".rstrip("0").rstrip(".")
527
+ sign = "-" if value < 0 else ""
528
+ return f"{sign}{mantissa}e+{digits - 1} (an integer with {digits:,} digits)"
529
+
530
+
531
+ def _reject_unsafe_ast(tree: ast.AST) -> None:
532
+ for node in ast.walk(tree):
533
+ if isinstance(node, (ast.ClassDef, ast.AsyncFunctionDef)):
534
+ raise CodeExecError("class definitions are blocked")
535
+ if isinstance(node, ast.Attribute) and node.attr.startswith("_"):
536
+ raise CodeExecError("dunder attribute access is blocked")
537
+ if isinstance(node, ast.Name) and node.id.startswith("_"):
538
+ raise CodeExecError("dunder names are blocked")
539
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
540
+ if node.func.id in _BANNED_CALLS:
541
+ raise CodeExecError(f"{node.func.id}() is blocked")
542
+
543
+
544
+ _BANNED_CALLS = frozenset(
545
+ {
546
+ "eval",
547
+ "exec",
548
+ "compile",
549
+ "open",
550
+ "input",
551
+ "breakpoint",
552
+ "getattr",
553
+ "setattr",
554
+ "delattr",
555
+ "globals",
556
+ "locals",
557
+ "vars",
558
+ "dir",
559
+ "help",
560
+ "__import__",
561
+ "memoryview",
562
+ "exit",
563
+ "quit",
564
+ }
565
+ )
566
+
567
+
568
+ def _format_result(value: Any) -> str:
569
+ if value is None:
570
+ return "None"
571
+ if isinstance(value, bool):
572
+ return str(value)
573
+ if isinstance(value, float):
574
+ if value.is_integer() and abs(value) < 1e15:
575
+ return str(int(value))
576
+ return format(value, ".12g")
577
+ return str(value)
578
+
579
+
580
+ _ALLOWED_IMPORT_ROOTS = frozenset(
581
+ {
582
+ "cmath",
583
+ "collections",
584
+ "copy",
585
+ "decimal",
586
+ "fractions",
587
+ "functools",
588
+ "itertools",
589
+ "json",
590
+ "math",
591
+ "mpmath",
592
+ "numbers",
593
+ "numpy",
594
+ "operator",
595
+ "re",
596
+ "statistics",
597
+ "string",
598
+ "sympy",
599
+ "textwrap",
600
+ "unicodedata",
601
+ }
602
+ )
603
+
604
+ _WORKER_NAMESPACE: dict[str, Any] | None = None
605
+
606
+
607
+ def _allowed_import(
608
+ name: str,
609
+ globals: dict[str, Any] | None = None,
610
+ locals: dict[str, Any] | None = None,
611
+ fromlist: tuple[str, ...] = (),
612
+ level: int = 0,
613
+ ) -> Any:
614
+ root = name.split(".")[0]
615
+ if root not in _ALLOWED_IMPORT_ROOTS:
616
+ raise ImportError(f"import of {name!r} is blocked")
617
+ return __import__(name, globals, locals, fromlist, level)
618
+
619
+
620
+ def _worker_namespace() -> dict[str, Any]:
621
+ global _WORKER_NAMESPACE
622
+ if _WORKER_NAMESPACE is None:
623
+ builtins = {
624
+ "abs": abs,
625
+ "all": all,
626
+ "any": any,
627
+ "bin": bin,
628
+ "bool": bool,
629
+ "bytes": bytes,
630
+ "chr": chr,
631
+ "complex": complex,
632
+ "dict": dict,
633
+ "divmod": divmod,
634
+ "enumerate": enumerate,
635
+ "filter": filter,
636
+ "float": float,
637
+ "format": format,
638
+ "frozenset": frozenset,
639
+ "hex": hex,
640
+ "int": int,
641
+ "isinstance": isinstance,
642
+ "issubclass": issubclass,
643
+ "iter": iter,
644
+ "len": len,
645
+ "list": list,
646
+ "map": map,
647
+ "max": max,
648
+ "min": min,
649
+ "next": next,
650
+ "oct": oct,
651
+ "ord": ord,
652
+ "pow": pow,
653
+ "print": print,
654
+ "range": range,
655
+ "repr": repr,
656
+ "reversed": reversed,
657
+ "round": round,
658
+ "set": set,
659
+ "slice": slice,
660
+ "sorted": sorted,
661
+ "str": str,
662
+ "sum": sum,
663
+ "tuple": tuple,
664
+ "zip": zip,
665
+ "True": True,
666
+ "False": False,
667
+ "None": None,
668
+ "__import__": _allowed_import,
669
+ }
670
+ _WORKER_NAMESPACE = {
671
+ "__builtins__": builtins,
672
+ "__name__": "__tool__",
673
+ "math": math,
674
+ }
675
+ return _WORKER_NAMESPACE
676
+
677
+
678
+ def run_cell(code: str) -> str:
679
+ tree = ast.parse(code)
680
+ _reject_unsafe_import_roots(tree)
681
+ _reject_unsafe_ast(tree)
682
+ namespace = _worker_namespace()
683
+ buffer = io.StringIO()
684
+ previous = sys.stdout
685
+ sys.stdout = buffer
686
+ try:
687
+ if tree.body and isinstance(tree.body[-1], ast.Expr):
688
+ body = tree.body[:-1]
689
+ last = tree.body[-1]
690
+ if body:
691
+ exec( # noqa: S102
692
+ compile(ast.Module(body, type_ignores=[]), "<tool>", "exec"),
693
+ namespace,
694
+ namespace,
695
+ )
696
+ value = eval( # noqa: S307
697
+ compile(ast.Expression(last.value), "<tool>", "eval"),
698
+ namespace,
699
+ namespace,
700
+ )
701
+ printed = buffer.getvalue()
702
+ if value is None:
703
+ return printed if printed else "None"
704
+ rendered = _format_result(value)
705
+ return f"{printed}{rendered}" if printed else rendered
706
+ exec(compile(tree, "<tool>", "exec"), namespace, namespace) # noqa: S102
707
+ printed = buffer.getvalue()
708
+ return printed if printed else "None"
709
+ finally:
710
+ sys.stdout = previous
711
+
712
+
713
+ def notebook_variables() -> dict[str, Any]:
714
+ """Names this worker's notebook defined, which calculator calls in the same conversation can use."""
715
+ return {key: value for key, value in _worker_namespace().items() if not key.startswith("_") and key != "math"}
716
+
717
+
718
+ def _reject_unsafe_import_roots(tree: ast.AST) -> None:
719
+ for node in ast.walk(tree):
720
+ if isinstance(node, ast.Import):
721
+ for alias in node.names:
722
+ root = alias.name.split(".")[0]
723
+ if root not in _ALLOWED_IMPORT_ROOTS:
724
+ raise CodeExecError(f"import of {alias.name!r} is blocked")
725
+ elif isinstance(node, ast.ImportFrom):
726
+ root = (node.module or "").split(".")[0]
727
+ if root not in _ALLOWED_IMPORT_ROOTS:
728
+ raise CodeExecError(f"import of {node.module!r} is blocked")
729
+
730
+
731
+ def _worker_loop() -> None:
732
+ for line in sys.stdin:
733
+ line = line.strip()
734
+ if not line:
735
+ continue
736
+ try:
737
+ request = json.loads(line)
738
+ if "expression" in request:
739
+ output = calculate(str(request.get("expression") or ""), notebook_variables())
740
+ else:
741
+ output = run_cell(str(request.get("code") or ""))
742
+ sys.stdout.write(json.dumps({"ok": True, "output": output}, ensure_ascii=False) + "\n")
743
+ except Exception as error:
744
+ detail = str(error) or type(error).__name__
745
+ sys.stdout.write(
746
+ json.dumps({"ok": False, "output": detail}, ensure_ascii=False) + "\n"
747
+ )
748
+ sys.stdout.flush()
749
+
750
+
751
+ if __name__ == "__main__":
752
+ _worker_loop()
tiny_gdn/config.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import asdict, dataclass, fields
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ LINEAR_LAYER_TYPES = frozenset({"gdn2", "kda", "diag_kdn"})
9
+ ATTENTION_LAYER_TYPES = frozenset({"full_attention", "gated_mla", "parallax"})
10
+ RESIDUAL_MODES = frozenset({"pre_norm", "gated_residual"})
11
+ DIAG_KDN_HEAD_DIMS = (64, 128)
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class TinyGDNConfig:
16
+ architecture: str = "TinyGDNForCausalLM"
17
+ model_type: str = "tiny_gdn"
18
+
19
+ vocab_size: int = 49_152
20
+ # Deep-thin sizing is deliberate: controlled sub-billion studies find
21
+ # depth materially more valuable than width around the 125M-150M scale.
22
+ hidden_size: int = 512
23
+ intermediate_size: int = 1_472
24
+ num_hidden_layers: int = 32
25
+
26
+ num_attention_heads: int = 4
27
+ num_key_value_heads: int = 1
28
+ attention_head_dim: int = 128
29
+ full_attention_interval: int = 4
30
+ attention_dropout: float = 0.0
31
+ partial_rotary_factor: float = 0.5
32
+ rope_theta: float = 1_000_000.0
33
+
34
+ linear_num_heads: int = 4
35
+ linear_num_value_heads: int = 4
36
+ linear_head_dim: int = 128
37
+ linear_expand_v: float = 1.0
38
+ linear_conv_kernel_dim: int = 4
39
+ allow_negative_eigenvalues: bool = False
40
+ linear_layer_type: str = "gdn2"
41
+ attention_layer_type: str = "full_attention"
42
+ mlp_activation: str = "swiglu"
43
+ use_block_attn_res: bool = False
44
+ kda_safe_gate: bool = True
45
+ kda_lower_bound: float = -5.0
46
+ mla_q_lora_rank: int | None = 512
47
+ mla_kv_lora_rank: int = 256
48
+ mla_qk_nope_head_dim: int = 128
49
+ mla_v_head_dim: int = 128
50
+ situ_gate_cap: float = 4.0
51
+ situ_up_cap: float = 25.0
52
+
53
+ # "gated_residual" replaces pre-norm with Qwen's multi-branch gated
54
+ # residual stream: each sublayer reads a gated mix of `residual_branches`
55
+ # normalized branches and writes its output back with per-branch scales.
56
+ residual_mode: str = "pre_norm"
57
+ residual_branches: int = 4
58
+ residual_gate_rank: int = 128
59
+ # GDN-2 output gate as one full-rank projection (Kimi K3) instead of fla's
60
+ # low-rank pair through head_v_dim.
61
+ linear_full_rank_gate: bool = False
62
+ # Hashed n-gram memory (Engram): `ngram_heads_per_order` tables per order,
63
+ # each with a distinct prime row count near `ngram_table_rows`, injected
64
+ # before block `ngram_layer_index`. An empty `ngram_orders` disables it.
65
+ ngram_orders: tuple[int, ...] = ()
66
+ ngram_heads_per_order: int = 4
67
+ ngram_table_rows: int = 2_097_152
68
+ ngram_embedding_dim: int = 128
69
+ ngram_layer_index: int = 1
70
+ ngram_conv_kernel: int = 4
71
+
72
+ max_position_embeddings: int = 32_768
73
+ training_sequence_length: int = 2_048
74
+ rms_norm_eps: float = 1e-6
75
+ initializer_range: float = 0.02
76
+ tie_word_embeddings: bool = True
77
+ shared_layer_indices: tuple[int, ...] = ()
78
+
79
+ # MTP is an opt-in ablation at this scale; static MTP is not assumed to
80
+ # improve a 150M model without a controlled pilot.
81
+ mtp_num_heads: int = 0
82
+ mtp_adapter_rank: int = 128
83
+ mtp_loss_weight: float = 0.0
84
+
85
+ bos_token_id: int = 0
86
+ eos_token_id: int = 1
87
+ pad_token_id: int = 2
88
+ unk_token_id: int = 3
89
+
90
+ def __post_init__(self) -> None:
91
+ for name in ("shared_layer_indices", "ngram_orders"):
92
+ object.__setattr__(self, name, tuple(getattr(self, name)))
93
+ if self.vocab_size <= 0 or self.vocab_size > 65_536:
94
+ raise ValueError("vocab_size must fit the uint16 token dataset")
95
+ if self.hidden_size != self.num_attention_heads * self.attention_head_dim:
96
+ raise ValueError("hidden_size must equal num_attention_heads * attention_head_dim")
97
+ if self.hidden_size != self.linear_num_heads * self.linear_head_dim:
98
+ raise ValueError("hidden_size must equal linear_num_heads * linear_head_dim")
99
+ if self.linear_num_value_heads < self.linear_num_heads:
100
+ raise ValueError("linear_num_value_heads must be at least linear_num_heads")
101
+ if self.linear_num_value_heads % self.linear_num_heads != 0:
102
+ raise ValueError("linear_num_value_heads must be divisible by linear_num_heads")
103
+ if self.num_attention_heads % self.num_key_value_heads != 0:
104
+ raise ValueError("num_attention_heads must be divisible by num_key_value_heads")
105
+ if self.num_hidden_layers % self.full_attention_interval != 0:
106
+ raise ValueError("num_hidden_layers must be divisible by full_attention_interval")
107
+ if not 0.0 < self.partial_rotary_factor <= 1.0:
108
+ raise ValueError("partial_rotary_factor must be in (0, 1]")
109
+ rotary_dim = int(self.attention_head_dim * self.partial_rotary_factor)
110
+ if rotary_dim <= 0 or rotary_dim % 2:
111
+ raise ValueError("The partial rotary dimension must be positive and even")
112
+ if self.training_sequence_length > self.max_position_embeddings:
113
+ raise ValueError("training_sequence_length exceeds max_position_embeddings")
114
+ if len(set(self.shared_layer_indices)) != len(self.shared_layer_indices):
115
+ raise ValueError("shared_layer_indices must be unique")
116
+ if any(
117
+ index < 0 or index >= self.num_hidden_layers
118
+ for index in self.shared_layer_indices
119
+ ):
120
+ raise ValueError("shared_layer_indices contains an invalid layer")
121
+ if self.mtp_num_heads < 0:
122
+ raise ValueError("mtp_num_heads cannot be negative")
123
+ if self.mtp_num_heads and self.mtp_adapter_rank <= 0:
124
+ raise ValueError("mtp_adapter_rank must be positive when MTP is enabled")
125
+ if not 0.0 <= self.mtp_loss_weight <= 1.0:
126
+ raise ValueError("mtp_loss_weight must be between zero and one")
127
+ for token_id in (
128
+ self.bos_token_id,
129
+ self.eos_token_id,
130
+ self.pad_token_id,
131
+ self.unk_token_id,
132
+ ):
133
+ if not 0 <= token_id < self.vocab_size:
134
+ raise ValueError(f"Special token ID {token_id} is outside the vocabulary")
135
+ if self.linear_layer_type not in LINEAR_LAYER_TYPES:
136
+ raise ValueError(
137
+ f"linear_layer_type must be one of {sorted(LINEAR_LAYER_TYPES)}"
138
+ )
139
+ if self.linear_layer_type == "diag_kdn":
140
+ if self.linear_head_dim not in DIAG_KDN_HEAD_DIMS:
141
+ raise ValueError(
142
+ f"diag_kdn needs linear_head_dim in {DIAG_KDN_HEAD_DIMS}"
143
+ )
144
+ if self.linear_num_value_heads != self.linear_num_heads:
145
+ raise ValueError("diag_kdn needs linear_num_value_heads == linear_num_heads")
146
+ if self.linear_expand_v != 1.0:
147
+ raise ValueError("diag_kdn needs linear_expand_v == 1.0")
148
+ if self.allow_negative_eigenvalues:
149
+ raise ValueError("diag_kdn derives its gain from the covariance; negative eigenvalues are unsupported")
150
+ if self.attention_layer_type not in ATTENTION_LAYER_TYPES:
151
+ raise ValueError(
152
+ f"attention_layer_type must be one of {sorted(ATTENTION_LAYER_TYPES)}"
153
+ )
154
+ if self.residual_mode not in RESIDUAL_MODES:
155
+ raise ValueError(f"residual_mode must be one of {sorted(RESIDUAL_MODES)}")
156
+ gated = self.residual_mode == "gated_residual"
157
+ if gated:
158
+ if self.residual_branches < 2:
159
+ raise ValueError("gated_residual needs at least two residual_branches")
160
+ if self.residual_gate_rank <= 0:
161
+ raise ValueError("residual_gate_rank must be positive")
162
+ if self.use_block_attn_res:
163
+ raise ValueError("gated_residual replaces block attention residuals")
164
+ if self.mtp_num_heads:
165
+ raise ValueError("gated_residual models do not support MTP heads")
166
+ if self.shared_layer_indices:
167
+ raise ValueError("gated_residual models do not support shared layers")
168
+ if self.linear_layer_type != "gdn2" or self.attention_layer_type != "parallax":
169
+ raise ValueError("gated_residual models pair gdn2 with parallax attention")
170
+ elif self.attention_layer_type == "parallax" or self.ngram_orders:
171
+ raise ValueError("parallax attention and n-gram memory need residual_mode 'gated_residual'")
172
+ if self.linear_full_rank_gate and self.linear_layer_type != "gdn2":
173
+ raise ValueError("linear_full_rank_gate applies to gdn2 layers")
174
+ if self.ngram_orders:
175
+ if any(order < 2 for order in self.ngram_orders):
176
+ raise ValueError("ngram_orders must be at least 2")
177
+ if tuple(sorted(set(self.ngram_orders))) != tuple(self.ngram_orders):
178
+ raise ValueError("ngram_orders must be unique and ascending")
179
+ if self.ngram_heads_per_order <= 0 or self.ngram_embedding_dim <= 0:
180
+ raise ValueError("n-gram heads and embedding width must be positive")
181
+ if self.ngram_table_rows <= self.vocab_size:
182
+ raise ValueError("ngram_table_rows must exceed the vocabulary")
183
+ if not 0 <= self.ngram_layer_index < self.num_hidden_layers:
184
+ raise ValueError("ngram_layer_index must name a block")
185
+ if self.ngram_conv_kernel <= 0:
186
+ raise ValueError("ngram_conv_kernel must be positive")
187
+ if self.mlp_activation not in {"swiglu", "situ_glu"}:
188
+ raise ValueError("mlp_activation must be 'swiglu' or 'situ_glu'")
189
+ if self.mla_kv_lora_rank <= 0:
190
+ raise ValueError("mla_kv_lora_rank must be positive")
191
+ if self.mla_q_lora_rank is not None and self.mla_q_lora_rank <= 0:
192
+ raise ValueError("mla_q_lora_rank must be positive or None")
193
+ if self.mla_qk_nope_head_dim <= 0 or self.mla_v_head_dim <= 0:
194
+ raise ValueError("MLA head dimensions must be positive")
195
+ if self.kda_lower_bound >= 0.0:
196
+ raise ValueError("kda_lower_bound must be negative log-decay")
197
+ if self.situ_gate_cap <= 0.0 or self.situ_up_cap <= 0.0:
198
+ raise ValueError("SiTU caps must be positive")
199
+
200
+ @property
201
+ def layer_types(self) -> tuple[str, ...]:
202
+ return tuple(
203
+ self.attention_layer_type
204
+ if (index + 1) % self.full_attention_interval == 0
205
+ else self.linear_layer_type
206
+ for index in range(self.num_hidden_layers)
207
+ )
208
+
209
+ @property
210
+ def rotary_dim(self) -> int:
211
+ return int(self.attention_head_dim * self.partial_rotary_factor)
212
+
213
+ @property
214
+ def effective_num_layers(self) -> int:
215
+ return self.num_hidden_layers + len(self.shared_layer_indices)
216
+
217
+ @property
218
+ def ngram_table_count(self) -> int:
219
+ return len(self.ngram_orders) * self.ngram_heads_per_order
220
+
221
+ @property
222
+ def ngram_memory_dim(self) -> int:
223
+ return self.ngram_table_count * self.ngram_embedding_dim
224
+
225
+ def to_dict(self) -> dict[str, Any]:
226
+ payload = asdict(self)
227
+ payload["layer_types"] = list(self.layer_types)
228
+ return payload
229
+
230
+ def save_json(self, path: Path) -> None:
231
+ path.parent.mkdir(parents=True, exist_ok=True)
232
+ path.write_text(
233
+ json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n",
234
+ encoding="utf-8",
235
+ )
236
+
237
+ @classmethod
238
+ def from_json(cls, path: Path) -> TinyGDNConfig:
239
+ payload = json.loads(path.read_text(encoding="utf-8"))
240
+ payload.pop("layer_types", None)
241
+ for name in ("shared_layer_indices", "ngram_orders"):
242
+ if name in payload:
243
+ payload[name] = tuple(payload[name])
244
+ allowed = {item.name for item in fields(cls)}
245
+ return cls(**{key: value for key, value in payload.items() if key in allowed})
246
+
247
+
248
+ def haiku_config(**overrides: Any) -> TinyGDNConfig:
249
+ """650M Haiku: 3×KDA + 1×Gated-MLA, AttnRes, SiTU-GLU, MTP."""
250
+
251
+ payload = {
252
+ "architecture": "HaikuForCausalLM",
253
+ "model_type": "haiku",
254
+ "vocab_size": 65_536,
255
+ "hidden_size": 1024,
256
+ "intermediate_size": 3840,
257
+ "num_hidden_layers": 36,
258
+ "num_attention_heads": 8,
259
+ "num_key_value_heads": 8,
260
+ "attention_head_dim": 128,
261
+ "full_attention_interval": 4,
262
+ "linear_num_heads": 8,
263
+ "linear_num_value_heads": 8,
264
+ "linear_head_dim": 128,
265
+ "linear_layer_type": "kda",
266
+ "attention_layer_type": "gated_mla",
267
+ "mlp_activation": "situ_glu",
268
+ "use_block_attn_res": True,
269
+ "mtp_num_heads": 2,
270
+ "mtp_adapter_rank": 128,
271
+ "mtp_loss_weight": 0.2,
272
+ "max_position_embeddings": 32_768,
273
+ "training_sequence_length": 2048,
274
+ }
275
+ payload.update(overrides)
276
+ return TinyGDNConfig(**payload)
277
+
278
+
279
+ def haiku_kdn_config(**overrides: Any) -> TinyGDNConfig:
280
+ """Haiku with Diagonal KDN in place of KDA in the 27 linear layers.
281
+
282
+ Opt-in: at equal tokens it trailed KDA in Haiku pilots and trains ~23%
283
+ slower at full depth (docs/architecture.md, "Haiku v2").
284
+ """
285
+
286
+ return haiku_config(**{"linear_layer_type": "diag_kdn", **overrides})
287
+
288
+
289
+ def senryu_config(**overrides: Any) -> TinyGDNConfig:
290
+ """800M Senryu: 3×Gated DeltaNet-2 + 1×Gated-MLA over 44 layers, AttnRes, SiTU-GLU.
291
+
292
+ Haiku's width, heads, tokenizer, and residual design with GDN-2's
293
+ channel-wise erase and write gates in the 33 linear layers. A rank-512
294
+ query LoRA costs as many parameters as a full 1024×1024 query, so queries
295
+ are full rank, and the KV latent doubles to 512. The feed-forward narrows
296
+ to 3392 to pay for the depth. Next-token only: MTP has no pilot win at
297
+ this scale (docs/architecture.md, "Senryu").
298
+ """
299
+
300
+ return haiku_config(
301
+ **{
302
+ "architecture": "SenryuForCausalLM",
303
+ "model_type": "senryu",
304
+ "intermediate_size": 3392,
305
+ "num_hidden_layers": 44,
306
+ "linear_layer_type": "gdn2",
307
+ "mla_q_lora_rank": None,
308
+ "mla_kv_lora_rank": 512,
309
+ "mtp_num_heads": 0,
310
+ "mtp_loss_weight": 0.0,
311
+ **overrides,
312
+ }
313
+ )
314
+
315
+
316
+ def senryu2_1b_config(**overrides: Any) -> TinyGDNConfig:
317
+ """Senryu-2-1B: a 1.09B Senryu-2 backbone plus a 2.2B host-side n-gram memory.
318
+
319
+ 28 layers of 3×Gated DeltaNet-2 (full-rank output gate) + 1×Parallax
320
+ attention, width 1536, SiTU-GLU 3584, a 4-branch gated residual stream,
321
+ and orders-2/3 hashed n-gram tables injected before block 1
322
+ (docs/architecture.md, "Senryu-2-1B").
323
+ """
324
+
325
+ payload: dict[str, Any] = {
326
+ "architecture": "Senryu2ForCausalLM",
327
+ "model_type": "senryu2",
328
+ "vocab_size": 65_536,
329
+ "hidden_size": 1536,
330
+ "intermediate_size": 3584,
331
+ "num_hidden_layers": 28,
332
+ "num_attention_heads": 12,
333
+ "num_key_value_heads": 4,
334
+ "attention_head_dim": 128,
335
+ "full_attention_interval": 4,
336
+ "partial_rotary_factor": 0.5,
337
+ "rope_theta": 1_000_000.0,
338
+ "linear_num_heads": 12,
339
+ "linear_num_value_heads": 12,
340
+ "linear_head_dim": 128,
341
+ "linear_layer_type": "gdn2",
342
+ "attention_layer_type": "parallax",
343
+ "mlp_activation": "situ_glu",
344
+ "residual_mode": "gated_residual",
345
+ "residual_branches": 4,
346
+ "residual_gate_rank": 128,
347
+ "linear_full_rank_gate": True,
348
+ "ngram_orders": (2, 3),
349
+ "ngram_heads_per_order": 4,
350
+ "ngram_table_rows": 2_097_152,
351
+ "ngram_embedding_dim": 128,
352
+ "ngram_layer_index": 1,
353
+ "ngram_conv_kernel": 4,
354
+ "max_position_embeddings": 32_768,
355
+ "training_sequence_length": 32_768,
356
+ "mtp_num_heads": 0,
357
+ "mtp_loss_weight": 0.0,
358
+ }
359
+ payload.update(overrides)
360
+ return TinyGDNConfig(**payload)
361
+
362
+
363
+ def prompttercet_config(**overrides: Any) -> TinyGDNConfig:
364
+ """PromptTercet: a 501M Senryu-2 prompter, which writes the user's side of a chat.
365
+
366
+ Senryu-2-1B's layout at width 1024: 24 layers of 3×Gated DeltaNet-2 +
367
+ 1×Parallax attention, SiTU-GLU 2816, 8 query and 4 KV heads, and n-gram
368
+ tables of 1,048,576 rows, 1.09B host-side parameters, half of Senryu-2-1B's
369
+ (docs/architecture.md, "PromptTercet").
370
+ """
371
+
372
+ return senryu2_1b_config(
373
+ **{
374
+ "hidden_size": 1024,
375
+ "intermediate_size": 2816,
376
+ "num_hidden_layers": 24,
377
+ "num_attention_heads": 8,
378
+ "num_key_value_heads": 4,
379
+ "linear_num_heads": 8,
380
+ "linear_num_value_heads": 8,
381
+ "ngram_table_rows": 1_048_576,
382
+ **overrides,
383
+ }
384
+ )
tiny_gdn/detokenize.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Byte-accurate incremental decode for GPT-2-style byte-level BPE.
2
+
3
+ `tokenizer.decode(ids)` UTF-8-replaces incomplete sequences. Streaming that
4
+ as a string prefix then breaks on the next byte: decode([20492]) is a
5
+ replacement character and decode([20492, 294]) is `` ≈``, so the
6
+ accumulated text is no longer a prefix and the UI re-emits the whole
7
+ think block.
8
+
9
+ This decoder concatenates raw BPE bytes and only emits complete UTF-8
10
+ characters. The completing byte of ``≈`` yields `` ≈``; nothing is rewound.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Iterable, Mapping, Sequence
16
+ from typing import Any
17
+
18
+
19
+ def gpt2_bytes_to_unicode() -> dict[int, str]:
20
+ raw = (
21
+ list(range(ord("!"), ord("~") + 1))
22
+ + list(range(ord("¡"), ord("¬") + 1))
23
+ + list(range(ord("®"), ord("ÿ") + 1))
24
+ )
25
+ mapped = raw[:]
26
+ extra = 0
27
+ for byte in range(256):
28
+ if byte not in raw:
29
+ raw.append(byte)
30
+ mapped.append(256 + extra)
31
+ extra += 1
32
+ return dict(zip(raw, [chr(code) for code in mapped], strict=True))
33
+
34
+
35
+ def unicode_to_gpt2_bytes() -> dict[str, int]:
36
+ return {char: byte for byte, char in gpt2_bytes_to_unicode().items()}
37
+
38
+
39
+ def utf8_char_length(lead: int) -> int | None:
40
+ if lead < 0x80:
41
+ return 1
42
+ if 0xC2 <= lead <= 0xDF:
43
+ return 2
44
+ if 0xE0 <= lead <= 0xEF:
45
+ return 3
46
+ if 0xF0 <= lead <= 0xF4:
47
+ return 4
48
+ return None
49
+
50
+
51
+ def split_complete_utf8(buffer: bytes) -> tuple[str, bytes]:
52
+ """Return (decoded prefix, leftover incomplete or invalid-lead bytes)."""
53
+ index = 0
54
+ end = len(buffer)
55
+ while index < end:
56
+ size = utf8_char_length(buffer[index])
57
+ if size is None:
58
+ break
59
+ if index + size > end:
60
+ break
61
+ chunk = buffer[index : index + size]
62
+ try:
63
+ chunk.decode("utf-8")
64
+ except UnicodeDecodeError:
65
+ break
66
+ index += size
67
+ if index == 0:
68
+ return "", buffer
69
+ return buffer[:index].decode("utf-8"), buffer[index:]
70
+
71
+
72
+ def piece_to_bytes(piece: str, unicode_to_byte: Mapping[str, int]) -> bytes:
73
+ raw = bytearray()
74
+ for char in piece:
75
+ mapped = unicode_to_byte.get(char)
76
+ if mapped is None:
77
+ raw.extend(char.encode("utf-8"))
78
+ else:
79
+ raw.append(mapped)
80
+ return bytes(raw)
81
+
82
+
83
+ class IncrementalUtf8Decoder:
84
+ """Push token ids; read only complete Unicode as it becomes available."""
85
+
86
+ def __init__(
87
+ self,
88
+ tokenizer: Any,
89
+ *,
90
+ skip_special_ids: Iterable[int] | None = None,
91
+ ) -> None:
92
+ vocab = tokenizer.get_vocab()
93
+ self._id_to_piece = {tid: piece for piece, tid in vocab.items()}
94
+ self._unicode_to_byte = unicode_to_gpt2_bytes()
95
+ self._skip_special_ids = set(skip_special_ids or ())
96
+ self._pending = b""
97
+ self._text = ""
98
+
99
+ @property
100
+ def text(self) -> str:
101
+ return self._text
102
+
103
+ def reset(self) -> None:
104
+ self._pending = b""
105
+ self._text = ""
106
+
107
+ def token_bytes(self, token_id: int) -> bytes:
108
+ piece = self._id_to_piece.get(token_id, "")
109
+ return piece_to_bytes(piece, self._unicode_to_byte)
110
+
111
+ def push(self, token_id: int) -> str:
112
+ if token_id in self._skip_special_ids:
113
+ return ""
114
+ self._pending += self.token_bytes(token_id)
115
+ complete, self._pending = split_complete_utf8(self._pending)
116
+ self._text += complete
117
+ return complete
118
+
119
+ def push_many(self, token_ids: Sequence[int]) -> str:
120
+ delta = []
121
+ for token_id in token_ids:
122
+ piece = self.push(token_id)
123
+ if piece:
124
+ delta.append(piece)
125
+ return "".join(delta)
126
+
127
+ def finalize(self) -> str:
128
+ if self._pending:
129
+ self._text += self._pending.decode("utf-8", errors="replace")
130
+ self._pending = b""
131
+ return self._text
tiny_gdn/fused_ops.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fused CUDA kernels for memory-bound blocks: SiTU-GLU, the LM loss, token log-probs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import torch
6
+ import triton
7
+ import triton.language as tl
8
+ from triton.language.extra import libdevice
9
+
10
+ from tiny_gdn.nn_common import (
11
+ linear_cross_entropy_reference,
12
+ linear_token_logprobs_reference,
13
+ situ_glu_reference,
14
+ )
15
+
16
+ BLOCK_SIZE = 1024
17
+ VOCAB_BLOCK_SIZE = 4096
18
+ LOGITS_CHUNK_BYTES = 1 << 30
19
+
20
+
21
+ @triton.jit
22
+ def _situ_glu_forward_kernel(
23
+ gate_up,
24
+ output,
25
+ total,
26
+ width,
27
+ gate_cap,
28
+ up_cap,
29
+ BLOCK: tl.constexpr,
30
+ ):
31
+ offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
32
+ mask = offsets < total
33
+ row = offsets // width
34
+ gate_offsets = offsets + row * width
35
+ gate = tl.load(gate_up + gate_offsets, mask=mask, other=0.0).to(tl.float32)
36
+ up = tl.load(gate_up + gate_offsets + width, mask=mask, other=0.0).to(tl.float32)
37
+ gated = gate_cap * libdevice.tanh(gate / gate_cap) * tl.sigmoid(gate)
38
+ result = gated * up_cap * libdevice.tanh(up / up_cap)
39
+ tl.store(output + offsets, result.to(output.dtype.element_ty), mask=mask)
40
+
41
+
42
+ @triton.jit
43
+ def _situ_glu_backward_kernel(
44
+ gate_up,
45
+ grad_output,
46
+ grad_gate_up,
47
+ total,
48
+ width,
49
+ gate_cap,
50
+ up_cap,
51
+ BLOCK: tl.constexpr,
52
+ ):
53
+ offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK)
54
+ mask = offsets < total
55
+ row = offsets // width
56
+ gate_offsets = offsets + row * width
57
+ gate = tl.load(gate_up + gate_offsets, mask=mask, other=0.0).to(tl.float32)
58
+ up = tl.load(gate_up + gate_offsets + width, mask=mask, other=0.0).to(tl.float32)
59
+ grad = tl.load(grad_output + offsets, mask=mask, other=0.0).to(tl.float32)
60
+ gate_tanh = libdevice.tanh(gate / gate_cap)
61
+ up_tanh = libdevice.tanh(up / up_cap)
62
+ sigmoid = tl.sigmoid(gate)
63
+ gated = gate_cap * gate_tanh * sigmoid
64
+ capped_up = up_cap * up_tanh
65
+ gate_slope = sigmoid * ((1.0 - gate_tanh * gate_tanh) + gate_cap * gate_tanh * (1.0 - sigmoid))
66
+ grad_gate = grad * capped_up * gate_slope
67
+ grad_up = grad * gated * (1.0 - up_tanh * up_tanh)
68
+ dtype = grad_gate_up.dtype.element_ty
69
+ tl.store(grad_gate_up + gate_offsets, grad_gate.to(dtype), mask=mask)
70
+ tl.store(grad_gate_up + gate_offsets + width, grad_up.to(dtype), mask=mask)
71
+
72
+
73
+ def _launch_grid(total: int) -> tuple[int]:
74
+ return (triton.cdiv(total, BLOCK_SIZE),)
75
+
76
+
77
+ class _SiTUGLUFunction(torch.autograd.Function):
78
+ @staticmethod
79
+ def forward(ctx, gate_up: torch.Tensor, gate_cap: float, up_cap: float) -> torch.Tensor:
80
+ gate_up = gate_up.contiguous()
81
+ width = gate_up.shape[-1] // 2
82
+ output = gate_up.new_empty((*gate_up.shape[:-1], width))
83
+ total = output.numel()
84
+ if total:
85
+ _situ_glu_forward_kernel[_launch_grid(total)](
86
+ gate_up, output, total, width, gate_cap, up_cap, BLOCK=BLOCK_SIZE
87
+ )
88
+ ctx.save_for_backward(gate_up)
89
+ ctx.caps = (gate_cap, up_cap)
90
+ return output
91
+
92
+ @staticmethod
93
+ def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
94
+ (gate_up,) = ctx.saved_tensors
95
+ gate_cap, up_cap = ctx.caps
96
+ grad_output = grad_output.contiguous()
97
+ grad_gate_up = torch.empty_like(gate_up)
98
+ width = gate_up.shape[-1] // 2
99
+ total = grad_output.numel()
100
+ if total:
101
+ _situ_glu_backward_kernel[_launch_grid(total)](
102
+ gate_up,
103
+ grad_output,
104
+ grad_gate_up,
105
+ total,
106
+ width,
107
+ gate_cap,
108
+ up_cap,
109
+ BLOCK=BLOCK_SIZE,
110
+ )
111
+ return grad_gate_up, None, None
112
+
113
+
114
+ def situ_glu(gate_up: torch.Tensor, gate_cap: float, up_cap: float) -> torch.Tensor:
115
+ """``softcap(gate) * sigmoid(gate) * softcap(up)`` over ``[..., gate | up]``.
116
+
117
+ The CUDA path evaluates in FP32 and rounds once; backward recomputes the
118
+ activations from ``gate_up`` instead of saving intermediates.
119
+ """
120
+
121
+ if gate_up.shape[-1] % 2:
122
+ raise ValueError("gate_up must have an even last dimension")
123
+ if not gate_up.is_cuda:
124
+ return situ_glu_reference(gate_up, gate_cap, up_cap)
125
+ return _SiTUGLUFunction.apply(gate_up, gate_cap, up_cap)
126
+
127
+
128
+ @triton.jit
129
+ def _cross_entropy_rows_kernel(
130
+ logits,
131
+ targets,
132
+ losses,
133
+ log_partitions,
134
+ valid_count,
135
+ row_stride,
136
+ vocab_size,
137
+ z_loss_coefficient,
138
+ ignore_index,
139
+ COMPUTE_GRAD: tl.constexpr,
140
+ BLOCK: tl.constexpr,
141
+ ):
142
+ """Per row: logsumexp and NLL; optionally overwrite the row with d(mean loss)/d(logits)."""
143
+
144
+ row = tl.program_id(0).to(tl.int64)
145
+ row_logits = logits + row * row_stride
146
+ target = tl.load(targets + row)
147
+ columns = tl.arange(0, BLOCK)
148
+ if target == ignore_index:
149
+ tl.store(losses + row, 0.0)
150
+ tl.store(log_partitions + row, 0.0)
151
+ if COMPUTE_GRAD:
152
+ for start in range(0, vocab_size, BLOCK):
153
+ offsets = start + columns
154
+ zeros = tl.zeros((BLOCK,), dtype=logits.dtype.element_ty)
155
+ tl.store(row_logits + offsets, zeros, mask=offsets < vocab_size)
156
+ else:
157
+ running_max = tl.full((), float("-inf"), tl.float32)
158
+ running_sum = tl.zeros((), dtype=tl.float32)
159
+ for start in range(0, vocab_size, BLOCK):
160
+ offsets = start + columns
161
+ values = tl.load(
162
+ row_logits + offsets, mask=offsets < vocab_size, other=float("-inf")
163
+ ).to(tl.float32)
164
+ new_max = tl.maximum(running_max, tl.max(values, axis=0))
165
+ running_sum = running_sum * tl.exp(running_max - new_max) + tl.sum(
166
+ tl.exp(values - new_max), axis=0
167
+ )
168
+ running_max = new_max
169
+ log_partition = running_max + tl.log(running_sum)
170
+ target_logit = tl.load(row_logits + target).to(tl.float32)
171
+ tl.store(losses + row, log_partition - target_logit)
172
+ tl.store(log_partitions + row, log_partition)
173
+ if COMPUTE_GRAD:
174
+ grad_scale = 1.0 / tl.load(valid_count).to(tl.float32)
175
+ softmax_scale = grad_scale * (1.0 + 2.0 * z_loss_coefficient * log_partition)
176
+ for start in range(0, vocab_size, BLOCK):
177
+ offsets = start + columns
178
+ in_vocab = offsets < vocab_size
179
+ values = tl.load(row_logits + offsets, mask=in_vocab, other=0.0).to(tl.float32)
180
+ grad = tl.exp(values - log_partition) * softmax_scale
181
+ grad = tl.where(offsets == target, grad - grad_scale, grad)
182
+ tl.store(row_logits + offsets, grad.to(logits.dtype.element_ty), mask=in_vocab)
183
+
184
+
185
+ class _LinearCrossEntropyFunction(torch.autograd.Function):
186
+ """Chunked ``states @ weight.T`` + cross-entropy + z-loss with gradients precomputed.
187
+
188
+ Each logits chunk is consumed in place, so peak extra memory is one chunk
189
+ instead of ``[tokens, vocab]`` logits plus their softmax for backward.
190
+ """
191
+
192
+ @staticmethod
193
+ def forward(
194
+ ctx,
195
+ states: torch.Tensor,
196
+ weight: torch.Tensor,
197
+ targets: torch.Tensor,
198
+ z_loss_coefficient: float,
199
+ ignore_index: int,
200
+ compute_grad: bool,
201
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
202
+ states = states.contiguous()
203
+ targets = targets.contiguous()
204
+ rows, vocab_size = states.shape[0], weight.shape[0]
205
+ valid = targets.ne(ignore_index)
206
+ valid_count = valid.sum(dtype=torch.float32)
207
+ losses = states.new_empty(rows, dtype=torch.float32)
208
+ log_partitions = states.new_empty(rows, dtype=torch.float32)
209
+ grad_states = torch.empty_like(states) if compute_grad else None
210
+ grad_weight = (
211
+ torch.zeros(weight.shape, dtype=torch.float32, device=weight.device)
212
+ if compute_grad
213
+ else None
214
+ )
215
+ chunk_rows = max(1, LOGITS_CHUNK_BYTES // (vocab_size * states.element_size()))
216
+ for start in range(0, rows, chunk_rows):
217
+ end = min(start + chunk_rows, rows)
218
+ chunk = states[start:end]
219
+ logits = chunk @ weight.t()
220
+ _cross_entropy_rows_kernel[(end - start,)](
221
+ logits,
222
+ targets[start:end],
223
+ losses[start:end],
224
+ log_partitions[start:end],
225
+ valid_count,
226
+ logits.stride(0),
227
+ vocab_size,
228
+ z_loss_coefficient,
229
+ ignore_index,
230
+ COMPUTE_GRAD=compute_grad,
231
+ BLOCK=VOCAB_BLOCK_SIZE,
232
+ num_warps=8,
233
+ )
234
+ if compute_grad:
235
+ torch.mm(logits, weight, out=grad_states[start:end])
236
+ if chunk.dtype == torch.float32:
237
+ grad_weight.addmm_(logits.t(), chunk)
238
+ else:
239
+ torch.addmm(
240
+ grad_weight, logits.t(), chunk, out_dtype=torch.float32, out=grad_weight
241
+ )
242
+ cross_entropy = losses.sum() / valid_count
243
+ z_loss = log_partitions.square().sum() / valid_count
244
+ objective = cross_entropy + z_loss_coefficient * z_loss
245
+ if compute_grad:
246
+ ctx.save_for_backward(grad_states, grad_weight)
247
+ ctx.weight_dtype = weight.dtype
248
+ ctx.mark_non_differentiable(cross_entropy, z_loss)
249
+ return objective, cross_entropy, z_loss
250
+
251
+ @staticmethod
252
+ def backward(
253
+ ctx, grad_objective: torch.Tensor, *_: torch.Tensor
254
+ ) -> tuple[torch.Tensor, torch.Tensor, None, None, None, None]:
255
+ grad_states, grad_weight = ctx.saved_tensors
256
+ scale = grad_objective.to(torch.float32)
257
+ grad_states = (grad_states * scale).to(grad_states.dtype)
258
+ grad_weight = (grad_weight * scale).to(ctx.weight_dtype)
259
+ return grad_states, grad_weight, None, None, None, None
260
+
261
+
262
+ def linear_cross_entropy(
263
+ states: torch.Tensor,
264
+ weight: torch.Tensor,
265
+ targets: torch.Tensor,
266
+ *,
267
+ z_loss_coefficient: float = 0.0,
268
+ ignore_index: int = -100,
269
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
270
+ """Mean ``cross_entropy(states @ weight.T, targets)`` without full logits.
271
+
272
+ Returns ``(objective, cross_entropy, z_loss)``. Only ``objective =
273
+ cross_entropy + z_loss_coefficient * z_loss`` carries gradients; ``z_loss``
274
+ is the mean squared log-partition over non-ignored targets.
275
+ """
276
+
277
+ if states.ndim != 2 or targets.shape != states.shape[:1]:
278
+ raise ValueError("states must be [tokens, hidden] and targets [tokens]")
279
+ if not states.is_cuda:
280
+ return linear_cross_entropy_reference(
281
+ states,
282
+ weight,
283
+ targets,
284
+ z_loss_coefficient=z_loss_coefficient,
285
+ ignore_index=ignore_index,
286
+ )
287
+ compute_grad = torch.is_grad_enabled() and (states.requires_grad or weight.requires_grad)
288
+ return _LinearCrossEntropyFunction.apply(
289
+ states, weight, targets, z_loss_coefficient, ignore_index, compute_grad
290
+ )
291
+
292
+
293
+ @triton.jit
294
+ def _token_logprob_grad_rows_kernel(
295
+ logits,
296
+ targets,
297
+ log_partitions,
298
+ row_grads,
299
+ row_stride,
300
+ vocab_size,
301
+ ignore_index,
302
+ BLOCK: tl.constexpr,
303
+ ):
304
+ """Overwrite each row with ``g * (onehot(target) - softmax)``, the gradient of ``g * log p``."""
305
+
306
+ row = tl.program_id(0).to(tl.int64)
307
+ row_logits = logits + row * row_stride
308
+ target = tl.load(targets + row)
309
+ columns = tl.arange(0, BLOCK)
310
+ if target == ignore_index:
311
+ for start in range(0, vocab_size, BLOCK):
312
+ offsets = start + columns
313
+ zeros = tl.zeros((BLOCK,), dtype=logits.dtype.element_ty)
314
+ tl.store(row_logits + offsets, zeros, mask=offsets < vocab_size)
315
+ else:
316
+ scale = tl.load(row_grads + row).to(tl.float32)
317
+ log_partition = tl.load(log_partitions + row)
318
+ for start in range(0, vocab_size, BLOCK):
319
+ offsets = start + columns
320
+ in_vocab = offsets < vocab_size
321
+ values = tl.load(row_logits + offsets, mask=in_vocab, other=0.0).to(tl.float32)
322
+ grad = -scale * tl.exp(values - log_partition)
323
+ grad = tl.where(offsets == target, grad + scale, grad)
324
+ tl.store(row_logits + offsets, grad.to(logits.dtype.element_ty), mask=in_vocab)
325
+
326
+
327
+ class _LinearTokenLogprobFunction(torch.autograd.Function):
328
+ """Per-row ``log_softmax(states @ weight.T)[target]`` without keeping logits.
329
+
330
+ Preference losses weight every sequence differently, so the gradient
331
+ cannot be precomputed in forward like the mean LM loss. Forward keeps one
332
+ log-partition per row; backward recomputes each logits chunk and turns it
333
+ into the scaled softmax gradient in place.
334
+ """
335
+
336
+ @staticmethod
337
+ def forward(
338
+ ctx,
339
+ states: torch.Tensor,
340
+ weight: torch.Tensor,
341
+ targets: torch.Tensor,
342
+ ignore_index: int,
343
+ ) -> torch.Tensor:
344
+ states = states.contiguous()
345
+ targets = targets.contiguous()
346
+ rows, vocab_size = states.shape[0], weight.shape[0]
347
+ negative_logprobs = states.new_empty(rows, dtype=torch.float32)
348
+ log_partitions = states.new_empty(rows, dtype=torch.float32)
349
+ unused_count = states.new_ones((), dtype=torch.float32)
350
+ chunk_rows = max(1, LOGITS_CHUNK_BYTES // (vocab_size * states.element_size()))
351
+ for start in range(0, rows, chunk_rows):
352
+ end = min(start + chunk_rows, rows)
353
+ logits = states[start:end] @ weight.t()
354
+ _cross_entropy_rows_kernel[(end - start,)](
355
+ logits,
356
+ targets[start:end],
357
+ negative_logprobs[start:end],
358
+ log_partitions[start:end],
359
+ unused_count,
360
+ logits.stride(0),
361
+ vocab_size,
362
+ 0.0,
363
+ ignore_index,
364
+ COMPUTE_GRAD=False,
365
+ BLOCK=VOCAB_BLOCK_SIZE,
366
+ num_warps=8,
367
+ )
368
+ ctx.save_for_backward(states, weight, targets, log_partitions)
369
+ ctx.ignore_index = ignore_index
370
+ ctx.chunk_rows = chunk_rows
371
+ return negative_logprobs.neg_()
372
+
373
+ @staticmethod
374
+ def backward(
375
+ ctx, grad_logprobs: torch.Tensor
376
+ ) -> tuple[torch.Tensor | None, torch.Tensor | None, None, None]:
377
+ states, weight, targets, log_partitions = ctx.saved_tensors
378
+ row_grads = grad_logprobs.to(torch.float32).contiguous()
379
+ rows, vocab_size = states.shape[0], weight.shape[0]
380
+ grad_states = torch.empty_like(states) if ctx.needs_input_grad[0] else None
381
+ grad_weight = (
382
+ torch.zeros(weight.shape, dtype=torch.float32, device=weight.device)
383
+ if ctx.needs_input_grad[1]
384
+ else None
385
+ )
386
+ for start in range(0, rows, ctx.chunk_rows):
387
+ end = min(start + ctx.chunk_rows, rows)
388
+ chunk = states[start:end]
389
+ logits = chunk @ weight.t()
390
+ _token_logprob_grad_rows_kernel[(end - start,)](
391
+ logits,
392
+ targets[start:end],
393
+ log_partitions[start:end],
394
+ row_grads[start:end],
395
+ logits.stride(0),
396
+ vocab_size,
397
+ ctx.ignore_index,
398
+ BLOCK=VOCAB_BLOCK_SIZE,
399
+ num_warps=8,
400
+ )
401
+ if grad_states is not None:
402
+ torch.mm(logits, weight, out=grad_states[start:end])
403
+ if grad_weight is not None:
404
+ if chunk.dtype == torch.float32:
405
+ grad_weight.addmm_(logits.t(), chunk)
406
+ else:
407
+ torch.addmm(
408
+ grad_weight, logits.t(), chunk, out_dtype=torch.float32, out=grad_weight
409
+ )
410
+ return (
411
+ grad_states,
412
+ None if grad_weight is None else grad_weight.to(weight.dtype),
413
+ None,
414
+ None,
415
+ )
416
+
417
+
418
+ def linear_token_logprobs(
419
+ states: torch.Tensor,
420
+ weight: torch.Tensor,
421
+ targets: torch.Tensor,
422
+ *,
423
+ ignore_index: int = -100,
424
+ ) -> torch.Tensor:
425
+ """fp32 ``log_softmax(states @ weight.T)[row, target]`` per row without full logits.
426
+
427
+ Rows whose target is ``ignore_index`` return 0 and receive no gradient.
428
+ """
429
+
430
+ if states.ndim != 2 or targets.shape != states.shape[:1]:
431
+ raise ValueError("states must be [tokens, hidden] and targets [tokens]")
432
+ if not states.is_cuda:
433
+ return linear_token_logprobs_reference(
434
+ states, weight, targets, ignore_index=ignore_index
435
+ )
436
+ return _LinearTokenLogprobFunction.apply(states, weight, targets, ignore_index)
tiny_gdn/gated_residual_ops.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fused CUDA kernels for Senryu-2's gated residual read and write.
2
+
3
+ The read normalizes every branch, gates it through a rank-``r`` bottleneck over
4
+ all branches and averages the gated branches; the write adds one scaled update
5
+ to every branch. The bottleneck GEMMs run on cuBLAS and every elementwise or
6
+ reduction stage around them is a single Triton pass over the branches, which
7
+ replaces dozens of memory-bound PyTorch ops per read on 32k-token rows.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+ import triton
15
+ import triton.language as tl
16
+
17
+ GEMM_ALIGNMENT = 8
18
+ COLUMN_BLOCK = 512
19
+ GRAD_ROWS_PER_PROGRAM = 32
20
+
21
+
22
+ def _warps(block: int) -> int:
23
+ return 8 if block >= 2048 else 4
24
+
25
+
26
+ @triton.jit
27
+ def _read_normalize_kernel(
28
+ residual,
29
+ gain,
30
+ flat,
31
+ rstd,
32
+ hidden_size,
33
+ eps,
34
+ BRANCHES: tl.constexpr,
35
+ BLOCK: tl.constexpr,
36
+ ):
37
+ vector = tl.program_id(0).to(tl.int64)
38
+ branch = vector % BRANCHES
39
+ columns = tl.arange(0, BLOCK)
40
+ mask = columns < hidden_size
41
+ offsets = vector * hidden_size + columns
42
+ values = tl.load(residual + offsets, mask=mask, other=0.0).to(tl.float32)
43
+ inverse_rms = tl.rsqrt(tl.sum(values * values, axis=0) / hidden_size + eps)
44
+ scale = tl.load(gain + branch * hidden_size + columns, mask=mask, other=0.0)
45
+ tl.store(rstd + vector, inverse_rms)
46
+ tl.store(flat + offsets, (values * inverse_rms * scale).to(flat.dtype.element_ty), mask=mask)
47
+
48
+
49
+ @triton.jit
50
+ def _read_combine_kernel(
51
+ residual,
52
+ rstd,
53
+ gain,
54
+ gate_logits,
55
+ out,
56
+ hidden_size,
57
+ BRANCHES: tl.constexpr,
58
+ BLOCK: tl.constexpr,
59
+ ):
60
+ row = tl.program_id(0).to(tl.int64)
61
+ columns = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
62
+ mask = columns < hidden_size
63
+ total = tl.zeros([BLOCK], dtype=tl.float32)
64
+ for branch in tl.static_range(BRANCHES):
65
+ vector = row * BRANCHES + branch
66
+ offsets = vector * hidden_size + columns
67
+ values = tl.load(residual + offsets, mask=mask, other=0.0).to(tl.float32)
68
+ logits = tl.load(gate_logits + offsets, mask=mask, other=0.0).to(tl.float32)
69
+ scale = tl.load(gain + branch * hidden_size + columns, mask=mask, other=0.0)
70
+ total += tl.sigmoid(logits) * (values * tl.load(rstd + vector) * scale)
71
+ tl.store(out + row * hidden_size + columns, (total / BRANCHES).to(out.dtype.element_ty), mask=mask)
72
+
73
+
74
+ @triton.jit
75
+ def _read_backward_gates_kernel(
76
+ residual,
77
+ rstd,
78
+ gain,
79
+ gate_logits,
80
+ grad_out,
81
+ flat,
82
+ grad_gate_logits,
83
+ hidden_size,
84
+ BRANCHES: tl.constexpr,
85
+ BLOCK: tl.constexpr,
86
+ ):
87
+ vector = tl.program_id(0).to(tl.int64)
88
+ row = vector // BRANCHES
89
+ branch = vector % BRANCHES
90
+ columns = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
91
+ mask = columns < hidden_size
92
+ offsets = vector * hidden_size + columns
93
+ values = tl.load(residual + offsets, mask=mask, other=0.0).to(tl.float32)
94
+ scale = tl.load(gain + branch * hidden_size + columns, mask=mask, other=0.0)
95
+ hat = values * tl.load(rstd + vector) * scale
96
+ gates = tl.sigmoid(tl.load(gate_logits + offsets, mask=mask, other=0.0).to(tl.float32))
97
+ grad = tl.load(grad_out + row * hidden_size + columns, mask=mask, other=0.0).to(tl.float32) / BRANCHES
98
+ tl.store(flat + offsets, hat.to(flat.dtype.element_ty), mask=mask)
99
+ grad_logits = grad * hat * gates * (1.0 - gates)
100
+ tl.store(grad_gate_logits + offsets, grad_logits.to(grad_gate_logits.dtype.element_ty), mask=mask)
101
+
102
+
103
+ @triton.jit
104
+ def _read_backward_residual_kernel(
105
+ residual,
106
+ rstd,
107
+ gain,
108
+ gate_logits,
109
+ grad_out,
110
+ grad_flat,
111
+ grad_residual,
112
+ grad_gain_partial,
113
+ rows,
114
+ hidden_size,
115
+ BRANCHES: tl.constexpr,
116
+ ROWS: tl.constexpr,
117
+ BLOCK: tl.constexpr,
118
+ ):
119
+ block = tl.program_id(0).to(tl.int64)
120
+ branch = tl.program_id(1)
121
+ columns = tl.arange(0, BLOCK)
122
+ mask = columns < hidden_size
123
+ scale = tl.load(gain + branch * hidden_size + columns, mask=mask, other=0.0)
124
+ grad_gain = tl.zeros([BLOCK], dtype=tl.float32)
125
+ for index in range(ROWS):
126
+ row = block * ROWS + index
127
+ valid = row < rows
128
+ row_mask = mask & valid
129
+ vector = row * BRANCHES + branch
130
+ offsets = vector * hidden_size + columns
131
+ inverse_rms = tl.load(rstd + vector, mask=valid, other=0.0)
132
+ normalized = tl.load(residual + offsets, mask=row_mask, other=0.0).to(tl.float32) * inverse_rms
133
+ gates = tl.sigmoid(tl.load(gate_logits + offsets, mask=row_mask, other=0.0).to(tl.float32))
134
+ grad = tl.load(grad_out + row * hidden_size + columns, mask=row_mask, other=0.0).to(tl.float32)
135
+ grad_hat = gates * (grad / BRANCHES)
136
+ grad_hat += tl.load(grad_flat + offsets, mask=row_mask, other=0.0).to(tl.float32)
137
+ grad_gain += grad_hat * normalized
138
+ grad_normalized = grad_hat * scale
139
+ mean = tl.sum(grad_normalized * normalized, axis=0) / hidden_size
140
+ result = inverse_rms * (grad_normalized - normalized * mean)
141
+ tl.store(grad_residual + offsets, result.to(grad_residual.dtype.element_ty), mask=row_mask)
142
+ tl.store(grad_gain_partial + (block * BRANCHES + branch) * hidden_size + columns, grad_gain, mask=mask)
143
+
144
+
145
+ @triton.jit
146
+ def _write_forward_kernel(
147
+ residual,
148
+ scales,
149
+ update,
150
+ out,
151
+ hidden_size,
152
+ BRANCHES: tl.constexpr,
153
+ BLOCK: tl.constexpr,
154
+ ):
155
+ row = tl.program_id(0).to(tl.int64)
156
+ columns = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
157
+ mask = columns < hidden_size
158
+ values = tl.load(update + row * hidden_size + columns, mask=mask, other=0.0).to(tl.float32)
159
+ for branch in tl.static_range(BRANCHES):
160
+ vector = row * BRANCHES + branch
161
+ offsets = vector * hidden_size + columns
162
+ scale = tl.load(scales + vector).to(tl.float32)
163
+ written = tl.load(residual + offsets, mask=mask, other=0.0).to(tl.float32) + scale * values
164
+ tl.store(out + offsets, written.to(out.dtype.element_ty), mask=mask)
165
+
166
+
167
+ @triton.jit
168
+ def _write_backward_kernel(
169
+ grad,
170
+ scales,
171
+ update,
172
+ grad_scales,
173
+ grad_update,
174
+ hidden_size,
175
+ BRANCHES: tl.constexpr,
176
+ BLOCK: tl.constexpr,
177
+ ):
178
+ row = tl.program_id(0).to(tl.int64)
179
+ columns = tl.arange(0, BLOCK)
180
+ mask = columns < hidden_size
181
+ values = tl.load(update + row * hidden_size + columns, mask=mask, other=0.0).to(tl.float32)
182
+ total = tl.zeros([BLOCK], dtype=tl.float32)
183
+ for branch in tl.static_range(BRANCHES):
184
+ vector = row * BRANCHES + branch
185
+ incoming = tl.load(grad + vector * hidden_size + columns, mask=mask, other=0.0).to(tl.float32)
186
+ total += incoming * tl.load(scales + vector).to(tl.float32)
187
+ tl.store(grad_scales + vector, tl.sum(incoming * values, axis=0).to(grad_scales.dtype.element_ty))
188
+ tl.store(grad_update + row * hidden_size + columns, total.to(grad_update.dtype.element_ty), mask=mask)
189
+
190
+
191
+ def _bottleneck_projection(down: torch.Tensor, write: torch.Tensor | None) -> torch.Tensor:
192
+ """``[down; write]`` padded with zero rows to a cuBLAS-friendly height."""
193
+
194
+ rows = down.shape[0] + (0 if write is None else write.shape[0])
195
+ padded = triton.cdiv(rows, GEMM_ALIGNMENT) * GEMM_ALIGNMENT
196
+ if write is None and padded == rows:
197
+ return down
198
+ projection = down.new_zeros(padded, down.shape[1])
199
+ projection[: down.shape[0]] = down
200
+ if write is not None:
201
+ projection[down.shape[0] : rows] = write
202
+ return projection
203
+
204
+
205
+ class _FusedGatedResidualRead(torch.autograd.Function):
206
+ """CUDA twin of ``senryu2._GatedResidualRead``: same math, rounding points and saved tensors."""
207
+
208
+ @staticmethod
209
+ def forward(ctx, residual, gamma, down, up, write, eps):
210
+ residual = residual.contiguous()
211
+ rows, branches, hidden_size = residual.shape
212
+ rank = down.shape[0]
213
+ gain = (1.0 + gamma.float()).contiguous()
214
+ flat = residual.new_empty(rows, branches * hidden_size, dtype=down.dtype)
215
+ rstd = residual.new_empty(rows, branches, dtype=torch.float32)
216
+ out = residual.new_empty(rows, hidden_size)
217
+ full = triton.next_power_of_2(hidden_size)
218
+ block = min(COLUMN_BLOCK, full)
219
+ _read_normalize_kernel[(rows * branches,)](
220
+ residual, gain, flat, rstd, hidden_size, eps, BRANCHES=branches, BLOCK=full, num_warps=_warps(full)
221
+ )
222
+ bottleneck = flat @ _bottleneck_projection(down, write).t()
223
+ hidden = bottleneck[:, :rank] / branches
224
+ gate_logits = F.silu(hidden.float()).to(down.dtype) @ up.t()
225
+ _read_combine_kernel[(rows, triton.cdiv(hidden_size, block))](
226
+ residual, rstd, gain, gate_logits, out, hidden_size, BRANCHES=branches, BLOCK=block
227
+ )
228
+ if write is None:
229
+ scales = residual.new_empty(rows, 0, dtype=torch.float32)
230
+ else:
231
+ scales = 2.0 * torch.sigmoid(bottleneck[:, rank : rank + branches].float() / branches)
232
+ ctx.save_for_backward(residual, gamma, down, up, write, rstd, hidden, scales)
233
+ scales_out = scales.to(residual.dtype, copy=True)
234
+ if write is None:
235
+ ctx.mark_non_differentiable(scales_out)
236
+ return out, scales_out
237
+
238
+ @staticmethod
239
+ def backward(ctx, grad_out, grad_scales):
240
+ residual, gamma, down, up, write, rstd, hidden, scales = ctx.saved_tensors
241
+ rows, branches, hidden_size = residual.shape
242
+ rank = down.shape[0]
243
+ dtype = down.dtype
244
+ gain = (1.0 + gamma.float()).contiguous()
245
+ grad_out = grad_out.contiguous()
246
+ full = triton.next_power_of_2(hidden_size)
247
+ block = min(COLUMN_BLOCK, full)
248
+
249
+ pre = hidden.float()
250
+ sigmoid_pre = torch.sigmoid(pre)
251
+ activated = F.silu(pre).to(dtype)
252
+ gate_logits = activated @ up.t()
253
+ flat = torch.empty_like(gate_logits)
254
+ grad_gate_logits = torch.empty_like(gate_logits)
255
+ _read_backward_gates_kernel[(rows * branches, triton.cdiv(hidden_size, block))](
256
+ residual, rstd, gain, gate_logits, grad_out, flat, grad_gate_logits, hidden_size,
257
+ BRANCHES=branches, BLOCK=block,
258
+ )
259
+ grad_up = grad_gate_logits.t() @ activated
260
+ grad_activated = (grad_gate_logits @ up).float()
261
+ del grad_gate_logits
262
+
263
+ projection = _bottleneck_projection(down, write)
264
+ grad_bottleneck = residual.new_zeros(rows, projection.shape[0], dtype=dtype)
265
+ grad_pre = grad_activated * sigmoid_pre * (1.0 + pre * (1.0 - sigmoid_pre))
266
+ grad_bottleneck[:, :rank] = (grad_pre / branches).to(dtype)
267
+ use_scales = write is not None and grad_scales is not None
268
+ if use_scales:
269
+ grad_scale_logits = grad_scales.float() * scales * (1.0 - scales / 2.0)
270
+ grad_bottleneck[:, rank : rank + branches] = (grad_scale_logits / branches).to(dtype)
271
+ grad_projection = grad_bottleneck.t() @ flat
272
+ grad_flat = grad_bottleneck @ projection
273
+ del flat
274
+
275
+ grad_residual = torch.empty_like(residual)
276
+ programs = triton.cdiv(rows, GRAD_ROWS_PER_PROGRAM)
277
+ grad_gain_partial = residual.new_empty(programs, branches, hidden_size, dtype=torch.float32)
278
+ _read_backward_residual_kernel[(programs, branches)](
279
+ residual, rstd, gain, gate_logits, grad_out, grad_flat, grad_residual, grad_gain_partial,
280
+ rows, hidden_size, BRANCHES=branches, ROWS=GRAD_ROWS_PER_PROGRAM, BLOCK=full, num_warps=_warps(full),
281
+ )
282
+ grad_write = None
283
+ if write is not None:
284
+ grad_write = (
285
+ grad_projection[rank : rank + branches].to(write.dtype) if use_scales else torch.zeros_like(write)
286
+ )
287
+ return (
288
+ grad_residual,
289
+ grad_gain_partial.sum(dim=0).to(gamma.dtype),
290
+ grad_projection[:rank].to(down.dtype),
291
+ grad_up.to(up.dtype),
292
+ grad_write,
293
+ None,
294
+ )
295
+
296
+
297
+ class _FusedGatedResidualWrite(torch.autograd.Function):
298
+ @staticmethod
299
+ def forward(ctx, residual, scales, update):
300
+ residual = residual.contiguous()
301
+ scales = scales.contiguous()
302
+ update = update.contiguous()
303
+ rows, branches, hidden_size = residual.shape
304
+ out = torch.empty_like(residual)
305
+ block = min(COLUMN_BLOCK, triton.next_power_of_2(hidden_size))
306
+ _write_forward_kernel[(rows, triton.cdiv(hidden_size, block))](
307
+ residual, scales, update, out, hidden_size, BRANCHES=branches, BLOCK=block
308
+ )
309
+ ctx.save_for_backward(scales, update)
310
+ return out
311
+
312
+ @staticmethod
313
+ def backward(ctx, grad):
314
+ scales, update = ctx.saved_tensors
315
+ grad = grad.contiguous()
316
+ rows, branches, hidden_size = grad.shape
317
+ grad_scales = torch.empty_like(scales)
318
+ grad_update = torch.empty_like(update)
319
+ full = triton.next_power_of_2(hidden_size)
320
+ _write_backward_kernel[(rows,)](
321
+ grad, scales, update, grad_scales, grad_update, hidden_size,
322
+ BRANCHES=branches, BLOCK=full, num_warps=_warps(full),
323
+ )
324
+ return grad, grad_scales, grad_update
325
+
326
+
327
+ def fused_gated_residual_read(
328
+ residual: torch.Tensor,
329
+ gamma: torch.Tensor,
330
+ down: torch.Tensor,
331
+ up: torch.Tensor,
332
+ write: torch.Tensor | None,
333
+ eps: float,
334
+ ) -> tuple[torch.Tensor, torch.Tensor]:
335
+ """``(x [N, d], scales [N, n])`` from CUDA branches ``[N, n, d]``."""
336
+
337
+ return _FusedGatedResidualRead.apply(residual, gamma, down, up, write, eps)
338
+
339
+
340
+ def fused_gated_residual_write(residual: torch.Tensor, scales: torch.Tensor, update: torch.Tensor) -> torch.Tensor:
341
+ """``residual + scales[..., None] * update[:, None]`` on CUDA, in FP32 and rounded once."""
342
+
343
+ return _FusedGatedResidualWrite.apply(residual, scales, update)
tiny_gdn/haiku_layers.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Haiku mixers: Gated MLA (NoPE), SiTU-GLU, and block Attention Residuals."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from torch import nn
10
+ from torch.nn.attention import sdpa_kernel
11
+
12
+ from tiny_gdn.config import TinyGDNConfig
13
+ from tiny_gdn.nn_common import RMSNorm, attention_sdpa_backends, situ_glu_reference
14
+
15
+ try:
16
+ from tiny_gdn.fused_ops import situ_glu
17
+ except ImportError:
18
+ situ_glu = situ_glu_reference
19
+
20
+
21
+ class GatedMultiheadLatentAttention(nn.Module):
22
+ """DeepSeek-style MLA with Kimi K3 NoPE and a full-rank output gate.
23
+
24
+ Queries and keys are content-only. Position is left to the KDA layers.
25
+ KV is compressed through a latent bottleneck, then expanded per head.
26
+ """
27
+
28
+ def __init__(self, config: TinyGDNConfig) -> None:
29
+ super().__init__()
30
+ self.num_heads = config.num_attention_heads
31
+ self.qk_dim = config.mla_qk_nope_head_dim
32
+ self.v_dim = config.mla_v_head_dim
33
+ self.dropout = config.attention_dropout
34
+ q_out = self.num_heads * self.qk_dim
35
+ v_out = self.num_heads * self.v_dim
36
+ kv_out = self.num_heads * (self.qk_dim + self.v_dim)
37
+
38
+ if config.mla_q_lora_rank is None:
39
+ self.q_proj: nn.Module = nn.Linear(config.hidden_size, q_out, bias=False)
40
+ else:
41
+ self.q_proj = nn.Sequential(
42
+ nn.Linear(config.hidden_size, config.mla_q_lora_rank, bias=False),
43
+ RMSNorm(config.mla_q_lora_rank, config.rms_norm_eps),
44
+ nn.Linear(config.mla_q_lora_rank, q_out, bias=False),
45
+ )
46
+ self.kv_down = nn.Linear(config.hidden_size, config.mla_kv_lora_rank, bias=False)
47
+ self.kv_norm = RMSNorm(config.mla_kv_lora_rank, config.rms_norm_eps)
48
+ self.kv_up = nn.Linear(config.mla_kv_lora_rank, kv_out, bias=False)
49
+ self.q_norm = RMSNorm(self.qk_dim, config.rms_norm_eps)
50
+ self.k_norm = RMSNorm(self.qk_dim, config.rms_norm_eps)
51
+ self.output_gate_proj = nn.Linear(config.hidden_size, v_out, bias=False)
52
+ self.o_proj = nn.Linear(v_out, config.hidden_size, bias=False)
53
+
54
+ def _attention_mask(
55
+ self,
56
+ attention_mask: torch.Tensor | None,
57
+ sequence_length: int,
58
+ device: torch.device,
59
+ ) -> torch.Tensor | None:
60
+ if attention_mask is None:
61
+ return None
62
+ if attention_mask.ndim != 2:
63
+ raise ValueError("attention_mask must have shape [batch, sequence]")
64
+ if attention_mask.shape[1] != sequence_length:
65
+ raise ValueError("attention_mask sequence length does not match input")
66
+ causal = torch.ones(
67
+ sequence_length,
68
+ sequence_length,
69
+ dtype=torch.bool,
70
+ device=device,
71
+ ).tril()
72
+ valid_keys = attention_mask[:, None, None, :].to(dtype=torch.bool, device=device)
73
+ return causal[None, None, :, :] & valid_keys
74
+
75
+ def _project_kv(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
76
+ batch_size, sequence_length, _ = hidden_states.shape
77
+ compressed = self.kv_norm(self.kv_down(hidden_states))
78
+ key_value = self.kv_up(compressed)
79
+ key, value = key_value.split(
80
+ [self.num_heads * self.qk_dim, self.num_heads * self.v_dim],
81
+ dim=-1,
82
+ )
83
+ key = self.k_norm(
84
+ key.view(batch_size, sequence_length, self.num_heads, self.qk_dim)
85
+ ).transpose(1, 2)
86
+ value = value.view(
87
+ batch_size, sequence_length, self.num_heads, self.v_dim
88
+ ).transpose(1, 2)
89
+ return key, value
90
+
91
+ def forward(
92
+ self,
93
+ hidden_states: torch.Tensor,
94
+ attention_mask: torch.Tensor | None = None,
95
+ past_key_value: tuple[torch.Tensor, torch.Tensor] | None = None,
96
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
97
+ batch_size, sequence_length, _ = hidden_states.shape
98
+ query = self.q_proj(hidden_states)
99
+ query = self.q_norm(
100
+ query.view(batch_size, sequence_length, self.num_heads, self.qk_dim)
101
+ ).transpose(1, 2)
102
+ key, value = self._project_kv(hidden_states)
103
+ if past_key_value is not None:
104
+ key = torch.cat([past_key_value[0], key], dim=2)
105
+ value = torch.cat([past_key_value[1], value], dim=2)
106
+ present = (key, value)
107
+ past_len = 0 if past_key_value is None else past_key_value[0].shape[2]
108
+ kv_len = key.shape[2]
109
+
110
+ if attention_mask is not None and past_key_value is None:
111
+ sdpa_mask = self._attention_mask(
112
+ attention_mask, sequence_length, hidden_states.device
113
+ )
114
+ is_causal = False
115
+ elif past_key_value is not None and sequence_length == 1:
116
+ sdpa_mask = (
117
+ None
118
+ if attention_mask is None
119
+ else attention_mask[:, None, None, :].to(
120
+ dtype=torch.bool, device=hidden_states.device
121
+ )
122
+ )
123
+ is_causal = False
124
+ elif past_key_value is not None:
125
+ q_idx = torch.arange(
126
+ past_len, past_len + sequence_length, device=hidden_states.device
127
+ )[:, None]
128
+ k_idx = torch.arange(kv_len, device=hidden_states.device)[None, :]
129
+ sdpa_mask = (k_idx <= q_idx)[None, None, :, :]
130
+ is_causal = False
131
+ else:
132
+ sdpa_mask = None
133
+ is_causal = True
134
+
135
+ with sdpa_kernel(attention_sdpa_backends(query.device)):
136
+ attention_output = F.scaled_dot_product_attention(
137
+ query,
138
+ key,
139
+ value,
140
+ attn_mask=sdpa_mask,
141
+ dropout_p=self.dropout if self.training else 0.0,
142
+ is_causal=is_causal,
143
+ )
144
+ attention_output = attention_output.transpose(1, 2).reshape(
145
+ batch_size, sequence_length, -1
146
+ )
147
+ attention_output = attention_output * torch.sigmoid(
148
+ self.output_gate_proj(hidden_states)
149
+ )
150
+ return self.o_proj(attention_output), present
151
+
152
+
153
+ class SiTUGLU(nn.Module):
154
+ """Sigmoid-Tanh Unit GLU from Kimi K3.
155
+
156
+ Caps the Swish linear factor and the up-projection so the routed / deep
157
+ stack cannot explode, while matching SwiGLU near the origin.
158
+ """
159
+
160
+ def __init__(self, config: TinyGDNConfig) -> None:
161
+ super().__init__()
162
+ self.gate_up_proj = nn.Linear(
163
+ config.hidden_size,
164
+ config.intermediate_size * 2,
165
+ bias=False,
166
+ )
167
+ self.down_proj = nn.Linear(
168
+ config.intermediate_size,
169
+ config.hidden_size,
170
+ bias=False,
171
+ )
172
+ self.gate_cap = config.situ_gate_cap
173
+ self.up_cap = config.situ_up_cap
174
+
175
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
176
+ gate_up = self.gate_up_proj(hidden_states)
177
+ return self.down_proj(situ_glu(gate_up, self.gate_cap, self.up_cap))
178
+
179
+
180
+ class BlockAttentionResidual(nn.Module):
181
+ """Selective depth skip over block outputs (Kimi K3 AttnRes, block-level)."""
182
+
183
+ def __init__(self, hidden_size: int) -> None:
184
+ super().__init__()
185
+ self.query = nn.Parameter(torch.zeros(hidden_size))
186
+ self.scale = 1.0 / math.sqrt(hidden_size)
187
+
188
+ def forward(
189
+ self,
190
+ hidden_states: torch.Tensor,
191
+ memories: list[torch.Tensor],
192
+ ) -> torch.Tensor:
193
+ if not memories:
194
+ return hidden_states
195
+ stacked = torch.stack(memories, dim=2)
196
+ scores = torch.einsum("d,bsnd->bsn", self.query, stacked) * self.scale
197
+ weights = torch.softmax(scores, dim=-1)
198
+ mixed = torch.einsum("bsn,bsnd->bsd", weights, stacked)
199
+ return hidden_states + mixed
tiny_gdn/model.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from safetensors.torch import load_model, save_model
11
+ from torch import nn
12
+ from torch.nn.attention import sdpa_kernel
13
+ from torch.utils.checkpoint import checkpoint
14
+
15
+ from tiny_gdn.config import LINEAR_LAYER_TYPES, TinyGDNConfig
16
+ from tiny_gdn.haiku_layers import (
17
+ BlockAttentionResidual,
18
+ GatedMultiheadLatentAttention,
19
+ SiTUGLU,
20
+ )
21
+ from tiny_gdn.nn_common import (
22
+ RMSNorm,
23
+ attention_sdpa_backends,
24
+ linear_cross_entropy_reference,
25
+ )
26
+
27
+ try:
28
+ from tiny_gdn.fused_ops import linear_cross_entropy
29
+ except ImportError:
30
+ linear_cross_entropy = linear_cross_entropy_reference
31
+
32
+ try:
33
+ # Import the module directly — `from fla.layers import GatedDeltaNet2`
34
+ # executes layers/__init__.py and eagerly loads every attention kernel.
35
+ from fla.layers.gdn2 import GatedDeltaNet2
36
+ except ImportError as import_error:
37
+ GatedDeltaNet2 = None
38
+ FLA_IMPORT_ERROR: ImportError | None = import_error
39
+ else:
40
+ FLA_IMPORT_ERROR = None
41
+
42
+ try:
43
+ from fla.layers.kda import KimiDeltaAttention
44
+ except ImportError as import_error:
45
+ KimiDeltaAttention = None
46
+ KDA_IMPORT_ERROR: ImportError | None = import_error
47
+ else:
48
+ KDA_IMPORT_ERROR = None
49
+
50
+ try:
51
+ from tiny_gdn.kdn import DiagonalKalmanDeltaNet
52
+ except ImportError as import_error:
53
+ DiagonalKalmanDeltaNet = None
54
+ KDN_IMPORT_ERROR: ImportError | None = import_error
55
+ else:
56
+ KDN_IMPORT_ERROR = None
57
+
58
+
59
+ @dataclass
60
+ class TinyGDNOutput:
61
+ loss: torch.Tensor | None
62
+ logits: torch.Tensor | None
63
+ main_loss: torch.Tensor | None
64
+ mtp_loss: torch.Tensor | None
65
+ z_loss: torch.Tensor | None
66
+ hidden_states: torch.Tensor | None = None
67
+ past_key_values: Any | None = None
68
+
69
+
70
+ class RotaryEmbedding(nn.Module):
71
+ def __init__(self, rotary_dim: int, rope_theta: float) -> None:
72
+ super().__init__()
73
+ inverse_frequency = 1.0 / (
74
+ rope_theta
75
+ ** (
76
+ torch.arange(0, rotary_dim, 2, dtype=torch.float32)
77
+ / rotary_dim
78
+ )
79
+ )
80
+ self.rotary_dim = rotary_dim
81
+ self.register_buffer("inverse_frequency", inverse_frequency, persistent=False)
82
+
83
+ def forward(
84
+ self,
85
+ sequence_length: int,
86
+ device: torch.device,
87
+ dtype: torch.dtype,
88
+ position_offset: int = 0,
89
+ ) -> tuple[torch.Tensor, torch.Tensor]:
90
+ positions = torch.arange(
91
+ position_offset,
92
+ position_offset + sequence_length,
93
+ device=device,
94
+ dtype=torch.float32,
95
+ )
96
+ frequencies = torch.outer(positions, self.inverse_frequency.float())
97
+ embeddings = torch.cat((frequencies, frequencies), dim=-1)
98
+ return embeddings.cos().to(dtype=dtype), embeddings.sin().to(dtype=dtype)
99
+
100
+
101
+ def rotate_half(hidden_states: torch.Tensor) -> torch.Tensor:
102
+ first, second = hidden_states.chunk(2, dim=-1)
103
+ return torch.cat((-second, first), dim=-1)
104
+
105
+
106
+ def apply_rotary_embedding(
107
+ query: torch.Tensor,
108
+ key: torch.Tensor,
109
+ cosine: torch.Tensor,
110
+ sine: torch.Tensor,
111
+ rotary_dim: int,
112
+ ) -> tuple[torch.Tensor, torch.Tensor]:
113
+ cosine = cosine[None, None, :, :]
114
+ sine = sine[None, None, :, :]
115
+ query_rotary, query_pass = query[..., :rotary_dim], query[..., rotary_dim:]
116
+ key_rotary, key_pass = key[..., :rotary_dim], key[..., rotary_dim:]
117
+ query_rotary = query_rotary * cosine + rotate_half(query_rotary) * sine
118
+ key_rotary = key_rotary * cosine + rotate_half(key_rotary) * sine
119
+ return (
120
+ torch.cat((query_rotary, query_pass), dim=-1),
121
+ torch.cat((key_rotary, key_pass), dim=-1),
122
+ )
123
+
124
+
125
+ class GatedGroupedQueryAttention(nn.Module):
126
+ """QK-normalized, partially rotary GQA with a learned sigmoid output gate."""
127
+
128
+ def __init__(self, config: TinyGDNConfig) -> None:
129
+ super().__init__()
130
+ self.num_heads = config.num_attention_heads
131
+ self.num_key_value_heads = config.num_key_value_heads
132
+ self.head_dim = config.attention_head_dim
133
+ self.rotary_dim = config.rotary_dim
134
+ self.dropout = config.attention_dropout
135
+
136
+ query_size = self.num_heads * self.head_dim
137
+ key_value_size = self.num_key_value_heads * self.head_dim
138
+ self.q_gate_proj = nn.Linear(config.hidden_size, query_size * 2, bias=False)
139
+ self.k_proj = nn.Linear(config.hidden_size, key_value_size, bias=False)
140
+ self.v_proj = nn.Linear(config.hidden_size, key_value_size, bias=False)
141
+ self.o_proj = nn.Linear(query_size, config.hidden_size, bias=False)
142
+ self.q_norm = RMSNorm(self.head_dim, config.rms_norm_eps)
143
+ self.k_norm = RMSNorm(self.head_dim, config.rms_norm_eps)
144
+ self.rotary = RotaryEmbedding(self.rotary_dim, config.rope_theta)
145
+
146
+ def _attention_mask(
147
+ self,
148
+ attention_mask: torch.Tensor | None,
149
+ sequence_length: int,
150
+ device: torch.device,
151
+ ) -> torch.Tensor | None:
152
+ if attention_mask is None:
153
+ return None
154
+ if attention_mask.ndim != 2:
155
+ raise ValueError("attention_mask must have shape [batch, sequence]")
156
+ if attention_mask.shape[1] != sequence_length:
157
+ raise ValueError("attention_mask sequence length does not match input")
158
+
159
+ causal = torch.ones(
160
+ sequence_length,
161
+ sequence_length,
162
+ dtype=torch.bool,
163
+ device=device,
164
+ ).tril()
165
+ valid_keys = attention_mask[:, None, None, :].to(dtype=torch.bool, device=device)
166
+ return causal[None, None, :, :] & valid_keys
167
+
168
+ def forward(
169
+ self,
170
+ hidden_states: torch.Tensor,
171
+ attention_mask: torch.Tensor | None = None,
172
+ past_key_value: tuple[torch.Tensor, torch.Tensor] | None = None,
173
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]:
174
+ batch_size, sequence_length, _ = hidden_states.shape
175
+ past_len = 0 if past_key_value is None else past_key_value[0].shape[2]
176
+ query_and_gate = self.q_gate_proj(hidden_states)
177
+ query, output_gate = query_and_gate.chunk(2, dim=-1)
178
+
179
+ query = query.view(batch_size, sequence_length, self.num_heads, self.head_dim)
180
+ key = self.k_proj(hidden_states).view(
181
+ batch_size,
182
+ sequence_length,
183
+ self.num_key_value_heads,
184
+ self.head_dim,
185
+ )
186
+ value = self.v_proj(hidden_states).view(
187
+ batch_size,
188
+ sequence_length,
189
+ self.num_key_value_heads,
190
+ self.head_dim,
191
+ )
192
+
193
+ query = self.q_norm(query).transpose(1, 2)
194
+ key = self.k_norm(key).transpose(1, 2)
195
+ value = value.transpose(1, 2)
196
+
197
+ cosine, sine = self.rotary(
198
+ sequence_length,
199
+ device=hidden_states.device,
200
+ dtype=query.dtype,
201
+ position_offset=past_len,
202
+ )
203
+ query, key = apply_rotary_embedding(
204
+ query,
205
+ key,
206
+ cosine,
207
+ sine,
208
+ rotary_dim=self.rotary_dim,
209
+ )
210
+ if past_key_value is not None:
211
+ key = torch.cat([past_key_value[0], key], dim=2)
212
+ value = torch.cat([past_key_value[1], value], dim=2)
213
+ present = (key, value)
214
+
215
+ kv_len = key.shape[2]
216
+ if attention_mask is not None and past_key_value is None:
217
+ sdpa_mask = self._attention_mask(
218
+ attention_mask,
219
+ sequence_length,
220
+ hidden_states.device,
221
+ )
222
+ is_causal = False
223
+ elif past_key_value is not None and sequence_length == 1:
224
+ # Decode step: query attends to the cached key/value prefix. Preserve
225
+ # the prefill padding mask when decoding a left-padded prompt batch.
226
+ sdpa_mask = (
227
+ None
228
+ if attention_mask is None
229
+ else attention_mask[:, None, None, :].to(
230
+ dtype=torch.bool,
231
+ device=hidden_states.device,
232
+ )
233
+ )
234
+ is_causal = False
235
+ elif past_key_value is not None:
236
+ # Prefill chunk with cache — build causal mask over kv_len.
237
+ q_idx = torch.arange(
238
+ past_len, past_len + sequence_length, device=hidden_states.device
239
+ )[:, None]
240
+ k_idx = torch.arange(kv_len, device=hidden_states.device)[None, :]
241
+ sdpa_mask = (k_idx <= q_idx)[None, None, :, :]
242
+ is_causal = False
243
+ else:
244
+ sdpa_mask = None
245
+ is_causal = True
246
+ sdpa_options = {
247
+ "attn_mask": sdpa_mask,
248
+ "dropout_p": self.dropout if self.training else 0.0,
249
+ "is_causal": is_causal,
250
+ "enable_gqa": True,
251
+ }
252
+ with sdpa_kernel(attention_sdpa_backends(query.device)):
253
+ attention_output = F.scaled_dot_product_attention(
254
+ query,
255
+ key,
256
+ value,
257
+ **sdpa_options,
258
+ )
259
+ attention_output = attention_output.transpose(1, 2).reshape(
260
+ batch_size,
261
+ sequence_length,
262
+ -1,
263
+ )
264
+ attention_output = attention_output * torch.sigmoid(output_gate)
265
+ return self.o_proj(attention_output), present
266
+
267
+
268
+ class SwiGLU(nn.Module):
269
+ def __init__(self, config: TinyGDNConfig) -> None:
270
+ super().__init__()
271
+ self.gate_up_proj = nn.Linear(
272
+ config.hidden_size,
273
+ config.intermediate_size * 2,
274
+ bias=False,
275
+ )
276
+ self.down_proj = nn.Linear(
277
+ config.intermediate_size,
278
+ config.hidden_size,
279
+ bias=False,
280
+ )
281
+
282
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
283
+ gate, up = self.gate_up_proj(hidden_states).chunk(2, dim=-1)
284
+ return self.down_proj(F.silu(gate) * up)
285
+
286
+
287
+ class TinyGDNBlock(nn.Module):
288
+ def __init__(self, config: TinyGDNConfig, layer_index: int) -> None:
289
+ super().__init__()
290
+ layer_type = config.layer_types[layer_index]
291
+ self.layer_type = layer_type
292
+ self.token_mixer_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
293
+ self.mlp_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
294
+
295
+ if layer_type == "gdn2":
296
+ if GatedDeltaNet2 is None:
297
+ raise ImportError(
298
+ "Gated DeltaNet-2 requires the pinned flash-linear-attention dependency"
299
+ ) from FLA_IMPORT_ERROR
300
+ self.token_mixer = GatedDeltaNet2(
301
+ hidden_size=config.hidden_size,
302
+ expand_v=config.linear_expand_v,
303
+ head_dim=config.linear_head_dim,
304
+ num_heads=config.linear_num_heads,
305
+ num_v_heads=config.linear_num_value_heads,
306
+ mode="chunk",
307
+ use_short_conv=True,
308
+ allow_neg_eigval=config.allow_negative_eigenvalues,
309
+ conv_size=config.linear_conv_kernel_dim,
310
+ conv_bias=False,
311
+ layer_idx=layer_index,
312
+ norm_eps=config.rms_norm_eps,
313
+ )
314
+ elif layer_type == "kda":
315
+ if KimiDeltaAttention is None:
316
+ raise ImportError(
317
+ "Kimi Delta Attention requires the pinned flash-linear-attention dependency"
318
+ ) from KDA_IMPORT_ERROR
319
+ self.token_mixer = KimiDeltaAttention(
320
+ hidden_size=config.hidden_size,
321
+ expand_v=config.linear_expand_v,
322
+ head_dim=config.linear_head_dim,
323
+ num_heads=config.linear_num_heads,
324
+ num_v_heads=config.linear_num_value_heads,
325
+ mode="chunk",
326
+ use_short_conv=True,
327
+ allow_neg_eigval=config.allow_negative_eigenvalues,
328
+ safe_gate=config.kda_safe_gate,
329
+ lower_bound=config.kda_lower_bound,
330
+ conv_size=config.linear_conv_kernel_dim,
331
+ conv_bias=False,
332
+ layer_idx=layer_index,
333
+ norm_eps=config.rms_norm_eps,
334
+ )
335
+ elif layer_type == "diag_kdn":
336
+ if DiagonalKalmanDeltaNet is None:
337
+ raise ImportError(
338
+ "Diagonal KDN requires Triton and the pinned flash-linear-attention dependency"
339
+ ) from KDN_IMPORT_ERROR
340
+ self.token_mixer = DiagonalKalmanDeltaNet(
341
+ hidden_size=config.hidden_size,
342
+ head_dim=config.linear_head_dim,
343
+ num_heads=config.linear_num_heads,
344
+ conv_size=config.linear_conv_kernel_dim,
345
+ norm_eps=config.rms_norm_eps,
346
+ layer_idx=layer_index,
347
+ )
348
+ elif layer_type == "full_attention":
349
+ self.token_mixer = GatedGroupedQueryAttention(config)
350
+ elif layer_type == "gated_mla":
351
+ self.token_mixer = GatedMultiheadLatentAttention(config)
352
+ else:
353
+ raise ValueError(f"Unsupported layer type: {layer_type}")
354
+
355
+ if config.mlp_activation == "swiglu":
356
+ self.mlp: nn.Module = SwiGLU(config)
357
+ elif config.mlp_activation == "situ_glu":
358
+ self.mlp = SiTUGLU(config)
359
+ else:
360
+ raise ValueError(f"Unsupported mlp_activation: {config.mlp_activation}")
361
+
362
+ def forward(
363
+ self,
364
+ hidden_states: torch.Tensor,
365
+ attention_mask: torch.Tensor | None = None,
366
+ *,
367
+ past_key_values: Any | None = None,
368
+ past_key_value: tuple[torch.Tensor, torch.Tensor] | None = None,
369
+ use_cache: bool = False,
370
+ ) -> tuple[torch.Tensor, Any]:
371
+ residual = hidden_states
372
+ normalized = self.token_mixer_norm(hidden_states)
373
+ present: Any = None
374
+ if self.layer_type in LINEAR_LAYER_TYPES:
375
+ mixed, _, past_key_values = self.token_mixer(
376
+ normalized,
377
+ attention_mask=attention_mask,
378
+ past_key_values=past_key_values,
379
+ use_cache=use_cache,
380
+ )
381
+ present = past_key_values
382
+ elif self.layer_type in {"full_attention", "gated_mla"}:
383
+ mixed, present = self.token_mixer(
384
+ normalized,
385
+ attention_mask=attention_mask,
386
+ past_key_value=past_key_value,
387
+ )
388
+ if not use_cache:
389
+ present = None
390
+ else:
391
+ raise ValueError(f"Unsupported layer type: {self.layer_type}")
392
+ hidden_states = residual + mixed
393
+ hidden_states = hidden_states + self.mlp(self.mlp_norm(hidden_states))
394
+ return hidden_states, present
395
+
396
+
397
+ class MultiTokenPredictionAdapter(nn.Module):
398
+ """A lightweight residual adapter for one additional prediction horizon."""
399
+
400
+ def __init__(self, config: TinyGDNConfig) -> None:
401
+ super().__init__()
402
+ self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
403
+ self.down_proj = nn.Linear(
404
+ config.hidden_size,
405
+ config.mtp_adapter_rank,
406
+ bias=False,
407
+ )
408
+ self.up_proj = nn.Linear(
409
+ config.mtp_adapter_rank,
410
+ config.hidden_size,
411
+ bias=False,
412
+ )
413
+
414
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
415
+ adapted = self.up_proj(F.silu(self.down_proj(self.norm(hidden_states))))
416
+ return hidden_states + adapted
417
+
418
+
419
+ class TinyGDNForCausalLM(nn.Module):
420
+ def __init__(self, config: TinyGDNConfig) -> None:
421
+ super().__init__()
422
+ self.config = config
423
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
424
+ self.layers = nn.ModuleList(
425
+ TinyGDNBlock(config, layer_index)
426
+ for layer_index in range(config.num_hidden_layers)
427
+ )
428
+ self.final_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
429
+ self.mtp_adapters = nn.ModuleList(
430
+ MultiTokenPredictionAdapter(config)
431
+ for _ in range(config.mtp_num_heads)
432
+ )
433
+ self.block_attn_res = (
434
+ BlockAttentionResidual(config.hidden_size)
435
+ if config.use_block_attn_res
436
+ else None
437
+ )
438
+ self.checkpointed_layers: frozenset[int] = frozenset()
439
+
440
+ self.apply(self._initialize_module)
441
+ self._initialize_residual_projections()
442
+
443
+ def _initialize_module(self, module: nn.Module) -> None:
444
+ if isinstance(module, nn.Linear):
445
+ nn.init.normal_(
446
+ module.weight,
447
+ mean=0.0,
448
+ std=self.config.initializer_range,
449
+ )
450
+ if module.bias is not None:
451
+ nn.init.zeros_(module.bias)
452
+ elif isinstance(module, nn.Embedding):
453
+ nn.init.normal_(
454
+ module.weight,
455
+ mean=0.0,
456
+ std=self.config.initializer_range,
457
+ )
458
+ elif DiagonalKalmanDeltaNet is not None and isinstance(
459
+ module, DiagonalKalmanDeltaNet
460
+ ):
461
+ # apply() visits children first, so this runs after the Linear re-init.
462
+ module.reset_noise_parameters()
463
+
464
+ def _initialize_residual_projections(self) -> None:
465
+ residual_std = self.config.initializer_range / math.sqrt(
466
+ 2 * self.config.num_hidden_layers
467
+ )
468
+ for layer in self.layers:
469
+ nn.init.normal_(
470
+ layer.token_mixer.o_proj.weight,
471
+ mean=0.0,
472
+ std=residual_std,
473
+ )
474
+ nn.init.normal_(
475
+ layer.mlp.down_proj.weight,
476
+ mean=0.0,
477
+ std=residual_std,
478
+ )
479
+ for adapter in self.mtp_adapters:
480
+ nn.init.normal_(adapter.up_proj.weight, mean=0.0, std=residual_std)
481
+
482
+ def enable_gradient_checkpointing(
483
+ self,
484
+ enabled: bool = True,
485
+ *,
486
+ layers: int | None = None,
487
+ ) -> None:
488
+ """Recompute block activations during backward instead of storing them.
489
+
490
+ ``layers`` checkpoints only that many blocks, linear-attention blocks
491
+ first: replaying softmax attention costs quadratically in sequence
492
+ length, replaying a linear-attention block costs linearly. ``None``
493
+ checkpoints every block.
494
+ """
495
+
496
+ if not enabled:
497
+ if layers is not None:
498
+ raise ValueError("layers needs gradient checkpointing enabled")
499
+ self.checkpointed_layers = frozenset()
500
+ return
501
+ count = len(self.layers) if layers is None else layers
502
+ if not 1 <= count <= len(self.layers):
503
+ raise ValueError(f"layers must be between 1 and {len(self.layers)}")
504
+ cheapest_replay_first = sorted(
505
+ range(len(self.layers)),
506
+ key=lambda index: self.layers[index].layer_type not in LINEAR_LAYER_TYPES,
507
+ )
508
+ self.checkpointed_layers = frozenset(cheapest_replay_first[:count])
509
+
510
+ def describe_gradient_checkpointing(self) -> str:
511
+ if not self.checkpointed_layers:
512
+ return "off"
513
+ layer_types = sorted(
514
+ {self.layers[index].layer_type for index in self.checkpointed_layers}
515
+ )
516
+ return (
517
+ f"{len(self.checkpointed_layers)}/{len(self.layers)} blocks "
518
+ f"({', '.join(layer_types)})"
519
+ )
520
+
521
+ def project_to_vocabulary(self, hidden_states: torch.Tensor) -> torch.Tensor:
522
+ return F.linear(hidden_states, self.embed_tokens.weight)
523
+
524
+ def _run_layer(
525
+ self,
526
+ layer_index: int,
527
+ hidden_states: torch.Tensor,
528
+ attention_mask: torch.Tensor | None,
529
+ *,
530
+ past_key_values: Any | None = None,
531
+ past_key_value: tuple[torch.Tensor, torch.Tensor] | None = None,
532
+ use_cache: bool = False,
533
+ ) -> tuple[torch.Tensor, Any]:
534
+ layer = self.layers[layer_index]
535
+ if self.training and layer_index in self.checkpointed_layers:
536
+ hidden_states, present = checkpoint(
537
+ layer,
538
+ hidden_states,
539
+ attention_mask,
540
+ use_reentrant=False,
541
+ )
542
+ return hidden_states, present
543
+ return layer(
544
+ hidden_states,
545
+ attention_mask,
546
+ past_key_values=past_key_values,
547
+ past_key_value=past_key_value,
548
+ use_cache=use_cache,
549
+ )
550
+
551
+ def _causal_loss(
552
+ self,
553
+ hidden_states: torch.Tensor,
554
+ labels: torch.Tensor,
555
+ target_offset: int,
556
+ adapter: nn.Module | None = None,
557
+ z_loss_coefficient: float = 0.0,
558
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
559
+ """Return ``(objective, cross_entropy, z_loss)``.
560
+
561
+ Only ``objective = cross_entropy + z_loss_coefficient * z_loss`` carries
562
+ gradients; the other two are detached values for logging.
563
+ """
564
+
565
+ if target_offset < 0:
566
+ raise ValueError("target_offset cannot be negative")
567
+ if target_offset and hidden_states.shape[1] <= target_offset:
568
+ raise ValueError(
569
+ f"Sequence length must exceed target offset {target_offset}"
570
+ )
571
+ if target_offset:
572
+ prediction_states = hidden_states[:, :-target_offset, :]
573
+ targets = labels[:, target_offset:].contiguous()
574
+ else:
575
+ prediction_states = hidden_states
576
+ targets = labels.contiguous()
577
+ if adapter is not None:
578
+ prediction_states = adapter(prediction_states)
579
+ return linear_cross_entropy(
580
+ prediction_states.reshape(-1, prediction_states.shape[-1]),
581
+ self.embed_tokens.weight,
582
+ targets.reshape(-1),
583
+ z_loss_coefficient=z_loss_coefficient,
584
+ )
585
+
586
+ def forward(
587
+ self,
588
+ input_ids: torch.Tensor,
589
+ labels: torch.Tensor | None = None,
590
+ attention_mask: torch.Tensor | None = None,
591
+ past_key_values: Any | None = None,
592
+ *,
593
+ use_cache: bool = False,
594
+ return_logits: bool = True,
595
+ return_hidden_states: bool = False,
596
+ labels_are_shifted: bool = False,
597
+ include_mtp_loss: bool = True,
598
+ mtp_loss_weight: float | None = None,
599
+ z_loss_coefficient: float = 0.0,
600
+ logits_to_keep: int | None = None,
601
+ ) -> TinyGDNOutput:
602
+ if input_ids.ndim != 2:
603
+ raise ValueError("input_ids must have shape [batch, sequence]")
604
+ if input_ids.shape[1] > self.config.max_position_embeddings:
605
+ raise ValueError("Input exceeds max_position_embeddings")
606
+ if labels is not None and labels.shape != input_ids.shape:
607
+ raise ValueError("labels must have the same shape as input_ids")
608
+ if z_loss_coefficient < 0.0:
609
+ raise ValueError("z_loss_coefficient cannot be negative")
610
+ if logits_to_keep is not None and logits_to_keep <= 0:
611
+ raise ValueError("logits_to_keep must be positive")
612
+ if use_cache and labels is not None:
613
+ raise ValueError("use_cache is not supported with labels")
614
+ effective_mtp_weight = (
615
+ self.config.mtp_loss_weight
616
+ if mtp_loss_weight is None
617
+ else mtp_loss_weight
618
+ )
619
+ if not 0.0 <= effective_mtp_weight <= 1.0:
620
+ raise ValueError("mtp_loss_weight must be between zero and one")
621
+
622
+ if use_cache and past_key_values is None:
623
+ try:
624
+ from fla.models.utils import Cache as FlaCache
625
+ except ImportError as import_error:
626
+ raise ImportError(
627
+ "Cached decode requires flash-linear-attention Cache"
628
+ ) from import_error
629
+ past_key_values = {
630
+ "fla": FlaCache(),
631
+ "gqa": [None] * len(self.layers),
632
+ }
633
+ elif past_key_values is not None and not isinstance(past_key_values, dict):
634
+ raise TypeError("past_key_values must be a TinyGDN cache dict or None")
635
+
636
+ fla_cache = None if past_key_values is None else past_key_values["fla"]
637
+ gqa_cache = None if past_key_values is None else past_key_values["gqa"]
638
+
639
+ hidden_states = self.embed_tokens(input_ids)
640
+ shared_layer_indices = set(self.config.shared_layer_indices)
641
+ softmax_types = {"full_attention", "gated_mla"}
642
+ attn_memories: list[torch.Tensor] = [hidden_states]
643
+ interval = self.config.full_attention_interval
644
+ for layer_index, layer in enumerate(self.layers):
645
+ layer_gqa = None if gqa_cache is None else gqa_cache[layer_index]
646
+ hidden_states, present = self._run_layer(
647
+ layer_index,
648
+ hidden_states,
649
+ attention_mask,
650
+ past_key_values=fla_cache,
651
+ past_key_value=layer_gqa,
652
+ use_cache=use_cache,
653
+ )
654
+ if use_cache and layer.layer_type in softmax_types and gqa_cache is not None:
655
+ gqa_cache[layer_index] = present
656
+ if layer_index in shared_layer_indices:
657
+ layer_gqa = None if gqa_cache is None else gqa_cache[layer_index]
658
+ hidden_states, present = self._run_layer(
659
+ layer_index,
660
+ hidden_states,
661
+ attention_mask,
662
+ past_key_values=fla_cache,
663
+ past_key_value=layer_gqa,
664
+ use_cache=use_cache,
665
+ )
666
+ if use_cache and layer.layer_type in softmax_types and gqa_cache is not None:
667
+ gqa_cache[layer_index] = present
668
+ if (
669
+ self.block_attn_res is not None
670
+ and (layer_index + 1) % interval == 0
671
+ ):
672
+ hidden_states = self.block_attn_res(
673
+ hidden_states, [*attn_memories, hidden_states]
674
+ )
675
+ attn_memories.append(hidden_states)
676
+ hidden_states = self.final_norm(hidden_states)
677
+
678
+ main_loss = None
679
+ mtp_loss = None
680
+ z_loss = None
681
+ total_loss = None
682
+ if labels is not None:
683
+ main_target_offset = 0 if labels_are_shifted else 1
684
+ main_objective, main_loss, z_loss = self._causal_loss(
685
+ hidden_states,
686
+ labels,
687
+ target_offset=main_target_offset,
688
+ z_loss_coefficient=z_loss_coefficient,
689
+ )
690
+ if z_loss_coefficient == 0.0:
691
+ z_loss = None
692
+ if self.mtp_adapters and include_mtp_loss:
693
+ auxiliary_losses = [
694
+ self._causal_loss(
695
+ hidden_states,
696
+ labels,
697
+ target_offset=(
698
+ head_index + 1
699
+ if labels_are_shifted
700
+ else head_index + 2
701
+ ),
702
+ adapter=adapter,
703
+ )[0]
704
+ for head_index, adapter in enumerate(self.mtp_adapters)
705
+ ]
706
+ mtp_loss = torch.stack(auxiliary_losses).mean()
707
+ total_loss = main_objective + effective_mtp_weight * mtp_loss
708
+ else:
709
+ total_loss = main_objective
710
+
711
+ output_states = (
712
+ hidden_states
713
+ if logits_to_keep is None
714
+ else hidden_states[:, -logits_to_keep:, :]
715
+ )
716
+ logits = self.project_to_vocabulary(output_states) if return_logits else None
717
+ return TinyGDNOutput(
718
+ loss=total_loss,
719
+ logits=logits,
720
+ main_loss=main_loss,
721
+ mtp_loss=mtp_loss,
722
+ z_loss=z_loss,
723
+ hidden_states=hidden_states if return_hidden_states else None,
724
+ past_key_values=past_key_values if use_cache else None,
725
+ )
726
+
727
+ def parameter_report(self) -> dict[str, int]:
728
+ total = sum(parameter.numel() for parameter in self.parameters())
729
+ mtp = sum(parameter.numel() for parameter in self.mtp_adapters.parameters())
730
+ embeddings = self.embed_tokens.weight.numel()
731
+ return {
732
+ "deployable_core": total - mtp,
733
+ "training_total": total,
734
+ "embedding": embeddings,
735
+ "mtp_auxiliary": mtp,
736
+ "non_embedding_core": total - mtp - embeddings,
737
+ }
738
+
739
+ def save_checkpoint(self, output_dir: Path) -> None:
740
+ output_dir.mkdir(parents=True, exist_ok=True)
741
+ self.config.save_json(output_dir / "config.json")
742
+ save_model(self, output_dir / "model.safetensors")
743
+
744
+ @classmethod
745
+ def from_checkpoint(
746
+ cls,
747
+ checkpoint_dir: Path,
748
+ *,
749
+ device: str | torch.device = "cpu",
750
+ dtype: torch.dtype | None = None,
751
+ ) -> TinyGDNForCausalLM:
752
+ config = TinyGDNConfig.from_json(checkpoint_dir / "config.json")
753
+ model = cls(config).to(device=device, dtype=dtype)
754
+ load_model(model, checkpoint_dir / "model.safetensors", device=str(device))
755
+ return model
756
+
757
+ def extra_repr(self) -> str:
758
+ report = self.parameter_report()
759
+ return (
760
+ f"core_parameters={report['deployable_core']:,}, "
761
+ f"training_parameters={report['training_total']:,}"
762
+ )
763
+
764
+ def get_architecture_metadata(self) -> dict[str, Any]:
765
+ return {
766
+ "architecture": self.config.architecture,
767
+ "layer_types": list(self.config.layer_types),
768
+ "effective_num_layers": self.config.effective_num_layers,
769
+ "shared_layer_indices": list(self.config.shared_layer_indices),
770
+ "parameter_report": self.parameter_report(),
771
+ "features": [
772
+ "hybrid linear + softmax token mixing",
773
+ "Kimi Delta Attention or Gated DeltaNet-2",
774
+ "gated MLA or gated GQA",
775
+ "optional block Attention Residuals",
776
+ "SwiGLU or SiTU-GLU",
777
+ "QK normalization",
778
+ "zero-centered RMSNorm",
779
+ "tied input-output embeddings",
780
+ "optional multi-token prediction auxiliaries",
781
+ ],
782
+ }
tiny_gdn/ngram.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hashed n-gram addressing shared by Senryu-2's model, its host table store, and serving.
2
+
3
+ Each table row is addressed with integer ops that give the same result on CPU
4
+ and CUDA: canonical token ids (NFKC-normalized, lowercased, stripped surface
5
+ forms) are multiplied by odd 31-bit constants, XOR-combined, mixed, and reduced
6
+ modulo a distinct prime per table. Token ids stay below 2**16, so every
7
+ product stays below 2**47 and int64 never overflows.
8
+
9
+ Tables live in one concatenated ``[total_rows, embedding_dim]`` tensor; table
10
+ ``t`` owns rows ``[offset_t, offset_t + rows_t)``. The prime row counts, the
11
+ multipliers, and the canonical map are saved beside every table file and
12
+ checked on load, so a table can never be read with a different address map.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import unicodedata
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import torch
23
+ from safetensors import safe_open
24
+ from safetensors.torch import save_file
25
+ from tokenizers import Tokenizer
26
+
27
+ from tiny_gdn.config import TinyGDNConfig
28
+
29
+ NGRAM_TABLES_FILE = "ngram_tables.safetensors"
30
+ NGRAM_TABLES_EMA_FILE = "ngram_tables_ema.safetensors"
31
+ NGRAM_OPTIMIZER_FILE = "ngram_optimizer.safetensors"
32
+
33
+ PRIME_STRIDE = 4099
34
+ HASH_SEED = 0x6B696D6F
35
+ MIX_SHIFT = 29
36
+ LOAD_CHUNK_ROWS = 1 << 20
37
+ _MASK64 = (1 << 64) - 1
38
+ _MILLER_RABIN_BASES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)
39
+
40
+
41
+ def _splitmix64(state: int) -> tuple[int, int]:
42
+ state = (state + 0x9E3779B97F4A7C15) & _MASK64
43
+ mixed = ((state ^ (state >> 30)) * 0xBF58476D1CE4E5B9) & _MASK64
44
+ mixed = ((mixed ^ (mixed >> 27)) * 0x94D049BB133111EB) & _MASK64
45
+ return state, mixed ^ (mixed >> 31)
46
+
47
+
48
+ def _is_prime(value: int) -> bool:
49
+ if value < 2:
50
+ return False
51
+ for base in _MILLER_RABIN_BASES:
52
+ if value % base == 0:
53
+ return value == base
54
+ odd, twos = value - 1, 0
55
+ while odd % 2 == 0:
56
+ odd //= 2
57
+ twos += 1
58
+ for base in _MILLER_RABIN_BASES:
59
+ witness = pow(base, odd, value)
60
+ if witness in (1, value - 1):
61
+ continue
62
+ for _ in range(twos - 1):
63
+ witness = witness * witness % value
64
+ if witness == value - 1:
65
+ break
66
+ else:
67
+ return False
68
+ return True
69
+
70
+
71
+ def _next_prime(value: int) -> int:
72
+ while not _is_prime(value):
73
+ value += 1
74
+ return value
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class NGramLayout:
79
+ """Where every n-gram of every order lands in the concatenated tables."""
80
+
81
+ orders: tuple[int, ...]
82
+ heads_per_order: int
83
+ table_rows: tuple[int, ...]
84
+ table_offsets: tuple[int, ...]
85
+ multipliers: tuple[tuple[int, ...], ...]
86
+ embedding_dim: int
87
+ pad_token_id: int
88
+
89
+ @classmethod
90
+ def from_config(cls, config: TinyGDNConfig) -> NGramLayout:
91
+ if not config.ngram_orders:
92
+ raise ValueError("config has no n-gram memory")
93
+ rows: list[int] = []
94
+ candidate = config.ngram_table_rows
95
+ for _ in range(config.ngram_table_count):
96
+ candidate = _next_prime(candidate + PRIME_STRIDE)
97
+ rows.append(candidate)
98
+ offsets = tuple(int(value) for value in np.cumsum([0, *rows[:-1]]))
99
+ state = HASH_SEED
100
+ multipliers: list[tuple[int, ...]] = []
101
+ max_order = max(config.ngram_orders)
102
+ for _ in range(config.ngram_table_count):
103
+ table: list[int] = []
104
+ for _ in range(max_order):
105
+ state, value = _splitmix64(state)
106
+ table.append((value >> 33) | (1 << 30) | 1)
107
+ multipliers.append(tuple(table))
108
+ return cls(
109
+ orders=tuple(config.ngram_orders),
110
+ heads_per_order=config.ngram_heads_per_order,
111
+ table_rows=tuple(rows),
112
+ table_offsets=offsets,
113
+ multipliers=tuple(multipliers),
114
+ embedding_dim=config.ngram_embedding_dim,
115
+ pad_token_id=config.bos_token_id,
116
+ )
117
+
118
+ @property
119
+ def table_count(self) -> int:
120
+ return len(self.table_rows)
121
+
122
+ @property
123
+ def total_rows(self) -> int:
124
+ return self.table_offsets[-1] + self.table_rows[-1]
125
+
126
+ @property
127
+ def max_order(self) -> int:
128
+ return max(self.orders)
129
+
130
+ @property
131
+ def memory_dim(self) -> int:
132
+ return self.table_count * self.embedding_dim
133
+
134
+ @property
135
+ def table_orders(self) -> tuple[int, ...]:
136
+ return tuple(order for order in self.orders for _ in range(self.heads_per_order))
137
+
138
+ def metadata_tensors(self) -> dict[str, torch.Tensor]:
139
+ return {
140
+ "table_rows": torch.tensor(self.table_rows, dtype=torch.int64),
141
+ "hash_multipliers": torch.tensor(self.multipliers, dtype=torch.int64),
142
+ }
143
+
144
+ def check_metadata(self, tensors: dict[str, torch.Tensor], source: Path) -> None:
145
+ for name, expected in self.metadata_tensors().items():
146
+ found = tensors.get(name)
147
+ if found is None or not torch.equal(found.cpu(), expected):
148
+ raise ValueError(f"{source} was written for a different n-gram layout ({name})")
149
+
150
+
151
+ def canonical_token_ids(tokenizer: Tokenizer, vocab_size: int) -> torch.Tensor:
152
+ """Map every token id to the smallest id sharing its normalized surface form.
153
+
154
+ Normalization is NFKC, then strip, then lowercase. Special tokens keep
155
+ their own ids, whitespace-only tokens are only NFKC-merged, and tokens
156
+ that decode to partial UTF-8 stay distinct.
157
+ """
158
+
159
+ special = set(tokenizer.get_added_tokens_decoder())
160
+ canonical = np.arange(vocab_size, dtype=np.int64)
161
+ first_by_key: dict[tuple[str, str], int] = {}
162
+ for token_id in range(min(vocab_size, tokenizer.get_vocab_size())):
163
+ if token_id in special:
164
+ continue
165
+ text = tokenizer.decode([token_id], skip_special_tokens=False)
166
+ if "\ufffd" in text:
167
+ key = ("bytes", tokenizer.id_to_token(token_id) or str(token_id))
168
+ else:
169
+ normalized = unicodedata.normalize("NFKC", text)
170
+ folded = normalized.strip().lower()
171
+ key = ("text", folded) if folded else ("space", normalized)
172
+ canonical[token_id] = first_by_key.setdefault(key, token_id)
173
+ return torch.from_numpy(canonical)
174
+
175
+
176
+ def document_distance(tokens: torch.Tensor, bos_token_id: int, row_starts: torch.Tensor | None = None) -> torch.Tensor:
177
+ """Offset of every token in a flat ``[N]`` stream from its document's first token.
178
+
179
+ Documents start at position 0, at every BOS token, and at ``row_starts``.
180
+ """
181
+
182
+ starts = tokens == bos_token_id
183
+ starts[0] = True
184
+ if row_starts is not None:
185
+ starts[row_starts] = True
186
+ positions = torch.arange(tokens.numel(), device=tokens.device)
187
+ first = torch.where(starts, positions, torch.zeros_like(positions)).cummax(dim=0).values
188
+ return positions - first
189
+
190
+
191
+ def ngram_row_indices(
192
+ canonical: torch.Tensor,
193
+ layout: NGramLayout,
194
+ *,
195
+ distance: torch.Tensor | None = None,
196
+ history: torch.Tensor | None = None,
197
+ ) -> torch.Tensor:
198
+ """Global table rows ``[..., L, tables]`` for the n-grams ending at each token.
199
+
200
+ ``canonical`` holds int64 canonical ids ``[..., L]``. Tokens before a
201
+ document start read as the pad id: with ``distance`` (same shape) a
202
+ document starts wherever the distance is zero; with ``history`` (the
203
+ ``max_order - 1`` canonical ids before position 0) the sequence continues
204
+ a cached one; with neither, position 0 starts the only document.
205
+ """
206
+
207
+ span = layout.max_order
208
+ length = canonical.shape[-1]
209
+ pad = layout.pad_token_id
210
+ if history is not None:
211
+ if history.shape[-1] != span - 1:
212
+ raise ValueError(f"history must hold {span - 1} tokens")
213
+ extended = torch.cat([history, canonical], dim=-1)
214
+ shifted = [extended[..., span - 1 - back : span - 1 - back + length] for back in range(span)]
215
+ else:
216
+ shifted = [canonical]
217
+ for back in range(1, span):
218
+ if back >= length:
219
+ previous = torch.full_like(canonical, pad)
220
+ else:
221
+ padding = canonical.new_full((*canonical.shape[:-1], back), pad)
222
+ previous = torch.cat([padding, canonical[..., :-back]], dim=-1)
223
+ if distance is not None:
224
+ previous = torch.where(distance >= back, previous, pad)
225
+ shifted.append(previous)
226
+ columns = []
227
+ for table, order in enumerate(layout.table_orders):
228
+ multipliers = layout.multipliers[table]
229
+ mixed = shifted[0] * multipliers[0]
230
+ for back in range(1, order):
231
+ mixed = mixed ^ (shifted[back] * multipliers[back])
232
+ mixed = mixed ^ (mixed >> MIX_SHIFT)
233
+ columns.append(torch.remainder(mixed, layout.table_rows[table]) + layout.table_offsets[table])
234
+ return torch.stack(columns, dim=-1)
235
+
236
+
237
+ def save_table_file(path: Path, tables: torch.Tensor, layout: NGramLayout, canonical: torch.Tensor) -> None:
238
+ if tables.shape != (layout.total_rows, layout.embedding_dim):
239
+ raise ValueError(f"tables have shape {tuple(tables.shape)}, layout needs {(layout.total_rows, layout.embedding_dim)}")
240
+ save_file(
241
+ {
242
+ "tables": tables.contiguous(),
243
+ "canonical_ids": canonical.to(dtype=torch.int64, device="cpu").contiguous(),
244
+ **layout.metadata_tensors(),
245
+ },
246
+ str(path),
247
+ )
248
+
249
+
250
+ def read_table_metadata(path: Path, layout: NGramLayout) -> torch.Tensor:
251
+ """Check ``path`` against ``layout`` and return its canonical token map."""
252
+
253
+ with safe_open(str(path), framework="pt", device="cpu") as handle:
254
+ metadata = {name: handle.get_tensor(name) for name in ("table_rows", "hash_multipliers")}
255
+ layout.check_metadata(metadata, path)
256
+ # get_tensor returns a view of a mapping of the whole file, which a kept
257
+ # view would hold open; FUSE mounts such as ntfs-3g then cannot delete it.
258
+ return handle.get_tensor("canonical_ids").clone()
259
+
260
+
261
+ def copy_rows_from_file(path: Path, name: str, destination: torch.Tensor) -> None:
262
+ """Copy tensor ``name`` of a safetensors file into ``destination`` in row chunks."""
263
+
264
+ with safe_open(str(path), framework="pt", device="cpu") as handle:
265
+ source = handle.get_slice(name)
266
+ shape = tuple(source.get_shape())
267
+ if shape != tuple(destination.shape):
268
+ raise ValueError(f"{path} holds {name} of shape {shape}, expected {tuple(destination.shape)}")
269
+ for start in range(0, shape[0], LOAD_CHUNK_ROWS):
270
+ stop = min(start + LOAD_CHUNK_ROWS, shape[0])
271
+ destination[start:stop].copy_(source[start:stop])
272
+
273
+
274
+ def load_table_file(
275
+ path: Path,
276
+ layout: NGramLayout,
277
+ *,
278
+ device: torch.device | str = "cpu",
279
+ dtype: torch.dtype = torch.float32,
280
+ out: torch.Tensor | None = None,
281
+ ) -> tuple[torch.Tensor, torch.Tensor]:
282
+ """``(tables, canonical_ids)`` from ``path``, copied in row chunks to bound host memory."""
283
+
284
+ canonical = read_table_metadata(path, layout)
285
+ tables = (
286
+ torch.empty((layout.total_rows, layout.embedding_dim), dtype=dtype, device=device)
287
+ if out is None
288
+ else out
289
+ )
290
+ copy_rows_from_file(path, "tables", tables)
291
+ return tables, canonical
tiny_gdn/nn_common.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn
6
+ from torch.nn.attention import SDPBackend
7
+
8
+ try:
9
+ from fla.modules.layernorm import rms_norm as fused_rms_norm
10
+ except ImportError:
11
+ fused_rms_norm = None
12
+
13
+
14
+ class RMSNorm(nn.Module):
15
+ """Zero-centered RMSNorm as used by Qwen3-Next.
16
+
17
+ On CUDA this runs FLA's single-pass Triton kernel with the ``1 + weight``
18
+ scale kept in FP32, which matches the eager FP32 math to rounding.
19
+ """
20
+
21
+ def __init__(self, hidden_size: int, eps: float) -> None:
22
+ super().__init__()
23
+ self.weight = nn.Parameter(torch.zeros(hidden_size))
24
+ self.eps = eps
25
+
26
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
27
+ scale = 1.0 + self.weight.float()
28
+ if fused_rms_norm is not None and hidden_states.is_cuda:
29
+ return fused_rms_norm(hidden_states, scale, None, eps=self.eps)
30
+ input_dtype = hidden_states.dtype
31
+ normalized = hidden_states.float()
32
+ normalized = normalized * torch.rsqrt(
33
+ normalized.square().mean(dim=-1, keepdim=True) + self.eps
34
+ )
35
+ return (normalized * scale).to(dtype=input_dtype)
36
+
37
+
38
+ def linear_cross_entropy_reference(
39
+ states: torch.Tensor,
40
+ weight: torch.Tensor,
41
+ targets: torch.Tensor,
42
+ *,
43
+ z_loss_coefficient: float = 0.0,
44
+ ignore_index: int = -100,
45
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
46
+ """Eager ``(objective, cross_entropy, z_loss)`` over materialized logits."""
47
+
48
+ logits = F.linear(states, weight)
49
+ cross_entropy = F.cross_entropy(logits, targets, ignore_index=ignore_index)
50
+ reduced_dtype = torch.promote_types(logits.dtype, torch.float32)
51
+ if z_loss_coefficient > 0.0:
52
+ # Keep logits in their training dtype for logsumexp. Casting the full
53
+ # [tokens, vocab] tensor to fp32 materializes it again in the autograd
54
+ # graph; upcast only the reduced [tokens] partition.
55
+ log_partition = torch.logsumexp(logits, dim=-1).to(reduced_dtype)
56
+ z_loss = log_partition.square()[targets.ne(ignore_index)].mean()
57
+ else:
58
+ z_loss = cross_entropy.new_zeros((), dtype=reduced_dtype)
59
+ objective = cross_entropy + z_loss_coefficient * z_loss
60
+ return objective, cross_entropy.detach(), z_loss.detach()
61
+
62
+
63
+ def linear_token_logprobs_reference(
64
+ states: torch.Tensor,
65
+ weight: torch.Tensor,
66
+ targets: torch.Tensor,
67
+ *,
68
+ ignore_index: int = -100,
69
+ ) -> torch.Tensor:
70
+ """Eager fp32 ``log_softmax(states @ weight.T)[row, target]``; ignored rows are 0."""
71
+
72
+ valid = targets.ne(ignore_index)
73
+ logprobs = F.linear(states, weight).float().log_softmax(dim=-1)
74
+ picked = logprobs.gather(1, targets.masked_fill(~valid, 0)[:, None]).squeeze(1)
75
+ return picked.masked_fill(~valid, 0.0)
76
+
77
+
78
+ def softcap(values: torch.Tensor, cap: float) -> torch.Tensor:
79
+ return cap * torch.tanh(values / cap)
80
+
81
+
82
+ def situ_glu_reference(gate_up: torch.Tensor, gate_cap: float, up_cap: float) -> torch.Tensor:
83
+ """``softcap(gate) * sigmoid(gate) * softcap(up)`` over ``[..., gate | up]``."""
84
+
85
+ gate, up = gate_up.chunk(2, dim=-1)
86
+ return softcap(gate, gate_cap) * torch.sigmoid(gate) * softcap(up, up_cap)
87
+
88
+
89
+ def attention_sdpa_backends(device: torch.device) -> list[SDPBackend]:
90
+ if device.type != "cuda":
91
+ return [SDPBackend.MATH]
92
+ return [
93
+ SDPBackend.CUDNN_ATTENTION,
94
+ SDPBackend.FLASH_ATTENTION,
95
+ SDPBackend.EFFICIENT_ATTENTION,
96
+ ]
tiny_gdn/parallax_ops.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parallax attention on fla's Triton kernels, with launch settings that fit the GPU.
2
+
3
+ fla tiles every Parallax kernel 64 rows deep with two pipeline stages, sized
4
+ for Hopper's 228 KB of shared memory. Its backward key/value kernel then needs
5
+ about 105 KB per block, more than consumer Blackwell (sm_120) and Ampere allow
6
+ (99 KB), so it fails to launch there. The tile is a launch constant, so this
7
+ module launches fla's own kernels with the largest tile that fits and keeps
8
+ fla's math unchanged.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable
14
+ from typing import Any
15
+
16
+ import torch
17
+ import triton
18
+ import triton.language as tl
19
+ from einops import reduce
20
+ from fla.ops.parallax.decode import parallax_decode_kernel, parallax_decode_one_step
21
+ from fla.ops.parallax.parallel import (
22
+ parallel_parallax_bwd_kernel_dkv,
23
+ parallel_parallax_bwd_kernel_dqr,
24
+ parallel_parallax_bwd_kernel_preprocess,
25
+ parallel_parallax_fwd_kernel,
26
+ )
27
+ from fla.ops.utils import prepare_chunk_indices
28
+ from fla.ops.utils.op import exp2
29
+ from fla.utils import autocast_custom_bwd, autocast_custom_fwd, contiguous
30
+ from triton.runtime.errors import OutOfResources
31
+
32
+ LaunchConfig = tuple[int, int, int]
33
+ # (tile rows, warps, pipeline stages), fastest first. Measured on an RTX PRO
34
+ # 6000 (sm_120, 99 KB per block): a 32-row tile with 4 warps beats every other
35
+ # setting that launches, forward and backward.
36
+ LARGE_SHARED_MEMORY_CONFIGS: tuple[LaunchConfig, ...] = ((64, 8, 2), (32, 4, 2), (32, 4, 1), (16, 4, 1))
37
+ SMALL_SHARED_MEMORY_CONFIGS: tuple[LaunchConfig, ...] = ((32, 4, 2), (32, 4, 1), (16, 4, 1))
38
+ LARGE_SHARED_MEMORY_BYTES = 160 * 1024
39
+
40
+ _selected: dict[tuple[str, int, int], LaunchConfig] = {}
41
+
42
+
43
+ def _device_index(device: torch.device) -> int:
44
+ return torch.cuda.current_device() if device.index is None else device.index
45
+
46
+
47
+ def _candidates(device: torch.device) -> tuple[LaunchConfig, ...]:
48
+ properties = torch.cuda.get_device_properties(_device_index(device))
49
+ if properties.shared_memory_per_block_optin >= LARGE_SHARED_MEMORY_BYTES:
50
+ return LARGE_SHARED_MEMORY_CONFIGS
51
+ return SMALL_SHARED_MEMORY_CONFIGS
52
+
53
+
54
+ def _launch(name: str, device: torch.device, head_dim: int, launch: Callable[[int, int, int], Any]) -> Any:
55
+ """Run ``launch`` with the first config that fits; remember it per kernel and GPU."""
56
+
57
+ key = (name, _device_index(device), head_dim)
58
+ chosen = _selected.get(key)
59
+ candidates = (chosen,) if chosen is not None else _candidates(device)
60
+ last_error: OutOfResources | None = None
61
+ for config in candidates:
62
+ try:
63
+ result = launch(*config)
64
+ except OutOfResources as error:
65
+ last_error = error
66
+ continue
67
+ _selected[key] = config
68
+ return result
69
+ assert last_error is not None
70
+ raise last_error
71
+
72
+
73
+ def selected_launch_configs() -> dict[tuple[str, int, int], LaunchConfig]:
74
+ return dict(_selected)
75
+
76
+
77
+ def _chunk_indices(cu_seqlens: torch.Tensor | None, tile: int) -> torch.Tensor | None:
78
+ return None if cu_seqlens is None else prepare_chunk_indices(cu_seqlens, tile)
79
+
80
+
81
+ def _grid_rows(length: int, chunk_indices: torch.Tensor | None, tile: int) -> int:
82
+ return triton.cdiv(length, tile) if chunk_indices is None else len(chunk_indices)
83
+
84
+
85
+ def _forward(
86
+ q: torch.Tensor,
87
+ r: torch.Tensor,
88
+ k: torch.Tensor,
89
+ v: torch.Tensor,
90
+ scale: float,
91
+ cu_seqlens: torch.Tensor | None,
92
+ window_size_left: int,
93
+ ) -> tuple[torch.Tensor, ...]:
94
+ batch, length, query_heads, head_dim = q.shape
95
+ kv_heads = k.shape[2]
96
+ o = torch.empty_like(q)
97
+ barv = torch.empty_like(q)
98
+ d1 = torch.empty((batch, length, query_heads), device=q.device, dtype=torch.float32)
99
+ bart = torch.empty_like(d1)
100
+ m = torch.empty_like(d1)
101
+
102
+ def launch(tile: int, warps: int, stages: int) -> None:
103
+ chunk_indices = _chunk_indices(cu_seqlens, tile)
104
+ grid = (_grid_rows(length, chunk_indices, tile), batch * query_heads)
105
+ parallel_parallax_fwd_kernel[grid](
106
+ q, r, k, v, o, barv, d1, bart, m,
107
+ scale, cu_seqlens, chunk_indices, length,
108
+ HQ=query_heads, H=kv_heads, G=query_heads // kv_heads, K=head_dim,
109
+ BK=triton.next_power_of_2(head_dim),
110
+ WINDOW_SIZE_LEFT=window_size_left, BT=tile, BS=tile,
111
+ num_warps=warps, num_stages=stages,
112
+ )
113
+
114
+ _launch("forward", q.device, head_dim, launch)
115
+ return o, barv, d1, bart, m
116
+
117
+
118
+ def _backward(
119
+ saved: tuple[torch.Tensor, ...],
120
+ grad_o: torch.Tensor,
121
+ scale: float,
122
+ cu_seqlens: torch.Tensor | None,
123
+ window_size_left: int,
124
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
125
+ q, r, k, v, o, barv, d1, bart, m = saved
126
+ batch, length, query_heads, head_dim = q.shape
127
+ kv_heads = k.shape[2]
128
+ groups = query_heads // kv_heads
129
+ grad_q = torch.empty_like(q)
130
+ grad_r = torch.empty_like(r)
131
+ # dK/dV are written per query head, then summed back onto the KV heads.
132
+ grad_k_heads = torch.empty((batch, length, query_heads, head_dim), device=q.device, dtype=q.dtype)
133
+ grad_v_heads = torch.empty_like(grad_k_heads)
134
+ delta_t = torch.empty((batch, length, query_heads), device=q.device, dtype=torch.float32)
135
+ delta_b = torch.empty_like(delta_t)
136
+ block_k = triton.next_power_of_2(head_dim)
137
+
138
+ def launch(tile: int, warps: int, stages: int) -> None:
139
+ chunk_indices = _chunk_indices(cu_seqlens, tile)
140
+ grid = (_grid_rows(length, chunk_indices, tile), batch * query_heads)
141
+ parallel_parallax_bwd_kernel_preprocess[grid](
142
+ grad_o, o, barv, delta_t, delta_b,
143
+ cu_seqlens, chunk_indices, length,
144
+ HQ=query_heads, K=head_dim, BK=block_k, BT=tile,
145
+ num_warps=4, num_stages=2,
146
+ )
147
+ parallel_parallax_bwd_kernel_dqr[grid](
148
+ q, r, k, v, d1, bart, m, delta_t, delta_b, grad_o, grad_q, grad_r,
149
+ scale, cu_seqlens, chunk_indices, length,
150
+ HQ=query_heads, H=kv_heads, G=groups, K=head_dim, BK=block_k,
151
+ WINDOW_SIZE_LEFT=window_size_left, BT=tile, BS=tile,
152
+ num_warps=warps, num_stages=stages,
153
+ )
154
+ parallel_parallax_bwd_kernel_dkv[grid](
155
+ q, r, k, v, d1, bart, m, delta_t, delta_b, grad_o, grad_k_heads, grad_v_heads,
156
+ scale, cu_seqlens, chunk_indices, length,
157
+ HQ=query_heads, H=kv_heads, G=groups, K=head_dim, BK=block_k,
158
+ WINDOW_SIZE_LEFT=window_size_left, BT=tile, BS=tile,
159
+ num_warps=warps, num_stages=stages,
160
+ )
161
+
162
+ _launch("backward", q.device, head_dim, launch)
163
+ if groups == 1:
164
+ return grad_q, grad_r, grad_k_heads, grad_v_heads
165
+ grad_k = reduce(grad_k_heads, "b t (h g) d -> b t h d", g=groups, reduction="sum")
166
+ grad_v = reduce(grad_v_heads, "b t (h g) d -> b t h d", g=groups, reduction="sum")
167
+ return grad_q, grad_r, grad_k, grad_v
168
+
169
+
170
+ class _ParallaxFunction(torch.autograd.Function):
171
+ @staticmethod
172
+ @contiguous
173
+ @autocast_custom_fwd
174
+ def forward(ctx, q, r, k, v, scale, window_size_left, cu_seqlens):
175
+ o, barv, d1, bart, m = _forward(q, r, k, v, scale, cu_seqlens, window_size_left)
176
+ ctx.save_for_backward(q, r, k, v, o, barv, d1, bart, m)
177
+ ctx.scale = scale
178
+ ctx.window_size_left = window_size_left
179
+ ctx.cu_seqlens = cu_seqlens
180
+ return o
181
+
182
+ @staticmethod
183
+ @contiguous
184
+ @autocast_custom_bwd
185
+ def backward(ctx, grad_o):
186
+ saved = ctx.saved_tensors
187
+ grad_q, grad_r, grad_k, grad_v = _backward(
188
+ saved, grad_o, ctx.scale, ctx.cu_seqlens, ctx.window_size_left
189
+ )
190
+ q, r, k, v = saved[:4]
191
+ return grad_q.to(q), grad_r.to(r), grad_k.to(k), grad_v.to(v), None, None, None
192
+
193
+
194
+ def _validate(q: torch.Tensor, r: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> None:
195
+ if q.dtype not in (torch.bfloat16, torch.float16):
196
+ raise TypeError(f"Parallax needs bf16 or fp16 inputs, got {q.dtype}")
197
+ if r.shape != q.shape:
198
+ raise ValueError("r must have the shape of q")
199
+ if k.shape != v.shape or k.shape[0] != q.shape[0] or k.shape[-1] != q.shape[-1]:
200
+ raise ValueError("k and v must share q's batch and head_dim")
201
+ if q.shape[2] % k.shape[2]:
202
+ raise ValueError("query heads must be a multiple of key/value heads")
203
+
204
+
205
+ def parallax_attention(
206
+ q: torch.Tensor,
207
+ r: torch.Tensor,
208
+ k: torch.Tensor,
209
+ v: torch.Tensor,
210
+ *,
211
+ scale: float | None = None,
212
+ window_size: int | None = None,
213
+ cu_seqlens: torch.Tensor | None = None,
214
+ ) -> torch.Tensor:
215
+ """Causal Parallax over ``[batch, length, heads, head_dim]`` inputs with autograd.
216
+
217
+ ``r`` is not scaled; ``scale`` applies to ``q @ kᵀ`` only (default
218
+ ``head_dim ** -0.5``). With ``cu_seqlens`` the batch must be 1 and each
219
+ packed sequence attends only within itself.
220
+ """
221
+
222
+ _validate(q, r, k, v)
223
+ if k.shape[1] != q.shape[1]:
224
+ raise ValueError("training Parallax needs one key per query")
225
+ if cu_seqlens is not None and q.shape[0] != 1:
226
+ raise ValueError("packed sequences (cu_seqlens) need batch size 1")
227
+ if scale is None:
228
+ scale = q.shape[-1] ** -0.5
229
+ window_size_left = -1 if window_size is None else window_size
230
+ return _ParallaxFunction.apply(q, r, k, v, float(scale), window_size_left, cu_seqlens)
231
+
232
+
233
+ @torch.no_grad()
234
+ def parallax_decode_cached(
235
+ q: torch.Tensor,
236
+ r: torch.Tensor,
237
+ k: torch.Tensor,
238
+ v: torch.Tensor,
239
+ *,
240
+ scale: float | None = None,
241
+ window_size: int | None = None,
242
+ cache_start: torch.Tensor | None = None,
243
+ ) -> torch.Tensor:
244
+ """Forward-only Parallax for ``Sq`` new queries over ``Skv >= Sq`` cached keys.
245
+
246
+ Query ``i`` sits at absolute position ``Skv - Sq + i``. One query uses
247
+ fla's vector decode kernel; longer chunks use the tiled prefill kernel.
248
+ """
249
+
250
+ _validate(q, r, k, v)
251
+ batch, queries, query_heads, head_dim = q.shape
252
+ keys, kv_heads = k.shape[1], k.shape[2]
253
+ if keys < queries:
254
+ raise ValueError("the cache must hold at least as many keys as new queries")
255
+ if scale is None:
256
+ scale = head_dim ** -0.5
257
+ if queries == 1:
258
+ return parallax_decode_one_step(q, r, k, v, scale=scale, window_size=window_size, cache_start=cache_start)
259
+ window_size_left = -1 if window_size is None else window_size
260
+ q, r, k, v = (tensor.contiguous() for tensor in (q, r, k, v))
261
+ if cache_start is not None:
262
+ cache_start = cache_start.to(device=q.device, dtype=torch.int32).contiguous()
263
+ o = torch.empty_like(q)
264
+
265
+ def launch(tile: int, warps: int, stages: int) -> None:
266
+ grid = (triton.cdiv(queries, tile), batch * query_heads)
267
+ parallax_decode_kernel[grid](
268
+ q, r, k, v, o, float(scale), cache_start, queries, keys,
269
+ HQ=query_heads, H=kv_heads, G=query_heads // kv_heads, K=head_dim,
270
+ BK=triton.next_power_of_2(head_dim),
271
+ WINDOW_SIZE_LEFT=window_size_left,
272
+ USE_CACHE_START=cache_start is not None,
273
+ BT=tile, BS=tile,
274
+ num_warps=warps, num_stages=stages,
275
+ )
276
+
277
+ _launch("decode", q.device, head_dim, launch)
278
+ return o
279
+
280
+
281
+ @triton.jit(do_not_specialize=["Skv"])
282
+ def _parallax_graph_decode_kernel(
283
+ q,
284
+ r,
285
+ k,
286
+ v,
287
+ o,
288
+ scale,
289
+ cache_end,
290
+ Skv,
291
+ HQ: tl.constexpr,
292
+ H: tl.constexpr,
293
+ G: tl.constexpr,
294
+ K: tl.constexpr,
295
+ BK: tl.constexpr,
296
+ BS: tl.constexpr,
297
+ ):
298
+ """One query per row over a fixed ``Skv`` cache, stopping at that row's ``cache_end``.
299
+
300
+ ``Skv`` stays the buffer length so a CUDA graph can replay the launch while
301
+ each row's live prefix, read from ``cache_end``, changes between replays.
302
+ """
303
+
304
+ i_bh = tl.program_id(0)
305
+ i_b, i_hq = i_bh // HQ, i_bh % HQ
306
+ i_h = i_hq // G
307
+ RCP_LN2: tl.constexpr = 1.4426950216
308
+ kv_hi = tl.load(cache_end + i_b).to(tl.int32)
309
+ kv_hi = tl.minimum(tl.maximum(kv_hi, 0), Skv)
310
+
311
+ p_q = tl.make_block_ptr(q + i_bh * K, (K,), (1,), (0,), (BK,), (0,))
312
+ p_r = tl.make_block_ptr(r + i_bh * K, (K,), (1,), (0,), (BK,), (0,))
313
+ p_o = tl.make_block_ptr(o + i_bh * K, (K,), (1,), (0,), (BK,), (0,))
314
+ b_q = tl.load(p_q, boundary_check=(0,), padding_option="zero").to(tl.float32)
315
+ b_r = tl.load(p_r, boundary_check=(0,), padding_option="zero").to(tl.float32)
316
+ scale_log2 = scale * RCP_LN2
317
+ m = tl.full((1,), -float("inf"), dtype=tl.float32)
318
+ d1 = tl.zeros((1,), dtype=tl.float32)
319
+ d2 = tl.zeros((1,), dtype=tl.float32)
320
+ o1 = tl.zeros((BK,), dtype=tl.float32)
321
+ o2 = tl.zeros((BK,), dtype=tl.float32)
322
+
323
+ p_k = tl.make_block_ptr(k + (i_b * Skv * H + i_h) * K, (Skv, K), (H * K, 1), (0, 0), (BS, BK), (1, 0))
324
+ p_v = tl.make_block_ptr(v + (i_b * Skv * H + i_h) * K, (Skv, K), (H * K, 1), (0, 0), (BS, BK), (1, 0))
325
+ for i_s in range(0, tl.cdiv(kv_hi, BS) * BS, BS):
326
+ col = i_s + tl.arange(0, BS)
327
+ mask = col < kv_hi
328
+ b_k = tl.load(p_k, boundary_check=(0, 1), padding_option="zero")
329
+ b_v = tl.load(p_v, boundary_check=(0, 1), padding_option="zero")
330
+ s1 = tl.sum(b_q[None, :] * b_k, axis=1) * scale_log2
331
+ s2 = tl.sum(b_r[None, :] * b_k, axis=1)
332
+ s1 = tl.where(mask, s1, -float("inf"))
333
+ m_new = tl.maximum(m, tl.max(s1))
334
+ m_safe = tl.where(m_new == -float("inf"), 0.0, m_new)
335
+ alpha = exp2(m - m_safe)
336
+ p1 = exp2(s1 - m_safe)
337
+ p2 = p1 * s2
338
+ d1 = d1 * alpha + tl.sum(p1)
339
+ d2 = d2 * alpha + tl.sum(p2)
340
+ o1 = o1 * alpha + tl.sum(p1[:, None] * b_v, axis=0)
341
+ o2 = o2 * alpha + tl.sum(p2[:, None] * b_v, axis=0)
342
+ m = m_new
343
+ p_k = tl.advance(p_k, (BS, 0))
344
+ p_v = tl.advance(p_v, (BS, 0))
345
+
346
+ inv_d1 = tl.where(d1 > 0.0, 1.0 / d1, 0.0)
347
+ out = o1 * inv_d1 * (1.0 + d2 * inv_d1) - o2 * inv_d1
348
+ tl.store(p_o, out.to(p_o.dtype.element_ty), boundary_check=(0,))
349
+
350
+
351
+ def parallax_graph_decode(
352
+ q: torch.Tensor,
353
+ r: torch.Tensor,
354
+ k: torch.Tensor,
355
+ v: torch.Tensor,
356
+ cache_end: torch.Tensor,
357
+ *,
358
+ scale: float,
359
+ ) -> torch.Tensor:
360
+ """Single-token Parallax over ``k, v`` of ``[rows, capacity, heads, dim]``.
361
+
362
+ Row ``i`` attends to keys ``[0, cache_end[i])``. ``capacity`` is fixed, so
363
+ the launch can be captured in a CUDA graph and replayed as rows grow.
364
+ """
365
+
366
+ _validate(q, r, k, v)
367
+ batch, queries, query_heads, head_dim = q.shape
368
+ if queries != 1:
369
+ raise ValueError(f"graph decode steps one query, got {queries}")
370
+ if cache_end.shape != (batch,):
371
+ raise ValueError("cache_end must hold one length per row")
372
+ kv_heads = k.shape[2]
373
+ q, r, k, v = (tensor.contiguous() for tensor in (q, r, k, v))
374
+ cache_end = cache_end.to(device=q.device, dtype=torch.int32).contiguous()
375
+ out = torch.empty_like(q)
376
+ _parallax_graph_decode_kernel[(batch * query_heads,)](
377
+ q,
378
+ r,
379
+ k,
380
+ v,
381
+ out,
382
+ float(scale),
383
+ cache_end,
384
+ k.shape[1],
385
+ HQ=query_heads,
386
+ H=kv_heads,
387
+ G=query_heads // kv_heads,
388
+ K=head_dim,
389
+ BK=triton.next_power_of_2(head_dim),
390
+ BS=128,
391
+ num_warps=4,
392
+ num_stages=2,
393
+ )
394
+ return out
tiny_gdn/paths.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import errno
4
+ import os
5
+ from pathlib import Path
6
+
7
+ _UNUSABLE_STAT_ERRNOS = {
8
+ errno.ENOENT,
9
+ errno.ENOTDIR,
10
+ errno.EIO,
11
+ errno.ESTALE,
12
+ 5,
13
+ 116,
14
+ }
15
+
16
+ REMOVABLE_MOUNT_PARENTS = (Path("/media"), Path("/mnt"), Path("/run/media"))
17
+ FOUR_TB_DISK = Path("/media/nvidia/4TB")
18
+ FOUR_TB2_DISK = Path("/media/nvidia/4TB2")
19
+
20
+
21
+ def is_usable_path(path: Path, *, directory: bool = False) -> bool:
22
+ """True when `path` can be stat'd. NTFS ESTALE/EIO dentries are False."""
23
+
24
+ try:
25
+ return path.is_dir() if directory else path.is_file() or path.exists()
26
+ except OSError as error:
27
+ if error.errno in _UNUSABLE_STAT_ERRNOS:
28
+ return False
29
+ raise
30
+
31
+
32
+ def is_usable_dir(path: Path) -> bool:
33
+ return is_usable_path(path, directory=True)
34
+
35
+
36
+ def is_usable_file(path: Path) -> bool:
37
+ try:
38
+ return path.is_file()
39
+ except OSError as error:
40
+ if error.errno in _UNUSABLE_STAT_ERRNOS:
41
+ return False
42
+ raise
43
+
44
+
45
+ def resolve_data_path(path: str | Path) -> Path:
46
+ """Resolve a config data path, skipping dead NTFS project symlinks.
47
+
48
+ Configs keep portable values like ``data/tokenized/stage3-sft/manifest.json``.
49
+ When that project symlink is ESTALE/EIO, use ``TINY_GDN_DATA_ROOT`` instead.
50
+ """
51
+
52
+ raw = Path(path)
53
+ candidates: list[Path] = [raw]
54
+ parts = raw.parts
55
+ if len(parts) >= 2 and parts[0] == "data":
56
+ candidates.append(data_root().joinpath(*parts[1:]))
57
+ elif "tokenized" in parts:
58
+ index = parts.index("tokenized")
59
+ candidates.append(data_root().joinpath(*parts[index:]))
60
+ for candidate in candidates:
61
+ if is_usable_file(candidate) or is_usable_dir(candidate):
62
+ try:
63
+ return candidate.resolve()
64
+ except OSError:
65
+ return candidate
66
+ if len(parts) >= 2 and parts[0] == "data":
67
+ return data_root().joinpath(*parts[1:])
68
+ return raw
69
+
70
+
71
+ def project_root() -> Path:
72
+ configured = os.environ.get("TINY_GDN_PROJECT_ROOT")
73
+ if configured:
74
+ return Path(configured).expanduser()
75
+ return Path(__file__).resolve().parents[2]
76
+
77
+
78
+ def _existing_dir(path: Path) -> Path | None:
79
+ try:
80
+ if path.is_dir():
81
+ return path
82
+ except OSError:
83
+ return None
84
+ return None
85
+
86
+
87
+ def data_root() -> Path:
88
+ """Large corpora root (tokenized packs, raw downloads, HF cache).
89
+
90
+ Portable layout is ``<drive>/llm-data`` next to ``<drive>/llm``.
91
+ """
92
+
93
+ configured = os.environ.get("TINY_GDN_DATA_ROOT")
94
+ if configured:
95
+ return Path(configured).expanduser()
96
+ sibling = project_root().parent / "llm-data"
97
+ for candidate in (
98
+ sibling,
99
+ Path("D:/llm-data"),
100
+ Path("/mnt/d/llm-data"),
101
+ Path("/data/llm-data"),
102
+ ):
103
+ found = _existing_dir(candidate)
104
+ if found is not None:
105
+ return found
106
+ if os.name == "nt":
107
+ return Path("D:/llm-data")
108
+ return sibling
109
+
110
+
111
+ def runs_root() -> Path:
112
+ """Checkpoint root. Prefer an explicit env, then a live home mirror.
113
+
114
+ ``~/llm-runs`` wins when present so a laptop WSL tree is not shadowed by
115
+ a portable ``D:/llm-runs`` copy. Native Ubuntu uses the sibling
116
+ ``<drive>/llm-runs`` once home has no runs directory.
117
+ """
118
+
119
+ configured = os.environ.get("TINY_GDN_LINUX_RUNS_ROOT")
120
+ if configured:
121
+ return Path(configured).expanduser()
122
+ home_runs = Path.home() / "llm-runs"
123
+ if _existing_dir(home_runs) is not None:
124
+ return home_runs
125
+ for candidate in (
126
+ project_root().parent / "llm-runs",
127
+ Path("D:/llm-runs"),
128
+ Path("/mnt/d/llm-runs"),
129
+ Path("/data/llm-runs"),
130
+ ):
131
+ found = _existing_dir(candidate)
132
+ if found is not None:
133
+ return found
134
+ return home_runs
135
+
136
+
137
+ def haiku_data_root() -> Path:
138
+ """Haiku corpora and tokenizer live on the system NVMe, not the 4TB disk."""
139
+
140
+ configured = os.environ.get("HAIKU_DATA_ROOT")
141
+ if configured:
142
+ return Path(configured).expanduser()
143
+ return Path.home() / "llm-data" / "haiku"
144
+
145
+
146
+ def haiku_runs_root() -> Path:
147
+ configured = os.environ.get("HAIKU_RUNS_ROOT")
148
+ if configured:
149
+ return Path(configured).expanduser()
150
+ return Path.home() / "llm-runs" / "haiku"
151
+
152
+
153
+ def haiku_checkpoint_root() -> Path:
154
+ """Run directories for new Haiku trains, on 4TB2 so checkpoints stay off the root disk."""
155
+
156
+ configured = os.environ.get("HAIKU_CHECKPOINT_ROOT")
157
+ if configured:
158
+ return Path(configured).expanduser()
159
+ return FOUR_TB2_DISK / "llm-runs" / "haiku"
160
+
161
+
162
+ def senryu_checkpoint_root() -> Path:
163
+ """Senryu run directories, on 4TB2 beside Haiku's. Senryu reads Haiku's data and tokenizer."""
164
+
165
+ configured = os.environ.get("SENRYU_CHECKPOINT_ROOT")
166
+ if configured:
167
+ return Path(configured).expanduser()
168
+ return FOUR_TB2_DISK / "llm-runs" / "senryu"
169
+
170
+
171
+ def senryu2_1b_checkpoint_root() -> Path:
172
+ """Senryu-2-1B run directories, on 4TB2: each checkpoint also carries ~35 GB of n-gram tables."""
173
+
174
+ configured = os.environ.get("SENRYU2_1B_CHECKPOINT_ROOT")
175
+ if configured:
176
+ return Path(configured).expanduser()
177
+ return FOUR_TB2_DISK / "llm-runs" / "senryu-2-1b"
178
+
179
+
180
+ def senryu2_1_1b_checkpoint_root() -> Path:
181
+ """Senryu-2.1-1B run directories, on 4TB2 beside Senryu-2-1B's, with the same n-gram tables."""
182
+
183
+ configured = os.environ.get("SENRYU2_1_1B_CHECKPOINT_ROOT")
184
+ if configured:
185
+ return Path(configured).expanduser()
186
+ return FOUR_TB2_DISK / "llm-runs" / "senryu-2.1-1b"
187
+
188
+
189
+ def prompttercet_checkpoint_root() -> Path:
190
+ """PromptTercet run directories, on 4TB2: checkpoints carry ~17 GB of n-gram tables and moments."""
191
+
192
+ configured = os.environ.get("PROMPTTERCET_CHECKPOINT_ROOT")
193
+ if configured:
194
+ return Path(configured).expanduser()
195
+ return FOUR_TB2_DISK / "llm-runs" / "prompttercet"
196
+
197
+
198
+ def prompttercet1_1_0_5b_checkpoint_root() -> Path:
199
+ """PromptTercet-1.1-0.5B run directories, on 4TB2 beside PromptTercet's, with the same n-gram tables."""
200
+
201
+ configured = os.environ.get("PROMPTTERCET1_1_0_5B_CHECKPOINT_ROOT")
202
+ if configured:
203
+ return Path(configured).expanduser()
204
+ return FOUR_TB2_DISK / "llm-runs" / "prompttercet-1.1-0.5b"
205
+
206
+
207
+ def translate_haiku_data_root() -> Path:
208
+ """TranslateHaiku tokenizer and caches live on NVMe, never on the 9TB corpus disk."""
209
+
210
+ configured = os.environ.get("TRANSLATE_HAIKU_DATA_ROOT")
211
+ if configured:
212
+ return Path(configured).expanduser()
213
+ return Path.home() / "llm-data" / "translate-haiku"
214
+
215
+
216
+ def translate_haiku_runs_root() -> Path:
217
+ configured = os.environ.get("TRANSLATE_HAIKU_RUNS_ROOT")
218
+ if configured:
219
+ return Path(configured).expanduser()
220
+ return Path.home() / "llm-runs" / "translate-haiku"
221
+
222
+
223
+ def assert_translate_write_path(path: Path, *, kind: str = "path") -> Path:
224
+ """Refuse corpus-disk writes. The 4TB2 stick is only for the Windows connector."""
225
+
226
+ resolved = path.expanduser().resolve()
227
+ tercet = tercet_tokenizer_dir().resolve()
228
+ if resolved == tercet or tercet in resolved.parents:
229
+ raise ValueError(f"Refusing to write TranslateHaiku {kind} over the Tercet tokenizer: {resolved}")
230
+ if resolved == FOUR_TB_DISK or FOUR_TB_DISK in resolved.parents:
231
+ raise ValueError(
232
+ f"TranslateHaiku {kind} must stay off the 4TB corpus disk: {resolved}"
233
+ )
234
+ return resolved
235
+
236
+
237
+ def tercet_tokenizer_dir() -> Path:
238
+ return project_root() / "artifacts" / "tokenizer"
239
+
240
+
241
+ def mount_point(path: Path) -> Path:
242
+ """Mount point of the filesystem that holds `path`, or would hold it once created."""
243
+
244
+ current = path.expanduser().resolve()
245
+ while not os.path.ismount(current):
246
+ current = current.parent
247
+ return current
248
+
249
+
250
+ def assert_mounted_write_path(path: Path, *, kind: str = "path") -> Path:
251
+ """Refuse a path under /media, /mnt, or /run/media whose drive is not mounted.
252
+
253
+ Writing through the bare mount point would fill the root filesystem instead.
254
+ """
255
+
256
+ resolved = path.expanduser().resolve()
257
+ mount = mount_point(resolved)
258
+ for parent in REMOVABLE_MOUNT_PARENTS:
259
+ mounted = mount == parent or parent in mount.parents
260
+ if parent in resolved.parents and not mounted:
261
+ raise ValueError(
262
+ f"{kind} {resolved} is not on a mounted drive and would land on "
263
+ f"the filesystem mounted at {mount}; mount the drive first"
264
+ )
265
+ return resolved
266
+
267
+
268
+ def assert_haiku_write_path(path: Path, *, kind: str = "path") -> Path:
269
+ """Refuse writes over the Tercet vocab, onto the 4TB disk, or onto an unmounted drive.
270
+
271
+ The 4TB disk's USB bridge sporadically rejects 16-byte writes and drops them.
272
+ """
273
+
274
+ resolved = path.expanduser().resolve()
275
+ tercet = tercet_tokenizer_dir().resolve()
276
+ if resolved == tercet or tercet in resolved.parents:
277
+ raise ValueError(f"Refusing to write Haiku {kind} over the Tercet tokenizer: {resolved}")
278
+ if resolved == FOUR_TB_DISK or FOUR_TB_DISK in resolved.parents:
279
+ raise ValueError(f"Haiku {kind} must stay off the 4TB disk: {resolved}")
280
+ return assert_mounted_write_path(resolved, kind=f"Haiku {kind}")
281
+
282
+
283
+ def load_hf_token() -> None:
284
+ """Populate ``HF_TOKEN`` from the environment or a standard token file."""
285
+
286
+ existing = os.environ.get("HF_TOKEN") or os.environ.get(
287
+ "HUGGING_FACE_HUB_TOKEN"
288
+ )
289
+ if existing:
290
+ os.environ.setdefault("HF_TOKEN", existing)
291
+ os.environ.setdefault("HUGGING_FACE_HUB_TOKEN", existing)
292
+ return
293
+ candidates = [
294
+ Path.home() / ".cache" / "huggingface" / "token",
295
+ ]
296
+ hf_home = os.environ.get("HF_HOME")
297
+ if hf_home:
298
+ candidates.append(Path(hf_home) / "token")
299
+ candidates.append(data_root() / ".hf" / "token")
300
+ candidates.append(Path("/mnt/c/Users/roblo/.cache/huggingface/token"))
301
+ for path in candidates:
302
+ try:
303
+ if not path.is_file():
304
+ continue
305
+ token = path.read_text(encoding="utf-8").strip()
306
+ except OSError:
307
+ continue
308
+ if not token:
309
+ continue
310
+ os.environ["HF_TOKEN"] = token
311
+ os.environ.setdefault("HUGGING_FACE_HUB_TOKEN", token)
312
+ return
tiny_gdn/senryu2.py ADDED
@@ -0,0 +1,982 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Senryu-2: a Gated DeltaNet-2 + Parallax hybrid on a 4-branch gated residual stream.
2
+
3
+ Every sublayer reads its input from the residual branches through Qwen's
4
+ Gated Residual (per-branch RMSNorm, elementwise sigmoid gate from a low-rank
5
+ bottleneck over all branches) and writes its output back to every branch with
6
+ one data-dependent scalar per branch. A hashed n-gram memory, whose tables live
7
+ in host memory during training, is injected before block ``ngram_layer_index``
8
+ (docs/architecture.md, "Senryu-2").
9
+
10
+ Training and scoring run packed: the batch is flattened into one row and split
11
+ into documents at every BOS token, so GDN-2, Parallax, the n-gram hashes and
12
+ the n-gram convolution never look across a document boundary.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+ from fla.layers.gdn2 import GatedDeltaNet2
25
+ from fla.models.utils import Cache as FlaCache
26
+ from fla.modules.rotary import rotary_embedding
27
+ from safetensors.torch import save_model
28
+ from torch import nn
29
+ from torch.utils.checkpoint import checkpoint
30
+
31
+ from tiny_gdn.config import TinyGDNConfig
32
+ from tiny_gdn.gated_residual_ops import fused_gated_residual_read, fused_gated_residual_write
33
+ from tiny_gdn.haiku_layers import SiTUGLU
34
+ from tiny_gdn.model import TinyGDNOutput, linear_cross_entropy
35
+ from tiny_gdn.ngram import (
36
+ NGRAM_TABLES_EMA_FILE,
37
+ NGRAM_TABLES_FILE,
38
+ NGramLayout,
39
+ document_distance,
40
+ load_table_file,
41
+ ngram_row_indices,
42
+ )
43
+ from tiny_gdn.nn_common import RMSNorm
44
+ from tiny_gdn.parallax_ops import parallax_attention, parallax_decode_cached
45
+
46
+ GATED_RESIDUAL_CHUNK_ROWS = 4096
47
+ KV_CACHE_GRANULE = 256
48
+
49
+
50
+ def mark_muon_row_blocks(parameter: nn.Parameter, blocks: int) -> None:
51
+ """Orthogonalize ``parameter`` as ``blocks`` equal row blocks (heads, fused halves)."""
52
+
53
+ if parameter.shape[0] % blocks:
54
+ raise ValueError(f"{blocks} row blocks do not divide {parameter.shape[0]} rows")
55
+ parameter._muon_row_blocks = blocks
56
+
57
+
58
+ def mark_adamw_only(*parameters: nn.Parameter) -> None:
59
+ """Keep 2D weights that are gates or elongated low-rank maps on AdamW."""
60
+
61
+ for parameter in parameters:
62
+ parameter._adamw_only = True
63
+
64
+
65
+ def mark_gain(*parameters: nn.Parameter) -> None:
66
+ """2D per-branch norm gains and filters: AdamW without weight decay, like 1D gains."""
67
+
68
+ mark_adamw_only(*parameters)
69
+ for parameter in parameters:
70
+ parameter._no_weight_decay = True
71
+
72
+
73
+ # --------------------------------------------------------------------------- layout
74
+
75
+
76
+ @dataclass
77
+ class Senryu2Context:
78
+ """Per-forward state shared by every block (passes through activation checkpointing)."""
79
+
80
+ batch: int
81
+ length: int
82
+ cu_seqlens: torch.Tensor | None
83
+ distance: torch.Tensor | None
84
+ rotary: tuple[torch.Tensor, torch.Tensor]
85
+ position_offset: int = 0
86
+ cache: Senryu2Cache | None = None
87
+
88
+
89
+ class RotaryTables:
90
+ """Partial-RoPE cos/sin rows ``[length, rotary_dim / 2]``, built in FP32 and cached."""
91
+
92
+ def __init__(self, rotary_dim: int, theta: float) -> None:
93
+ self.rotary_dim = rotary_dim
94
+ self.theta = theta
95
+ self._cached: tuple[torch.Tensor, torch.Tensor] | None = None
96
+ self._key: tuple[torch.device, torch.dtype, bool] | None = None
97
+
98
+ def get(self, length: int, device: torch.device, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
99
+ key = (device, dtype, torch.is_inference_mode_enabled())
100
+ cached = self._cached
101
+ if cached is None or self._key != key or cached[0].shape[0] < length:
102
+ rows = max(length, 4096 if cached is None else 2 * cached[0].shape[0])
103
+ inverse_frequency = 1.0 / (
104
+ self.theta
105
+ ** (torch.arange(0, self.rotary_dim, 2, device=device, dtype=torch.float32) / self.rotary_dim)
106
+ )
107
+ angles = torch.outer(torch.arange(rows, device=device, dtype=torch.float32), inverse_frequency)
108
+ cached = (angles.cos().to(dtype), angles.sin().to(dtype))
109
+ self._cached = cached
110
+ self._key = key
111
+ return cached
112
+
113
+
114
+ def parallax_reference(
115
+ q: torch.Tensor,
116
+ r: torch.Tensor,
117
+ k: torch.Tensor,
118
+ v: torch.Tensor,
119
+ *,
120
+ scale: float,
121
+ cu_seqlens: torch.Tensor | None = None,
122
+ ) -> torch.Tensor:
123
+ """FP32 Parallax for queries at the last ``Tq`` of ``Tk`` key positions.
124
+
125
+ ``out = O1 / d1 * (1 + d2 / d1) - O2 / d1`` with ``p1 = exp(scale q·k)``,
126
+ ``p2 = p1 * (r·k)``; ``cu_seqlens`` (batch 1, ``Tq == Tk``) masks across
127
+ packed documents.
128
+ """
129
+
130
+ batch, queries, query_heads, head_dim = q.shape
131
+ keys, kv_heads = k.shape[1], k.shape[2]
132
+ groups = query_heads // kv_heads
133
+ qf = q.float().reshape(batch, queries, kv_heads, groups, head_dim)
134
+ rf = r.float().reshape(batch, queries, kv_heads, groups, head_dim)
135
+ kf, vf = k.float(), v.float()
136
+ s1 = torch.einsum("bqhgd,bkhd->bhgqk", qf, kf) * scale
137
+ s2 = torch.einsum("bqhgd,bkhd->bhgqk", rf, kf)
138
+ query_positions = torch.arange(keys - queries, keys, device=q.device)[:, None]
139
+ key_positions = torch.arange(keys, device=q.device)[None, :]
140
+ masked = key_positions > query_positions
141
+ if cu_seqlens is not None:
142
+ segment = torch.zeros(keys, dtype=torch.long, device=q.device)
143
+ segment[cu_seqlens[1:-1].long()] = 1
144
+ segment = segment.cumsum(0)
145
+ masked = masked | (segment[keys - queries :, None] != segment[None, :])
146
+ s1 = s1.masked_fill(masked, float("-inf"))
147
+ p1 = (s1 - s1.amax(dim=-1, keepdim=True)).exp()
148
+ d1 = p1.sum(dim=-1)
149
+ p2 = p1 * s2
150
+ d2 = p2.sum(dim=-1)
151
+ o1 = torch.einsum("bhgqk,bkhd->bqhgd", p1, vf)
152
+ o2 = torch.einsum("bhgqk,bkhd->bqhgd", p2, vf)
153
+ inverse_d1 = (1.0 / d1).permute(0, 3, 1, 2)[..., None]
154
+ correction = (d2 / d1).permute(0, 3, 1, 2)[..., None]
155
+ out = o1 * inverse_d1 * (1.0 + correction) - o2 * inverse_d1
156
+ return out.reshape(batch, queries, query_heads, head_dim).to(q.dtype)
157
+
158
+
159
+ # ------------------------------------------------------------------ gated residual
160
+
161
+
162
+ class _GatedResidualRead(torch.autograd.Function):
163
+ """``x = (1/n) Σ σ(W_u SiLU(W_d vec(R̂) / n))_i ⊙ R̂_i`` and ``s = 2σ(W_w vec(R̂) / n)``.
164
+
165
+ Saves only the branches, the per-branch inverse RMS and the bottleneck
166
+ pre-activation; the normalized branches and gates are recomputed in
167
+ chunks during backward, so a 32k-token read keeps ~0.4 GB instead of ~4 GB.
168
+ CUDA runs the fused kernels in ``gated_residual_ops`` instead.
169
+ """
170
+
171
+ @staticmethod
172
+ def forward(ctx, residual, gamma, down, up, write, eps):
173
+ rows, branches, hidden_size = residual.shape
174
+ dtype = down.dtype
175
+ gain = 1.0 + gamma.float()
176
+ out = residual.new_empty(rows, hidden_size)
177
+ rstd = residual.new_empty(rows, branches, dtype=torch.float32)
178
+ hidden = residual.new_empty(rows, down.shape[0])
179
+ scales = residual.new_empty(rows, 0 if write is None else branches, dtype=torch.float32)
180
+ for start in range(0, rows, GATED_RESIDUAL_CHUNK_ROWS):
181
+ stop = min(start + GATED_RESIDUAL_CHUNK_ROWS, rows)
182
+ values = residual[start:stop].float()
183
+ chunk_rstd = torch.rsqrt(values.square().mean(dim=-1, keepdim=True) + eps)
184
+ hat = values * chunk_rstd * gain
185
+ flat = hat.to(dtype).flatten(1)
186
+ chunk_hidden = (flat @ down.t()) / branches
187
+ activated = F.silu(chunk_hidden.float()).to(dtype)
188
+ gates = torch.sigmoid((activated @ up.t()).float()).view(stop - start, branches, hidden_size)
189
+ out[start:stop] = ((gates * hat).sum(dim=1) / branches).to(out.dtype)
190
+ rstd[start:stop] = chunk_rstd.squeeze(-1)
191
+ hidden[start:stop] = chunk_hidden
192
+ if write is not None:
193
+ scales[start:stop] = 2.0 * torch.sigmoid((flat @ write.t()).float() / branches)
194
+ ctx.save_for_backward(residual, gamma, down, up, write, rstd, hidden, scales)
195
+ scales_out = scales.to(residual.dtype, copy=True)
196
+ if write is None:
197
+ ctx.mark_non_differentiable(scales_out)
198
+ return out, scales_out
199
+
200
+ @staticmethod
201
+ def backward(ctx, grad_out, grad_scales):
202
+ residual, gamma, down, up, write, rstd, hidden, scales = ctx.saved_tensors
203
+ rows, branches, hidden_size = residual.shape
204
+ dtype = down.dtype
205
+ gain = 1.0 + gamma.float()
206
+ grad_residual = torch.empty(residual.shape, dtype=residual.dtype, device=residual.device)
207
+ grad_gamma = torch.zeros(branches, hidden_size, dtype=torch.float32, device=residual.device)
208
+ grad_down = torch.zeros(down.shape, dtype=torch.float32, device=down.device)
209
+ grad_up = torch.zeros(up.shape, dtype=torch.float32, device=up.device)
210
+ grad_write = None if write is None else torch.zeros(write.shape, dtype=torch.float32, device=write.device)
211
+ use_scales = write is not None and grad_scales is not None
212
+ for start in range(0, rows, GATED_RESIDUAL_CHUNK_ROWS):
213
+ stop = min(start + GATED_RESIDUAL_CHUNK_ROWS, rows)
214
+ count = stop - start
215
+ normalized = residual[start:stop].float() * rstd[start:stop, :, None]
216
+ hat = normalized * gain
217
+ flat = hat.to(dtype).flatten(1)
218
+ pre = hidden[start:stop].float()
219
+ sigmoid_pre = torch.sigmoid(pre)
220
+ activated = (pre * sigmoid_pre).to(dtype)
221
+ gates = torch.sigmoid((activated @ up.t()).float()).view(count, branches, hidden_size)
222
+ grad_x = grad_out[start:stop].float().unsqueeze(1) / branches
223
+ grad_hat = gates * grad_x
224
+ grad_gate_logits = (grad_x * hat * gates * (1.0 - gates)).flatten(1).to(dtype)
225
+ grad_up += (grad_gate_logits.t() @ activated).float()
226
+ grad_activated = (grad_gate_logits @ up).float()
227
+ grad_pre = grad_activated * sigmoid_pre * (1.0 + pre * (1.0 - sigmoid_pre))
228
+ grad_pre = (grad_pre / branches).to(dtype)
229
+ grad_down += (grad_pre.t() @ flat).float()
230
+ grad_flat = (grad_pre @ down).float()
231
+ if use_scales:
232
+ scale_values = scales[start:stop]
233
+ grad_scale_logits = grad_scales[start:stop].float() * scale_values * (1.0 - scale_values / 2.0)
234
+ grad_scale_logits = (grad_scale_logits / branches).to(dtype)
235
+ grad_write += (grad_scale_logits.t() @ flat).float()
236
+ grad_flat += (grad_scale_logits @ write).float()
237
+ grad_hat = grad_hat + grad_flat.view(count, branches, hidden_size)
238
+ grad_gamma += (grad_hat * normalized).sum(dim=0)
239
+ grad_normalized = grad_hat * gain
240
+ grad_residual[start:stop] = (
241
+ rstd[start:stop, :, None]
242
+ * (grad_normalized - normalized * (grad_normalized * normalized).mean(dim=-1, keepdim=True))
243
+ ).to(grad_residual.dtype)
244
+ return (
245
+ grad_residual,
246
+ grad_gamma.to(gamma.dtype),
247
+ grad_down.to(down.dtype),
248
+ grad_up.to(up.dtype),
249
+ None if grad_write is None else grad_write.to(write.dtype),
250
+ None,
251
+ )
252
+
253
+
254
+ def gated_residual_read_reference(
255
+ residual: torch.Tensor,
256
+ gamma: torch.Tensor,
257
+ down: torch.Tensor,
258
+ up: torch.Tensor,
259
+ write: torch.Tensor | None,
260
+ eps: float,
261
+ ) -> tuple[torch.Tensor, torch.Tensor]:
262
+ """Eager autograd version of :class:`_GatedResidualRead`, for tests."""
263
+
264
+ rows, branches, hidden_size = residual.shape
265
+ gain = 1.0 + gamma.float()
266
+ values = residual.float()
267
+ hat = values * torch.rsqrt(values.square().mean(dim=-1, keepdim=True) + eps) * gain
268
+ flat = hat.to(down.dtype).flatten(1)
269
+ hidden = (flat @ down.t()) / branches
270
+ gates = torch.sigmoid((F.silu(hidden.float()).to(up.dtype) @ up.t()).float()).view(rows, branches, hidden_size)
271
+ out = ((gates * hat).sum(dim=1) / branches).to(residual.dtype)
272
+ if write is None:
273
+ return out, residual.new_empty(rows, 0)
274
+ scales = 2.0 * torch.sigmoid((flat @ write.t()).float() / branches)
275
+ return out, scales.to(residual.dtype)
276
+
277
+
278
+ class GatedResidual(nn.Module):
279
+ """Qwen's Gated Residual read (and write scales) over ``branches`` residual branches."""
280
+
281
+ def __init__(self, branches: int, hidden_size: int, rank: int, eps: float, *, write: bool) -> None:
282
+ super().__init__()
283
+ self.branches = branches
284
+ self.eps = eps
285
+ self.weight = nn.Parameter(torch.zeros(branches, hidden_size))
286
+ self.down_proj = nn.Linear(branches * hidden_size, rank, bias=False)
287
+ self.up_proj = nn.Linear(rank, branches * hidden_size, bias=False)
288
+ self.write_proj = nn.Linear(branches * hidden_size, branches, bias=False) if write else None
289
+ mark_gain(self.weight)
290
+ mark_adamw_only(self.down_proj.weight, self.up_proj.weight)
291
+ if self.write_proj is not None:
292
+ mark_adamw_only(self.write_proj.weight)
293
+
294
+ def read(self, residual: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
295
+ """``(x [N, d], scales [N, n])`` from branches ``[N, n, d]``."""
296
+
297
+ write = None if self.write_proj is None else self.write_proj.weight
298
+ read = fused_gated_residual_read if residual.is_cuda else _GatedResidualRead.apply
299
+ return read(residual, self.weight, self.down_proj.weight, self.up_proj.weight, write, self.eps)
300
+
301
+ @staticmethod
302
+ def write(residual: torch.Tensor, scales: torch.Tensor, update: torch.Tensor) -> torch.Tensor:
303
+ if residual.is_cuda:
304
+ return fused_gated_residual_write(residual, scales, update)
305
+ return residual + scales.unsqueeze(-1) * update.unsqueeze(-2)
306
+
307
+
308
+ # ------------------------------------------------------------------- token mixers
309
+
310
+
311
+ class ParallaxAttention(nn.Module):
312
+ """Parallax attention (softmax plus a learned first-order correction from ``r``).
313
+
314
+ Grouped query/key/value heads with per-head zero-centered RMSNorm on q, r
315
+ and k, partial RoPE on q, r and k, and a full-rank sigmoid output gate.
316
+ """
317
+
318
+ def __init__(self, config: TinyGDNConfig, layer_index: int) -> None:
319
+ super().__init__()
320
+ self.layer_index = layer_index
321
+ self.num_heads = config.num_attention_heads
322
+ self.num_kv_heads = config.num_key_value_heads
323
+ self.head_dim = config.attention_head_dim
324
+ self.scale = self.head_dim ** -0.5
325
+ query_width = self.num_heads * self.head_dim
326
+ kv_width = self.num_kv_heads * self.head_dim
327
+ hidden = config.hidden_size
328
+ self.q_proj = nn.Linear(hidden, query_width, bias=False)
329
+ self.r_proj = nn.Linear(hidden, query_width, bias=False)
330
+ self.k_proj = nn.Linear(hidden, kv_width, bias=False)
331
+ self.v_proj = nn.Linear(hidden, kv_width, bias=False)
332
+ self.g_proj = nn.Linear(hidden, query_width, bias=True)
333
+ self.o_proj = nn.Linear(query_width, hidden, bias=False)
334
+ self.q_norm = RMSNorm(self.head_dim, config.rms_norm_eps)
335
+ self.r_norm = RMSNorm(self.head_dim, config.rms_norm_eps)
336
+ self.k_norm = RMSNorm(self.head_dim, config.rms_norm_eps)
337
+ for projection in (self.q_proj, self.r_proj):
338
+ mark_muon_row_blocks(projection.weight, self.num_heads)
339
+ for projection in (self.k_proj, self.v_proj):
340
+ mark_muon_row_blocks(projection.weight, self.num_kv_heads)
341
+ mark_adamw_only(self.g_proj.weight)
342
+
343
+ def forward(self, hidden_states: torch.Tensor, context: Senryu2Context) -> torch.Tensor:
344
+ batch, length, _ = hidden_states.shape
345
+ q = self.q_norm(self.q_proj(hidden_states).view(batch, length, self.num_heads, self.head_dim))
346
+ r = self.r_norm(self.r_proj(hidden_states).view(batch, length, self.num_heads, self.head_dim))
347
+ k = self.k_norm(self.k_proj(hidden_states).view(batch, length, self.num_kv_heads, self.head_dim))
348
+ v = self.v_proj(hidden_states).view(batch, length, self.num_kv_heads, self.head_dim)
349
+ cosine, sine = context.rotary
350
+ q, r, k = (
351
+ rotary_embedding(
352
+ tensor,
353
+ cosine,
354
+ sine,
355
+ seqlen_offsets=context.position_offset,
356
+ cu_seqlens=context.cu_seqlens,
357
+ )
358
+ for tensor in (q, r, k)
359
+ )
360
+ use_kernel = q.is_cuda and q.dtype in (torch.bfloat16, torch.float16)
361
+ cache = context.cache
362
+ if cache is not None:
363
+ keys, values = cache.append_attention(self.layer_index, k, v, context.position_offset)
364
+ if not use_kernel:
365
+ out = parallax_reference(q, r, keys, values, scale=self.scale)
366
+ elif keys.shape[1] == length:
367
+ out = parallax_attention(q, r, keys, values, scale=self.scale)
368
+ else:
369
+ out = parallax_decode_cached(q, r, keys, values, scale=self.scale)
370
+ elif use_kernel:
371
+ out = parallax_attention(q, r, k, v, scale=self.scale, cu_seqlens=context.cu_seqlens)
372
+ else:
373
+ out = parallax_reference(q, r, k, v, scale=self.scale, cu_seqlens=context.cu_seqlens)
374
+ gate = torch.sigmoid(self.g_proj(hidden_states)).view(batch, length, self.num_heads, self.head_dim)
375
+ return self.o_proj((out * gate).reshape(batch, length, self.num_heads * self.head_dim))
376
+
377
+
378
+ def build_gated_deltanet2(config: TinyGDNConfig, layer_index: int) -> GatedDeltaNet2:
379
+ mixer = GatedDeltaNet2(
380
+ hidden_size=config.hidden_size,
381
+ expand_v=config.linear_expand_v,
382
+ head_dim=config.linear_head_dim,
383
+ num_heads=config.linear_num_heads,
384
+ num_v_heads=config.linear_num_value_heads,
385
+ mode="chunk",
386
+ use_short_conv=True,
387
+ allow_neg_eigval=config.allow_negative_eigenvalues,
388
+ conv_size=config.linear_conv_kernel_dim,
389
+ conv_bias=False,
390
+ layer_idx=layer_index,
391
+ norm_eps=config.rms_norm_eps,
392
+ )
393
+ if config.linear_full_rank_gate:
394
+ # The layer calls `self.g_proj(hidden_states)`, so a single full-rank
395
+ # map drops in for fla's low-rank pair.
396
+ mixer.g_proj = nn.Linear(config.hidden_size, mixer.value_dim, bias=True)
397
+ mark_adamw_only(mixer.g_proj.weight)
398
+ else:
399
+ mark_adamw_only(*(layer.weight for layer in mixer.g_proj))
400
+ mark_adamw_only(*(layer.weight for layer in mixer.f_proj))
401
+ for projection in (mixer.q_proj, mixer.k_proj, mixer.b_proj):
402
+ mark_muon_row_blocks(projection.weight, mixer.num_heads)
403
+ for projection in (mixer.v_proj, mixer.w_proj):
404
+ mark_muon_row_blocks(projection.weight, mixer.num_v_heads)
405
+ return mixer
406
+
407
+
408
+ # ------------------------------------------------------------------- n-gram memory
409
+
410
+
411
+ class BranchRMSNorm(nn.Module):
412
+ """Zero-centered RMSNorm over the last dim with one gain vector per branch."""
413
+
414
+ def __init__(self, branches: int, hidden_size: int, eps: float) -> None:
415
+ super().__init__()
416
+ self.weight = nn.Parameter(torch.zeros(branches, hidden_size))
417
+ self.eps = eps
418
+ mark_gain(self.weight)
419
+
420
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
421
+ values = hidden_states.float()
422
+ values = values * torch.rsqrt(values.square().mean(dim=-1, keepdim=True) + self.eps)
423
+ return values * (1.0 + self.weight.float())
424
+
425
+
426
+ class NGramMemory(nn.Module):
427
+ """Engram-style memory: hashed n-gram rows, gated per residual branch, then a short conv.
428
+
429
+ ``e`` concatenates one row per table. Each branch gates the shared value
430
+ ``W_V e`` with ``σ(RMSNorm(R_m) · RMSNorm(W_K,m e) / √d)``; the gated values
431
+ pass a depthwise causal convolution (dilation = largest order, zero init)
432
+ and are added to their branches.
433
+ """
434
+
435
+ def __init__(self, config: TinyGDNConfig) -> None:
436
+ super().__init__()
437
+ self.layout = NGramLayout.from_config(config)
438
+ self.branches = config.residual_branches
439
+ self.hidden_size = config.hidden_size
440
+ self.kernel = config.ngram_conv_kernel
441
+ self.dilation = self.layout.max_order
442
+ memory_dim = self.layout.memory_dim
443
+ self.value_proj = nn.Linear(memory_dim, config.hidden_size, bias=False)
444
+ self.key_proj = nn.Linear(memory_dim, self.branches * config.hidden_size, bias=False)
445
+ self.hidden_norm = BranchRMSNorm(self.branches, config.hidden_size, config.rms_norm_eps)
446
+ self.key_norm = BranchRMSNorm(self.branches, config.hidden_size, config.rms_norm_eps)
447
+ self.conv_norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
448
+ self.conv_weight = nn.Parameter(torch.zeros(config.hidden_size, self.kernel))
449
+ mark_muon_row_blocks(self.key_proj.weight, self.branches)
450
+ mark_gain(self.conv_weight)
451
+ self.register_buffer("canonical_ids", torch.arange(config.vocab_size, dtype=torch.int64), persistent=False)
452
+ self.register_buffer("tables", None, persistent=False)
453
+
454
+ @property
455
+ def conv_history(self) -> int:
456
+ return (self.kernel - 1) * self.dilation
457
+
458
+ def set_canonical_ids(self, canonical: torch.Tensor) -> None:
459
+ if canonical.shape != self.canonical_ids.shape:
460
+ raise ValueError("canonical map does not match the vocabulary")
461
+ self.canonical_ids = canonical.to(device=self.canonical_ids.device, dtype=torch.int64)
462
+
463
+ def attach_tables(self, tables: torch.Tensor, canonical: torch.Tensor) -> None:
464
+ """Look rows up in ``tables [total_rows, embedding_dim]``.
465
+
466
+ The tables may stay in host memory while the model runs on the GPU:
467
+ decoding reads only ``table_count`` rows per token.
468
+ """
469
+
470
+ if tables.shape != (self.layout.total_rows, self.layout.embedding_dim):
471
+ raise ValueError(f"tables have shape {tuple(tables.shape)}")
472
+ self.set_canonical_ids(canonical)
473
+ self.tables = tables
474
+
475
+ def load_tables(self, path: Path, *, device: torch.device | str, dtype: torch.dtype) -> None:
476
+ tables, canonical = load_table_file(path, self.layout, device=device, dtype=dtype)
477
+ self.attach_tables(tables, canonical)
478
+
479
+ def lookup(
480
+ self,
481
+ input_ids: torch.Tensor,
482
+ *,
483
+ distance: torch.Tensor | None = None,
484
+ history: torch.Tensor | None = None,
485
+ ) -> torch.Tensor:
486
+ """Concatenated rows ``[..., memory_dim]`` for every position of ``input_ids``."""
487
+
488
+ if self.tables is None:
489
+ raise RuntimeError(
490
+ "Senryu-2 needs n-gram embeddings: pass ngram_embeddings or attach tables "
491
+ "with model.ngram.load_tables(...)"
492
+ )
493
+ canonical = self.canonical_ids[input_ids]
494
+ indices = ngram_row_indices(canonical, self.layout, distance=distance, history=history)
495
+ tables = self.tables
496
+ if tables.device == indices.device:
497
+ return F.embedding(indices, tables).flatten(-2)
498
+ rows = F.embedding(indices.to(tables.device), tables).flatten(-2)
499
+ return rows.to(indices.device, non_blocking=True)
500
+
501
+ def _convolve(
502
+ self,
503
+ values: torch.Tensor,
504
+ distance: torch.Tensor | None,
505
+ history: torch.Tensor | None,
506
+ ) -> tuple[torch.Tensor, torch.Tensor]:
507
+ """Causal dilated depthwise conv over ``[B, T, n, d]``; returns ``(out, new_history)``."""
508
+
509
+ batch, length = values.shape[:2]
510
+ span = self.conv_history
511
+ if history is None:
512
+ history = values.new_zeros(batch, span, self.branches, self.hidden_size)
513
+ extended = torch.cat([history, values], dim=1)
514
+ weight = self.conv_weight.to(values.dtype)
515
+ out = values * weight[:, -1]
516
+ for tap in range(1, self.kernel):
517
+ shift = tap * self.dilation
518
+ shifted = extended[:, span - shift : span - shift + length]
519
+ if distance is not None:
520
+ shifted = shifted * (distance >= shift).to(values.dtype)[..., None, None]
521
+ out = out + shifted * weight[:, -1 - tap]
522
+ return out, extended[:, -span:]
523
+
524
+ def forward(
525
+ self,
526
+ residual: torch.Tensor,
527
+ embeddings: torch.Tensor,
528
+ *,
529
+ batch: int,
530
+ distance: torch.Tensor | None,
531
+ conv_state: torch.Tensor | None = None,
532
+ ) -> tuple[torch.Tensor, torch.Tensor]:
533
+ """Branch updates ``[N, n, d]`` for branches ``[N, n, d]`` and rows ``[N, memory_dim]``."""
534
+
535
+ rows = residual.shape[0]
536
+ value = self.value_proj(embeddings)
537
+ keys = self.key_proj(embeddings).view(rows, self.branches, self.hidden_size)
538
+ similarity = (self.hidden_norm(residual) * self.key_norm(keys)).sum(dim=-1)
539
+ alpha = torch.sigmoid(similarity / math.sqrt(self.hidden_size)).to(value.dtype)
540
+ gated = alpha.unsqueeze(-1) * value.unsqueeze(1)
541
+ normalized = self.conv_norm(gated).view(batch, rows // batch, self.branches, self.hidden_size)
542
+ convolved, new_state = self._convolve(
543
+ normalized,
544
+ None if distance is None else distance.view(batch, rows // batch),
545
+ conv_state,
546
+ )
547
+ return F.silu(convolved).view(rows, self.branches, self.hidden_size) + gated, new_state
548
+
549
+
550
+ # ------------------------------------------------------------------------- blocks
551
+
552
+
553
+ class Senryu2Block(nn.Module):
554
+ def __init__(self, config: TinyGDNConfig, layer_index: int) -> None:
555
+ super().__init__()
556
+ self.layer_index = layer_index
557
+ self.layer_type = config.layer_types[layer_index]
558
+ residual = (config.residual_branches, config.hidden_size, config.residual_gate_rank, config.rms_norm_eps)
559
+ self.mixer_residual = GatedResidual(*residual, write=True)
560
+ self.mlp_residual = GatedResidual(*residual, write=True)
561
+ if self.layer_type == "gdn2":
562
+ self.token_mixer: nn.Module = build_gated_deltanet2(config, layer_index)
563
+ elif self.layer_type == "parallax":
564
+ self.token_mixer = ParallaxAttention(config, layer_index)
565
+ else:
566
+ raise ValueError(f"Senryu-2 has no {self.layer_type} layers")
567
+ self.mlp = SiTUGLU(config)
568
+ mark_muon_row_blocks(self.mlp.gate_up_proj.weight, 2)
569
+
570
+ def _mix(self, hidden_states: torch.Tensor, context: Senryu2Context) -> torch.Tensor:
571
+ batched = hidden_states.view(context.batch, context.length, -1)
572
+ if self.layer_type == "parallax":
573
+ mixed = self.token_mixer(batched, context)
574
+ else:
575
+ cache = context.cache
576
+ mixed, _, _ = self.token_mixer(
577
+ batched,
578
+ past_key_values=None if cache is None else cache.linear,
579
+ use_cache=cache is not None,
580
+ cu_seqlens=context.cu_seqlens,
581
+ )
582
+ return mixed.reshape(hidden_states.shape)
583
+
584
+ def forward(self, residual: torch.Tensor, context: Senryu2Context) -> torch.Tensor:
585
+ hidden_states, scales = self.mixer_residual.read(residual)
586
+ residual = GatedResidual.write(residual, scales, self._mix(hidden_states, context))
587
+ hidden_states, scales = self.mlp_residual.read(residual)
588
+ return GatedResidual.write(residual, scales, self.mlp(hidden_states))
589
+
590
+
591
+ # -------------------------------------------------------------------------- cache
592
+
593
+
594
+ @dataclass
595
+ class Senryu2Cache:
596
+ """Decode state: GDN-2 states, Parallax keys/values, and the n-gram tails."""
597
+
598
+ linear: Any = field(default_factory=FlaCache)
599
+ keys: dict[int, torch.Tensor] = field(default_factory=dict)
600
+ values: dict[int, torch.Tensor] = field(default_factory=dict)
601
+ length: int = 0
602
+ ngram_tokens: torch.Tensor | None = None
603
+ ngram_conv: torch.Tensor | None = None
604
+
605
+ def append_attention(
606
+ self,
607
+ layer_index: int,
608
+ keys: torch.Tensor,
609
+ values: torch.Tensor,
610
+ start: int,
611
+ ) -> tuple[torch.Tensor, torch.Tensor]:
612
+ """Write ``[B, T, H, D]`` keys/values at ``start``; return views of the whole prefix."""
613
+
614
+ stop = start + keys.shape[1]
615
+ stored_keys = self.keys.get(layer_index)
616
+ if stored_keys is None or stored_keys.shape[1] < stop:
617
+ capacity = max(stop, 0 if stored_keys is None else 2 * stored_keys.shape[1])
618
+ capacity = -(-capacity // KV_CACHE_GRANULE) * KV_CACHE_GRANULE
619
+ grown_keys = keys.new_empty(keys.shape[0], capacity, *keys.shape[2:])
620
+ grown_values = values.new_empty(values.shape[0], capacity, *values.shape[2:])
621
+ if stored_keys is not None:
622
+ grown_keys[:, :start] = stored_keys[:, :start]
623
+ grown_values[:, :start] = self.values[layer_index][:, :start]
624
+ self.keys[layer_index] = stored_keys = grown_keys
625
+ self.values[layer_index] = grown_values
626
+ stored_values = self.values[layer_index]
627
+ stored_keys[:, start:stop] = keys
628
+ stored_values[:, start:stop] = values
629
+ return stored_keys[:, :stop], stored_values[:, :stop]
630
+
631
+
632
+ # -------------------------------------------------------------------------- model
633
+
634
+
635
+ @dataclass
636
+ class _Packing:
637
+ """How a ``[B, T]`` batch maps onto one packed row of ``valid`` tokens."""
638
+
639
+ batch: int
640
+ length: int
641
+ index: torch.Tensor | None
642
+ row_starts: torch.Tensor
643
+
644
+ def pack(self, tensor: torch.Tensor) -> torch.Tensor:
645
+ flat = tensor.reshape(self.batch * self.length, *tensor.shape[2:])
646
+ return flat if self.index is None else flat.index_select(0, self.index)
647
+
648
+ def unpack(self, tensor: torch.Tensor) -> torch.Tensor:
649
+ if self.index is None:
650
+ return tensor.view(self.batch, self.length, *tensor.shape[1:])
651
+ out = tensor.new_zeros(self.batch * self.length, *tensor.shape[1:])
652
+ out.index_copy_(0, self.index, tensor)
653
+ return out.view(self.batch, self.length, *tensor.shape[1:])
654
+
655
+
656
+ class Senryu2ForCausalLM(nn.Module):
657
+ def __init__(self, config: TinyGDNConfig) -> None:
658
+ super().__init__()
659
+ if config.residual_mode != "gated_residual":
660
+ raise ValueError("Senryu2ForCausalLM needs residual_mode 'gated_residual'")
661
+ self.config = config
662
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
663
+ self.layers = nn.ModuleList(Senryu2Block(config, index) for index in range(config.num_hidden_layers))
664
+ self.final_residual = GatedResidual(
665
+ config.residual_branches,
666
+ config.hidden_size,
667
+ config.residual_gate_rank,
668
+ config.rms_norm_eps,
669
+ write=False,
670
+ )
671
+ self.ngram = NGramMemory(config) if config.ngram_orders else None
672
+ self.rotary = RotaryTables(config.rotary_dim, config.rope_theta)
673
+ self.checkpointed_layers: frozenset[int] = frozenset()
674
+ self.apply(self._initialize_module)
675
+ self._initialize_residual_projections()
676
+
677
+ # ---------------------------------------------------------------- setup
678
+ def _initialize_module(self, module: nn.Module) -> None:
679
+ if isinstance(module, nn.Linear):
680
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
681
+ if module.bias is not None:
682
+ nn.init.zeros_(module.bias)
683
+ elif isinstance(module, nn.Embedding):
684
+ nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
685
+
686
+ def _initialize_residual_projections(self) -> None:
687
+ residual_std = self.config.initializer_range / math.sqrt(2 * self.config.num_hidden_layers)
688
+ for layer in self.layers:
689
+ nn.init.normal_(layer.token_mixer.o_proj.weight, mean=0.0, std=residual_std)
690
+ nn.init.normal_(layer.mlp.down_proj.weight, mean=0.0, std=residual_std)
691
+
692
+ def enable_gradient_checkpointing(self, enabled: bool = True, *, layers: int | None = None) -> None:
693
+ """Recompute block activations in backward; ``layers`` picks GDN-2 blocks first."""
694
+
695
+ if not enabled:
696
+ if layers is not None:
697
+ raise ValueError("layers needs gradient checkpointing enabled")
698
+ self.checkpointed_layers = frozenset()
699
+ return
700
+ count = len(self.layers) if layers is None else layers
701
+ if not 1 <= count <= len(self.layers):
702
+ raise ValueError(f"layers must be between 1 and {len(self.layers)}")
703
+ cheapest_replay_first = sorted(
704
+ range(len(self.layers)),
705
+ key=lambda index: self.layers[index].layer_type != "gdn2",
706
+ )
707
+ self.checkpointed_layers = frozenset(cheapest_replay_first[:count])
708
+
709
+ def describe_gradient_checkpointing(self) -> str:
710
+ if not self.checkpointed_layers:
711
+ return "off"
712
+ layer_types = sorted({self.layers[index].layer_type for index in self.checkpointed_layers})
713
+ return f"{len(self.checkpointed_layers)}/{len(self.layers)} blocks ({', '.join(layer_types)})"
714
+
715
+ def project_to_vocabulary(self, hidden_states: torch.Tensor) -> torch.Tensor:
716
+ return F.linear(hidden_states, self.embed_tokens.weight)
717
+
718
+ # -------------------------------------------------------------- packing
719
+ def _packing(self, input_ids: torch.Tensor, attention_mask: torch.Tensor | None) -> _Packing:
720
+ batch, length = input_ids.shape
721
+ device = input_ids.device
722
+ if attention_mask is None or bool(attention_mask.all()):
723
+ row_starts = torch.arange(0, batch * length, length, device=device)
724
+ return _Packing(batch, length, None, row_starts)
725
+ if attention_mask.shape != input_ids.shape:
726
+ raise ValueError("attention_mask must match input_ids")
727
+ valid = attention_mask.reshape(-1).bool()
728
+ index = valid.nonzero().flatten()
729
+ lengths = attention_mask.bool().sum(dim=1)
730
+ if bool((lengths == 0).any()):
731
+ raise ValueError("every row needs at least one unmasked token")
732
+ row_starts = torch.cumsum(lengths, dim=0) - lengths
733
+ return _Packing(batch, length, index, row_starts)
734
+
735
+ def packed_layout(
736
+ self,
737
+ tokens: torch.Tensor,
738
+ row_starts: torch.Tensor | None = None,
739
+ ) -> tuple[torch.Tensor, torch.Tensor]:
740
+ """``(cu_seqlens int32, distance int64)`` for a flat token stream split at BOS."""
741
+
742
+ distance = document_distance(tokens, self.config.bos_token_id, row_starts)
743
+ starts = (distance == 0).nonzero().flatten()
744
+ cu_seqlens = torch.cat([starts, starts.new_tensor([tokens.numel()])]).to(torch.int32)
745
+ return cu_seqlens, distance
746
+
747
+ # -------------------------------------------------------------- forward
748
+ def _run_block(self, index: int, residual: torch.Tensor, context: Senryu2Context) -> torch.Tensor:
749
+ layer = self.layers[index]
750
+ if self.training and index in self.checkpointed_layers:
751
+ return checkpoint(layer, residual, context, use_reentrant=False)
752
+ return layer(residual, context)
753
+
754
+ def _inject_ngrams(
755
+ self,
756
+ residual: torch.Tensor,
757
+ embeddings: torch.Tensor,
758
+ context: Senryu2Context,
759
+ ) -> torch.Tensor:
760
+ assert self.ngram is not None
761
+ cache = context.cache
762
+ conv_state = None if cache is None else cache.ngram_conv
763
+ distance = context.distance if cache is None else None
764
+ if self.training and self.checkpointed_layers:
765
+ update, new_state = checkpoint(
766
+ self.ngram,
767
+ residual,
768
+ embeddings,
769
+ batch=context.batch,
770
+ distance=distance,
771
+ conv_state=conv_state,
772
+ use_reentrant=False,
773
+ )
774
+ else:
775
+ update, new_state = self.ngram(
776
+ residual,
777
+ embeddings,
778
+ batch=context.batch,
779
+ distance=distance,
780
+ conv_state=conv_state,
781
+ )
782
+ if cache is not None:
783
+ cache.ngram_conv = new_state
784
+ return residual + update
785
+
786
+ def _ngram_rows(
787
+ self,
788
+ input_ids: torch.Tensor,
789
+ packing: _Packing | None,
790
+ distance: torch.Tensor | None,
791
+ ngram_embeddings: torch.Tensor | None,
792
+ cache: Senryu2Cache | None,
793
+ ) -> torch.Tensor:
794
+ assert self.ngram is not None
795
+ layout = self.ngram.layout
796
+ if cache is not None:
797
+ history = cache.ngram_tokens
798
+ if history is None:
799
+ history = input_ids.new_full((input_ids.shape[0], layout.max_order - 1), layout.pad_token_id)
800
+ canonical = self.ngram.canonical_ids[input_ids]
801
+ cache.ngram_tokens = torch.cat([history, canonical], dim=1)[:, -(layout.max_order - 1) :]
802
+ if ngram_embeddings is not None:
803
+ return ngram_embeddings.reshape(-1, layout.memory_dim)
804
+ return self.ngram.lookup(input_ids, history=history).reshape(-1, layout.memory_dim)
805
+ assert packing is not None
806
+ if ngram_embeddings is not None:
807
+ if ngram_embeddings.shape != (*input_ids.shape, layout.memory_dim):
808
+ raise ValueError(
809
+ f"ngram_embeddings must have shape {(*input_ids.shape, layout.memory_dim)}"
810
+ )
811
+ return packing.pack(ngram_embeddings)
812
+ return self.ngram.lookup(packing.pack(input_ids), distance=distance)
813
+
814
+ def forward(
815
+ self,
816
+ input_ids: torch.Tensor,
817
+ labels: torch.Tensor | None = None,
818
+ attention_mask: torch.Tensor | None = None,
819
+ past_key_values: Senryu2Cache | None = None,
820
+ *,
821
+ use_cache: bool = False,
822
+ return_logits: bool = True,
823
+ return_hidden_states: bool = False,
824
+ labels_are_shifted: bool = False,
825
+ include_mtp_loss: bool = True,
826
+ mtp_loss_weight: float | None = None,
827
+ z_loss_coefficient: float = 0.0,
828
+ logits_to_keep: int | None = None,
829
+ ngram_embeddings: torch.Tensor | None = None,
830
+ ) -> TinyGDNOutput:
831
+ del include_mtp_loss, mtp_loss_weight
832
+ if input_ids.ndim != 2:
833
+ raise ValueError("input_ids must have shape [batch, sequence]")
834
+ if labels is not None and labels.shape != input_ids.shape:
835
+ raise ValueError("labels must have the same shape as input_ids")
836
+ if z_loss_coefficient < 0.0:
837
+ raise ValueError("z_loss_coefficient cannot be negative")
838
+ if logits_to_keep is not None and logits_to_keep <= 0:
839
+ raise ValueError("logits_to_keep must be positive")
840
+ if use_cache and labels is not None:
841
+ raise ValueError("use_cache is not supported with labels")
842
+ if past_key_values is not None and not isinstance(past_key_values, Senryu2Cache):
843
+ raise TypeError("past_key_values must be a Senryu2Cache or None")
844
+ cached = use_cache or past_key_values is not None
845
+ batch, length = input_ids.shape
846
+ offset = 0 if past_key_values is None else past_key_values.length
847
+ if offset + length > self.config.max_position_embeddings:
848
+ raise ValueError("Input exceeds max_position_embeddings")
849
+
850
+ embeddings = self.embed_tokens(input_ids)
851
+ device, dtype = embeddings.device, embeddings.dtype
852
+ packing: _Packing | None = None
853
+ distance: torch.Tensor | None = None
854
+ if cached:
855
+ if attention_mask is not None and not bool(attention_mask.all()):
856
+ raise ValueError("Senryu-2 decodes unpadded rows; drop the padding instead of masking it")
857
+ cache = past_key_values if past_key_values is not None else Senryu2Cache()
858
+ context = Senryu2Context(
859
+ batch=batch,
860
+ length=length,
861
+ cu_seqlens=None,
862
+ distance=None,
863
+ rotary=self.rotary.get(offset + length, device, dtype),
864
+ position_offset=offset,
865
+ cache=cache,
866
+ )
867
+ hidden = embeddings.reshape(batch * length, -1)
868
+ else:
869
+ cache = None
870
+ packing = self._packing(input_ids, attention_mask)
871
+ tokens = packing.pack(input_ids)
872
+ cu_seqlens, distance = self.packed_layout(tokens, packing.row_starts)
873
+ context = Senryu2Context(
874
+ batch=1,
875
+ length=tokens.numel(),
876
+ cu_seqlens=cu_seqlens,
877
+ distance=distance,
878
+ rotary=self.rotary.get(tokens.numel(), device, dtype),
879
+ )
880
+ hidden = packing.pack(embeddings)
881
+ residual = hidden.unsqueeze(1).expand(-1, self.config.residual_branches, -1)
882
+
883
+ for index in range(len(self.layers)):
884
+ if self.ngram is not None and index == self.config.ngram_layer_index:
885
+ rows = self._ngram_rows(input_ids, packing, distance, ngram_embeddings, cache)
886
+ residual = self._inject_ngrams(residual, rows.to(dtype), context)
887
+ residual = self._run_block(index, residual, context)
888
+ hidden_states, _ = self.final_residual.read(residual)
889
+ if cache is not None:
890
+ cache.length = offset + length
891
+
892
+ main_loss = None
893
+ z_loss = None
894
+ total_loss = None
895
+ if labels is not None:
896
+ assert packing is not None
897
+ if labels_are_shifted:
898
+ targets = labels
899
+ else:
900
+ targets = torch.cat([labels[:, 1:], labels.new_full((batch, 1), -100)], dim=1)
901
+ total_loss, main_loss, z_loss = linear_cross_entropy(
902
+ hidden_states,
903
+ self.embed_tokens.weight,
904
+ packing.pack(targets).reshape(-1),
905
+ z_loss_coefficient=z_loss_coefficient,
906
+ )
907
+ if z_loss_coefficient == 0.0:
908
+ z_loss = None
909
+
910
+ batched_states = (
911
+ hidden_states.view(batch, length, -1) if packing is None else packing.unpack(hidden_states)
912
+ )
913
+ output_states = batched_states if logits_to_keep is None else batched_states[:, -logits_to_keep:]
914
+ logits = self.project_to_vocabulary(output_states) if return_logits else None
915
+ return TinyGDNOutput(
916
+ loss=total_loss,
917
+ logits=logits,
918
+ main_loss=main_loss,
919
+ mtp_loss=None,
920
+ z_loss=z_loss,
921
+ hidden_states=batched_states if return_hidden_states else None,
922
+ past_key_values=cache if use_cache else None,
923
+ )
924
+
925
+ # ------------------------------------------------------------ reporting
926
+ def parameter_report(self) -> dict[str, int]:
927
+ total = sum(parameter.numel() for parameter in self.parameters())
928
+ embeddings = self.embed_tokens.weight.numel()
929
+ tables = 0 if self.ngram is None else self.ngram.layout.total_rows * self.ngram.layout.embedding_dim
930
+ return {
931
+ "deployable_core": total,
932
+ "training_total": total,
933
+ "embedding": embeddings,
934
+ "mtp_auxiliary": 0,
935
+ "non_embedding_core": total - embeddings,
936
+ "ngram_table": tables,
937
+ }
938
+
939
+ def save_checkpoint(self, output_dir: Path) -> None:
940
+ output_dir.mkdir(parents=True, exist_ok=True)
941
+ self.config.save_json(output_dir / "config.json")
942
+ save_model(self, output_dir / "model.safetensors")
943
+
944
+ def load_ngram_tables(
945
+ self,
946
+ checkpoint_dir: Path,
947
+ *,
948
+ weights: str,
949
+ device: str | torch.device,
950
+ dtype: torch.dtype,
951
+ ) -> None:
952
+ """Attach the checkpoint's tables that match ``weights`` ("normal" or "ema")."""
953
+
954
+ if self.ngram is None:
955
+ return
956
+ table_file = checkpoint_dir / (NGRAM_TABLES_EMA_FILE if weights == "ema" else NGRAM_TABLES_FILE)
957
+ if not table_file.is_file():
958
+ raise FileNotFoundError(f"Senryu-2 checkpoint has no n-gram tables: {table_file}")
959
+ self.ngram.load_tables(table_file, device=device, dtype=dtype)
960
+
961
+ def extra_repr(self) -> str:
962
+ report = self.parameter_report()
963
+ return f"core_parameters={report['deployable_core']:,}, ngram_table_parameters={report['ngram_table']:,}"
964
+
965
+ def get_architecture_metadata(self) -> dict[str, Any]:
966
+ return {
967
+ "architecture": self.config.architecture,
968
+ "layer_types": list(self.config.layer_types),
969
+ "effective_num_layers": self.config.effective_num_layers,
970
+ "shared_layer_indices": [],
971
+ "parameter_report": self.parameter_report(),
972
+ "features": [
973
+ "3:1 Gated DeltaNet-2 + Parallax attention hybrid",
974
+ "4-branch Gated Residual stream (gated read, per-branch write scales)",
975
+ "hashed n-gram memory (orders 2-3) with per-branch context gating",
976
+ "full-rank sigmoid output gates",
977
+ "partial RoPE, per-head QK/R normalization",
978
+ "SiTU-GLU",
979
+ "document-masked packed training",
980
+ "tied input-output embeddings",
981
+ ],
982
+ }
tiny_gdn/senryu_chat.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The chat defaults Senryu-2.1 trained with: its system prompt and its tools.
2
+
3
+ Conversations without a system prompt of their own opened with this prompt,
4
+ dated the day they were written, and listed these three tools in this order.
5
+ Inference that fills in today's date and offers the same tools gives the
6
+ model the context it learned to answer in.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import date
12
+ from typing import Any
13
+
14
+ from tiny_gdn.code_exec import CALCULATOR_TOOL
15
+ from tiny_gdn.web_fetch import FETCH_PAGE_TOOL
16
+ from tiny_gdn.web_search import NEMOTRON_WEB_SEARCH_TOOL
17
+
18
+ SENRYU_2_1_NAME = "Senryu-2.1"
19
+ SENRYU_TOOLS: tuple[dict[str, Any], ...] = (NEMOTRON_WEB_SEARCH_TOOL, FETCH_PAGE_TOOL, CALCULATOR_TOOL)
20
+ # SENRYU_TOOLS as a cli_chat.resolve_cli_tools spec.
21
+ SENRYU_TOOL_SPEC = "web-search,fetch-page,calculator"
22
+
23
+ # Spelled out rather than taken from the locale, so the date reads as in training on any host.
24
+ _WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
25
+ _MONTHS = (
26
+ "January",
27
+ "February",
28
+ "March",
29
+ "April",
30
+ "May",
31
+ "June",
32
+ "July",
33
+ "August",
34
+ "September",
35
+ "October",
36
+ "November",
37
+ "December",
38
+ )
39
+
40
+ _RULES = r"""Tool Rules:
41
+ - Answer from your own knowledge whenever you can. Most requests need no tools.
42
+ - **Use web search sparingly, only when it is absolutely necessary:** for news and events after your training, live data such as prices, scores or weather, or a precise fact the user needs and you don't know. Never search for things you can answer yourself, such as explanations, definitions, how-tos, code, math, writing or advice, and never search just to double-check what you already know.
43
+ - When you must search, use one focused query and answer from its results. Search again only if they leave the question unanswered.
44
+ - Fetch a page only when the user links one or a search result you need is cut short.
45
+ - Use the calculator for arithmetic you can't reliably do in your head.
46
+
47
+ Formatting Rules:
48
+ - Use Markdown for lists, tables, and styling.
49
+ - Use ```code fences``` for all code blocks.
50
+ - Format file names, paths, and function names with `inline code` backticks.
51
+ - **For all mathematical expressions, you must use dollar-sign delimiters. Use $...$ for inline math and $$...$$ for block math. Do not use \(...\) or \[...\] delimiters.**
52
+ - For responses with many sections where some are more important than others, use collapsible sections (HTML details/summary tags) to highlight key information while allowing users to expand less critical details."""
53
+
54
+
55
+ def prompt_date(day: date) -> str:
56
+ """``Sunday, October 25, 2026``: the date as the prompt states it."""
57
+
58
+ return f"{_WEEKDAYS[day.weekday()]}, {_MONTHS[day.month - 1]} {day.day}, {day.year}"
59
+
60
+
61
+ def senryu_system_prompt(name: str = SENRYU_2_1_NAME, today: date | None = None) -> str:
62
+ """The trained default system prompt for model ``name``, dated ``today`` (default: the local date)."""
63
+
64
+ day = today if today is not None else date.today()
65
+ return (
66
+ f"You are {name}, a large language model from KerzgrAI. Today's date is {prompt_date(day)}.\n\n{_RULES}"
67
+ )
tiny_gdn/smoltalk_chat.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SmolTalk2 / SmolLM3 chat-template contract for Tercet-R.
2
+
3
+ The SFT subset stores the toggle and tools in `chat_template_kwargs`:
4
+
5
+ - `enable_thinking`: True → assistant turns receive a zero-loss
6
+ `<|think|>\\n` control prefix; assistant targets may emit `<think>` naturally
7
+ - `enable_thinking`: False → assistant turns receive a zero-loss
8
+ `<|no_think|>\\n` control prefix
9
+ - `custom_instructions`: the system prompt, used verbatim. Only the SmolLM3
10
+ template directives `/think`, `/no_think`, and `/system_override` are
11
+ removed because they are control markers, not prompt text
12
+ - `xml_tools` / `python_tools`: appended to the system prompt as a Hermes
13
+ `<tools>` block only when tools are present and the prompt does not already
14
+ carry one
15
+ - `tool_format` (inference only): "auto" and "json" render Hermes JSON
16
+ `<tool_call>` blocks, the layout the served models were trained on. "xml"
17
+ is Cascade's OpenHands layout and is used only when a request asks for it
18
+
19
+ There is no default identity, metadata header, or wrapper: a conversation
20
+ without a system prompt and without tools has no system turn at all.
21
+
22
+ Tool results (`tool` / `function` roles, or text still wrapped in Nemotron
23
+ `<tool_response>` XML) are rendered as a user turn where every result is
24
+ prefixed with the `<|tool_response|>` special token.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import re
31
+ from dataclasses import dataclass, replace
32
+ from typing import Any, Literal
33
+
34
+ from tiny_gdn.tools import (
35
+ json_ready,
36
+ TOOL_RESPONSE_CLOSE,
37
+ TOOL_RESPONSE_OPEN,
38
+ TOOLS_CLOSE,
39
+ TOOLS_OPEN,
40
+ assistant_message_content,
41
+ coerce_tools,
42
+ format_tool_calls_xml,
43
+ loads_json,
44
+ message_text,
45
+ parse_arguments_payload,
46
+ render_available_tools,
47
+ strip_leaked_chatml,
48
+ )
49
+
50
+
51
+ ReasoningMode = Literal["/think", "/no_think"]
52
+ ToolFormat = Literal["json", "xml"]
53
+ ToolFormatChoice = Literal["auto", "json", "xml"]
54
+
55
+ NO_THINK_TOKEN = "<|no_think|>"
56
+ NO_THINK_PREFIX = f"{NO_THINK_TOKEN}\n"
57
+ THINK_CONTROL_TOKEN = "<|think|>"
58
+ THINK_CONTROL_PREFIX = f"{THINK_CONTROL_TOKEN}\n"
59
+ TOOL_RESPONSE_TOKEN = "<|tool_response|>"
60
+ TOOL_RESPONSE_PREFIX = f"{TOOL_RESPONSE_TOKEN}\n"
61
+ THINK_OPEN = "<think>"
62
+ THINK_CLOSE = "</think>"
63
+ TOOL_CALL_OPEN = "<tool_call>"
64
+ TOOL_CALL_CLOSE = "</tool_call>"
65
+ SYSTEM_OVERRIDE_MARK = "/system_override"
66
+ THINK_MARK = "/think"
67
+ NO_THINK_MARK = "/no_think"
68
+
69
+ # SmolTalk2 SFT used this markdown web_search schema. Tercet-R stage-3
70
+ # packs Nemotron Agentic-v2 search instead (`web-search` + Tavily JSON);
71
+ # see tiny_gdn.web_search.NEMOTRON_WEB_SEARCH_TOOL.
72
+ SMOLTALK_WEB_SEARCH_TOOL = {
73
+ "type": "function",
74
+ "function": {
75
+ "name": "web_search",
76
+ "description": (
77
+ "Performs a web search for a query and returns a string of the "
78
+ "top search results formatted as markdown with titles, links, "
79
+ "and descriptions."
80
+ ),
81
+ "parameters": {
82
+ "type": "object",
83
+ "properties": {
84
+ "query": {
85
+ "type": "string",
86
+ "description": "The search query to perform.",
87
+ }
88
+ },
89
+ "required": ["query"],
90
+ },
91
+ },
92
+ }
93
+ XML_TOOLS_PREAMBLE = (
94
+ "You may call one or more functions to assist with the user query.\n"
95
+ "You are provided with function signatures within <tools></tools> XML "
96
+ "tags:\n<tools>\n"
97
+ )
98
+ XML_TOOLS_EPILOGUE = (
99
+ "</tools>\n\n"
100
+ "For each function call, return a json object with function name and "
101
+ "arguments within <tool_call></tool_call> XML tags:\n"
102
+ "<tool_call>\n"
103
+ '{"name": <function-name>, "arguments": <args-json-object>}\n'
104
+ "</tool_call>"
105
+ )
106
+ PYTHON_TOOLS_PREAMBLE = (
107
+ "When you send a message containing Python code between '<code>' and "
108
+ "'</code>' tags, it will be executed in a stateful Jupyter notebook "
109
+ "environment, and you will then be given the output to continued "
110
+ "reasoning in an agentic loop.\n\n"
111
+ "You can use the following tools in your python code like regular "
112
+ "functions:\n<tools>\n"
113
+ )
114
+ PYTHON_TOOLS_EPILOGUE = (
115
+ "</tools>\n\n"
116
+ "The state persists between code executions: so variables that you "
117
+ "define in one step are still available thereafter."
118
+ )
119
+ _EMPTY_THINK_BLOCK = re.compile(
120
+ re.escape(THINK_OPEN) + r"\s*" + re.escape(THINK_CLOSE)
121
+ )
122
+
123
+
124
+ @dataclass(frozen=True)
125
+ class ChatTemplateKwargs:
126
+ custom_instructions: str = ""
127
+ enable_thinking: bool = True
128
+ xml_tools: tuple[str, ...] = ()
129
+ python_tools: tuple[str, ...] = ()
130
+ tool_format: ToolFormat = "json"
131
+
132
+
133
+ def coerce_tool_strings(raw_tools: Any) -> tuple[str, ...]:
134
+ if raw_tools is None:
135
+ return ()
136
+ if isinstance(raw_tools, str):
137
+ text = raw_tools.strip()
138
+ return (text,) if text else ()
139
+ if isinstance(raw_tools, dict):
140
+ raw_tools = [raw_tools]
141
+ if not isinstance(raw_tools, list):
142
+ return ()
143
+ rendered: list[str] = []
144
+ for item in raw_tools:
145
+ if isinstance(item, str):
146
+ text = item.strip()
147
+ if text:
148
+ rendered.append(text)
149
+ continue
150
+ if isinstance(item, dict):
151
+ rendered.append(json.dumps(item, ensure_ascii=False))
152
+ return tuple(rendered)
153
+
154
+
155
+ def parse_chat_template_kwargs(raw: Any) -> ChatTemplateKwargs:
156
+ if raw is None:
157
+ return ChatTemplateKwargs()
158
+ if isinstance(raw, str):
159
+ text = raw.strip()
160
+ if not text:
161
+ return ChatTemplateKwargs()
162
+ raw = json.loads(text)
163
+ if not isinstance(raw, dict):
164
+ return ChatTemplateKwargs()
165
+ enable = raw.get("enable_thinking")
166
+ if enable is None:
167
+ enable_thinking = True
168
+ elif isinstance(enable, bool):
169
+ enable_thinking = enable
170
+ else:
171
+ enable_thinking = str(enable).strip().lower() in {"1", "true", "yes", "on"}
172
+ custom = raw.get("custom_instructions")
173
+ return ChatTemplateKwargs(
174
+ custom_instructions=custom if isinstance(custom, str) else "",
175
+ enable_thinking=enable_thinking,
176
+ xml_tools=coerce_tool_strings(raw.get("xml_tools")),
177
+ python_tools=coerce_tool_strings(raw.get("python_tools")),
178
+ )
179
+
180
+
181
+ def resolve_reasoning_mode(
182
+ enable_thinking: bool,
183
+ custom_instructions: str,
184
+ ) -> ReasoningMode:
185
+ if NO_THINK_MARK in custom_instructions:
186
+ return "/no_think"
187
+ if THINK_MARK in custom_instructions:
188
+ return "/think"
189
+ return "/think" if enable_thinking else "/no_think"
190
+
191
+
192
+ def strip_template_markers(custom_instructions: str) -> str:
193
+ return (
194
+ custom_instructions.replace(NO_THINK_MARK, "")
195
+ .replace(THINK_MARK, "")
196
+ .replace(SYSTEM_OVERRIDE_MARK, "")
197
+ .strip()
198
+ )
199
+
200
+
201
+ def strip_tools_wrapper(item: str) -> str:
202
+ """Drop a `<tools>` / `</tools>` wrapper some sources bake into each entry."""
203
+
204
+ text = item.strip()
205
+ if text.startswith(TOOLS_OPEN):
206
+ text = text[len(TOOLS_OPEN) :]
207
+ if text.endswith(TOOLS_CLOSE):
208
+ text = text[: -len(TOOLS_CLOSE)]
209
+ return text.strip()
210
+
211
+
212
+ def render_xml_tools_block(xml_tools: tuple[str, ...]) -> str:
213
+ entries = [strip_tools_wrapper(item) for item in xml_tools]
214
+ entries = [item for item in entries if item]
215
+ if not entries:
216
+ return ""
217
+ body = "".join(f"{item}\n" for item in entries)
218
+ return f"{XML_TOOLS_PREAMBLE}{body}{XML_TOOLS_EPILOGUE}"
219
+
220
+
221
+ def render_cascade_tools_block(xml_tools: tuple[str, ...]) -> str:
222
+ """The same tools in Nemotron Cascade-2's layout: XML schemas, `<function=…>` calls."""
223
+
224
+ entries = [strip_tools_wrapper(item) for item in xml_tools]
225
+ return render_available_tools([loads_json(item) for item in entries if item])
226
+
227
+
228
+ def render_python_tools_block(python_tools: tuple[str, ...]) -> str:
229
+ entries = [strip_tools_wrapper(item) for item in python_tools]
230
+ entries = [item for item in entries if item]
231
+ if not entries:
232
+ return ""
233
+ body = "".join(f"{item}\n" for item in entries)
234
+ return f"{PYTHON_TOOLS_PREAMBLE}{body}{PYTHON_TOOLS_EPILOGUE}"
235
+
236
+
237
+ def unwrap_tool_result(content: str) -> str:
238
+ """Return the bare tool output, without ChatML leaks or `<tool_response>` XML."""
239
+
240
+ text = strip_leaked_chatml(content).strip()
241
+ if text.startswith(TOOL_RESPONSE_TOKEN):
242
+ text = text[len(TOOL_RESPONSE_TOKEN) :].strip()
243
+ if TOOL_RESPONSE_OPEN in text:
244
+ chunks: list[str] = []
245
+ cursor = 0
246
+ while True:
247
+ start = text.find(TOOL_RESPONSE_OPEN, cursor)
248
+ if start < 0:
249
+ tail = text[cursor:].strip()
250
+ if tail:
251
+ chunks.append(tail)
252
+ break
253
+ head = text[cursor:start].strip()
254
+ if head:
255
+ chunks.append(head)
256
+ start += len(TOOL_RESPONSE_OPEN)
257
+ end = text.find(TOOL_RESPONSE_CLOSE, start)
258
+ if end < 0:
259
+ inner = text[start:].strip()
260
+ cursor = len(text)
261
+ else:
262
+ inner = text[start:end].strip()
263
+ cursor = end + len(TOOL_RESPONSE_CLOSE)
264
+ if inner:
265
+ chunks.append(inner)
266
+ if cursor >= len(text):
267
+ break
268
+ text = "\n".join(chunks)
269
+ return text
270
+
271
+
272
+ def wrap_smoltalk_tool_result(content: str) -> str:
273
+ text = unwrap_tool_result(content)
274
+ if not text:
275
+ return ""
276
+ return f"{TOOL_RESPONSE_PREFIX}{text}"
277
+
278
+
279
+ def strip_empty_think_blocks(content: str) -> str:
280
+ """Drop `<think>` spans whose body is empty or whitespace-only.
281
+
282
+ Nemotron and similar traces sometimes emit `<think></think>` or
283
+ `<think>\\n</think>` with no reasoning. Those are not think turns.
284
+ """
285
+
286
+ stripped = _EMPTY_THINK_BLOCK.sub("", content)
287
+ if stripped == content:
288
+ return content
289
+ return stripped.lstrip("\r\n")
290
+
291
+
292
+ def rewrite_tool_result_content(content: str) -> str:
293
+ stripped = content.lstrip()
294
+ if stripped.startswith(TOOL_RESPONSE_TOKEN) and TOOL_RESPONSE_OPEN not in stripped:
295
+ return content
296
+ text = strip_leaked_chatml(content).strip()
297
+ if TOOL_RESPONSE_OPEN in text:
298
+ chunks: list[str] = []
299
+ cursor = 0
300
+ while True:
301
+ start = text.find(TOOL_RESPONSE_OPEN, cursor)
302
+ if start < 0:
303
+ break
304
+ start += len(TOOL_RESPONSE_OPEN)
305
+ end = text.find(TOOL_RESPONSE_CLOSE, start)
306
+ inner = (text[start:end] if end >= 0 else text[start:]).strip()
307
+ if inner:
308
+ chunks.append(wrap_smoltalk_tool_result(inner))
309
+ if end < 0:
310
+ break
311
+ cursor = end + len(TOOL_RESPONSE_CLOSE)
312
+ if chunks:
313
+ return "\n".join(chunks)
314
+ return wrap_smoltalk_tool_result(text)
315
+
316
+
317
+ def apply_reasoning_and_tool_controls(messages: list[dict[str, str]]) -> list[dict[str, str]]:
318
+ """Attach Haiku/Tercet-R control tokens to any ChatML conversation.
319
+
320
+ Assistant turns without a `masked_prefix` get `<|think|>` when the
321
+ content already contains a `<think>` block, otherwise `<|no_think|>`.
322
+ Empty or whitespace-only `<think>` spans are stripped and treated as
323
+ no-think, including when a think prefix was already attached.
324
+ `tool` roles and Nemotron `<tool_response>` user turns become user
325
+ turns prefixed with the `<|tool_response|>` special.
326
+ Existing prefixes and already-rewritten tool results are left alone
327
+ unless an empty think block was removed and no real think remains.
328
+ """
329
+
330
+ prepared: list[dict[str, str]] = []
331
+ pending: list[str] = []
332
+
333
+ def flush_tools() -> None:
334
+ if pending:
335
+ prepared.append({"role": "user", "content": "\n".join(pending)})
336
+ pending.clear()
337
+
338
+ for message in messages:
339
+ role = message["role"]
340
+ content = message["content"]
341
+ if role == "tool":
342
+ rewritten = rewrite_tool_result_content(content)
343
+ if rewritten:
344
+ pending.append(rewritten)
345
+ continue
346
+ if role == "user" and (
347
+ content.lstrip().startswith(TOOL_RESPONSE_TOKEN)
348
+ or TOOL_RESPONSE_OPEN in content
349
+ ):
350
+ rewritten = rewrite_tool_result_content(content)
351
+ if rewritten:
352
+ pending.append(rewritten)
353
+ continue
354
+ flush_tools()
355
+ if role == "assistant":
356
+ rendered = dict(message)
357
+ original = content
358
+ content = strip_empty_think_blocks(content)
359
+ rendered["content"] = content
360
+ has_think = THINK_OPEN in content
361
+ existing_prefix = rendered.get("masked_prefix")
362
+ if not existing_prefix:
363
+ rendered["masked_prefix"] = (
364
+ THINK_CONTROL_PREFIX if has_think else NO_THINK_PREFIX
365
+ )
366
+ elif content != original and not has_think:
367
+ rendered["masked_prefix"] = NO_THINK_PREFIX
368
+ prepared.append(rendered)
369
+ continue
370
+ prepared.append(dict(message))
371
+ flush_tools()
372
+ return prepared
373
+
374
+
375
+ def openai_tools_as_xml_strings(raw_tools: Any) -> tuple[str, ...]:
376
+ if raw_tools is None:
377
+ return ()
378
+ rendered: list[str] = []
379
+ for tool in coerce_tools(raw_tools):
380
+ rendered.append(
381
+ json.dumps(
382
+ json_ready({"type": "function", "function": tool}),
383
+ ensure_ascii=False,
384
+ default=str,
385
+ )
386
+ )
387
+ return tuple(rendered)
388
+
389
+
390
+ def format_smoltalk_tool_call(name: str, arguments: dict[str, Any]) -> str:
391
+ payload = {"name": name, "arguments": json_ready(arguments)}
392
+ return (
393
+ f"{TOOL_CALL_OPEN}\n"
394
+ f"{json.dumps(payload, ensure_ascii=False, default=str)}\n"
395
+ f"{TOOL_CALL_CLOSE}"
396
+ )
397
+
398
+
399
+ def format_smoltalk_tool_calls(raw_tool_calls: Any) -> str:
400
+ if not raw_tool_calls:
401
+ return ""
402
+ if not isinstance(raw_tool_calls, list):
403
+ raise ValueError("tool_calls must be a list")
404
+ chunks: list[str] = []
405
+ for raw_call in raw_tool_calls:
406
+ if not isinstance(raw_call, dict):
407
+ raise ValueError("Each tool_call must be an object")
408
+ payload = (
409
+ raw_call.get("function")
410
+ if isinstance(raw_call.get("function"), dict)
411
+ else raw_call
412
+ )
413
+ if not isinstance(payload, dict):
414
+ raise ValueError("tool_call is missing a function object")
415
+ name = payload.get("name")
416
+ if not isinstance(name, str) or not name.strip():
417
+ raise ValueError("tool_call is missing a function name")
418
+ arguments = parse_arguments_payload(payload.get("arguments"))
419
+ chunks.append(format_smoltalk_tool_call(name.strip(), arguments))
420
+ return "\n".join(chunks)
421
+
422
+
423
+ def assistant_smoltalk_content(message: dict[str, Any], *, tool_format: ToolFormat = "json") -> str:
424
+ content = assistant_message_content(
425
+ {**message, "tool_calls": None}
426
+ )
427
+ if TOOL_CALL_OPEN in content:
428
+ return content
429
+ if tool_format == "xml":
430
+ tool_xml = format_tool_calls_xml(message.get("tool_calls")).rstrip("\n")
431
+ else:
432
+ tool_xml = format_smoltalk_tool_calls(message.get("tool_calls"))
433
+ if not tool_xml:
434
+ return content
435
+ if content.strip():
436
+ return f"{content.rstrip()}\n{tool_xml}"
437
+ return tool_xml
438
+
439
+
440
+ def render_system_prompt(kwargs: ChatTemplateKwargs) -> str:
441
+ """Render the system turn verbatim; empty string means no system turn."""
442
+
443
+ custom = strip_leaked_chatml(strip_template_markers(kwargs.custom_instructions))
444
+ tool_blocks: list[str] = []
445
+ if TOOLS_OPEN not in custom:
446
+ if kwargs.tool_format == "xml":
447
+ xml_block = render_cascade_tools_block(kwargs.xml_tools)
448
+ else:
449
+ xml_block = render_xml_tools_block(kwargs.xml_tools)
450
+ if xml_block:
451
+ tool_blocks.append(xml_block)
452
+ python_block = render_python_tools_block(kwargs.python_tools)
453
+ if python_block:
454
+ tool_blocks.append(python_block)
455
+ sections = [custom] if custom else []
456
+ sections.extend(tool_blocks)
457
+ return "\n\n".join(sections).strip()
458
+
459
+
460
+ def merge_kwargs_with_system_message(
461
+ messages: list[dict[str, Any]],
462
+ kwargs: ChatTemplateKwargs,
463
+ ) -> tuple[list[dict[str, Any]], ChatTemplateKwargs]:
464
+ if not messages:
465
+ return messages, kwargs
466
+ first = messages[0]
467
+ if first.get("role") != "system":
468
+ return messages, kwargs
469
+ system_text = message_text(first.get("content"))
470
+ if system_text.strip():
471
+ merged = (
472
+ system_text
473
+ if not kwargs.custom_instructions.strip()
474
+ else f"{kwargs.custom_instructions.rstrip()}\n\n{system_text.strip()}"
475
+ )
476
+ kwargs = replace(kwargs, custom_instructions=merged)
477
+ return messages[1:], kwargs
478
+
479
+
480
+ def kwargs_from_inference_request(
481
+ *,
482
+ enable_thinking: bool,
483
+ custom_instructions: str = "",
484
+ xml_tools: Any = None,
485
+ python_tools: Any = None,
486
+ tools: Any = None,
487
+ tool_format: ToolFormatChoice = "json",
488
+ ) -> ChatTemplateKwargs:
489
+ """``tool_format="auto"`` is the Hermes JSON layout every served model was trained on.
490
+
491
+ The Cascade XML layout is only used when a request asks for ``xml`` explicitly.
492
+ """
493
+
494
+ xml = coerce_tool_strings(xml_tools)
495
+ if not xml:
496
+ xml = openai_tools_as_xml_strings(tools)
497
+ if tool_format == "auto":
498
+ tool_format = "json"
499
+ return ChatTemplateKwargs(
500
+ custom_instructions=custom_instructions,
501
+ enable_thinking=enable_thinking,
502
+ xml_tools=xml,
503
+ python_tools=coerce_tool_strings(python_tools),
504
+ tool_format=tool_format,
505
+ )
506
+
507
+
508
+ def _normalize_role(raw_role: Any, index: int) -> str:
509
+ if not isinstance(raw_role, str):
510
+ raise ValueError(f"Unsupported chat role at index {index}: {raw_role!r}")
511
+ role = raw_role.strip().lower()
512
+ if role == "human":
513
+ return "user"
514
+ if role == "gpt":
515
+ return "assistant"
516
+ if role == "function":
517
+ return "tool"
518
+ if role not in {"system", "user", "assistant", "tool"}:
519
+ raise ValueError(f"Unsupported chat role at index {index}: {raw_role!r}")
520
+ return role
521
+
522
+
523
+ def materialize_smoltalk_messages(
524
+ raw_messages: list[dict[str, Any]],
525
+ kwargs: ChatTemplateKwargs,
526
+ ) -> list[dict[str, str]]:
527
+ if not raw_messages:
528
+ raise ValueError("Chat history cannot be empty")
529
+ remaining, resolved = merge_kwargs_with_system_message(raw_messages, kwargs)
530
+ for index, raw_message in enumerate(remaining):
531
+ if not isinstance(raw_message, dict):
532
+ raise ValueError(f"Unsupported chat message at index {index}")
533
+ if _normalize_role(raw_message.get("role"), index) != "system":
534
+ continue
535
+ extra = strip_leaked_chatml(message_text(raw_message.get("content")))
536
+ if extra:
537
+ resolved = replace(
538
+ resolved,
539
+ custom_instructions=(
540
+ f"{resolved.custom_instructions.rstrip()}\n\n{extra}".strip()
541
+ ),
542
+ )
543
+ mode = resolve_reasoning_mode(
544
+ resolved.enable_thinking,
545
+ resolved.custom_instructions,
546
+ )
547
+ masked_prefix = THINK_CONTROL_PREFIX if mode == "/think" else NO_THINK_PREFIX
548
+ prepared: list[dict[str, str]] = []
549
+ system_prompt = render_system_prompt(resolved)
550
+ if system_prompt:
551
+ prepared.append({"role": "system", "content": system_prompt})
552
+ pending_tool_results: list[str] = []
553
+ for index, raw_message in enumerate(remaining):
554
+ role = _normalize_role(raw_message.get("role"), index)
555
+ if role == "system":
556
+ continue
557
+ if role == "assistant":
558
+ content = assistant_smoltalk_content(raw_message, tool_format=resolved.tool_format)
559
+ else:
560
+ content = message_text(raw_message.get("content"))
561
+ if role == "tool":
562
+ content = wrap_smoltalk_tool_result(content)
563
+ if not content:
564
+ raise ValueError(f"Chat content at index {index} must be non-empty")
565
+ pending_tool_results.append(content)
566
+ continue
567
+ if pending_tool_results:
568
+ prepared.append(
569
+ {"role": "user", "content": "\n".join(pending_tool_results)}
570
+ )
571
+ pending_tool_results = []
572
+ if not content.strip():
573
+ raise ValueError(f"Chat content at index {index} must be non-empty")
574
+ prepared_message = {"role": role, "content": content}
575
+ if role == "assistant":
576
+ prepared_message["masked_prefix"] = masked_prefix
577
+ prepared.append(prepared_message)
578
+ if pending_tool_results:
579
+ prepared.append({"role": "user", "content": "\n".join(pending_tool_results)})
580
+ if not any(message["role"] != "system" for message in prepared):
581
+ raise ValueError("Chat history cannot be empty")
582
+ return prepared
583
+
584
+
585
+ def format_think_block(reasoning: str, content: str) -> str:
586
+ """SmolTalk2 layout: `<think>\\n…\\n</think>\\n\\nanswer`."""
587
+
588
+ body = reasoning.strip()
589
+ if content:
590
+ return f"{THINK_OPEN}\n{body}\n{THINK_CLOSE}\n\n{content}"
591
+ return f"{THINK_OPEN}\n{body}\n{THINK_CLOSE}\n\n"
592
+
593
+
594
+ def render_assistant_turn(
595
+ content: str,
596
+ *,
597
+ reasoning: str | None,
598
+ tool_calls: list[dict[str, Any]] | None,
599
+ ) -> dict[str, str]:
600
+ """Render one assistant turn with a per-turn thinking control prefix.
601
+
602
+ A turn with reasoning gets `<|think|>` and a `<think>` block; a turn
603
+ without reasoning gets `<|no_think|>`. Tool calls become SmolTalk JSON
604
+ `<tool_call>` blocks unless the content already inlines them.
605
+ """
606
+
607
+ text = strip_empty_think_blocks(content.strip())
608
+ if tool_calls and TOOL_CALL_OPEN not in text:
609
+ calls = "\n".join(
610
+ format_smoltalk_tool_call(call["name"], call["arguments"]) for call in tool_calls
611
+ )
612
+ text = f"{text}\n{calls}" if text else calls
613
+ if reasoning and reasoning.strip():
614
+ return {
615
+ "role": "assistant",
616
+ "content": format_think_block(reasoning, text),
617
+ "masked_prefix": THINK_CONTROL_PREFIX,
618
+ }
619
+ return {"role": "assistant", "content": text, "masked_prefix": NO_THINK_PREFIX}
620
+
621
+
622
+ def materialize_canonical_conversation(
623
+ *,
624
+ system: str | None,
625
+ tools: Any,
626
+ messages: list[dict[str, Any]],
627
+ ) -> list[dict[str, Any]]:
628
+ """Render a stage-3 canonical conversation into ChatML-ready turns.
629
+
630
+ `messages` entries are `{"role", "content", "reasoning"?, "tool_calls"?,
631
+ "context_only"?}` with roles user / assistant / tool. The system prompt is
632
+ used verbatim; tools are appended only when the prompt lacks a `<tools>`
633
+ block. A `context_only` assistant turn keeps that flag, so the encoder
634
+ leaves it out of the loss.
635
+ """
636
+
637
+ kwargs = ChatTemplateKwargs(
638
+ custom_instructions=system or "",
639
+ xml_tools=openai_tools_as_xml_strings(tools) if tools else (),
640
+ )
641
+ prepared: list[dict[str, str]] = []
642
+ system_prompt = render_system_prompt(kwargs)
643
+ if system_prompt:
644
+ prepared.append({"role": "system", "content": system_prompt})
645
+ pending_tool_results: list[str] = []
646
+ for index, message in enumerate(messages):
647
+ role = message["role"]
648
+ if role == "tool":
649
+ wrapped = wrap_smoltalk_tool_result(message_text(message.get("content")))
650
+ if not wrapped:
651
+ raise ValueError(f"Tool result at index {index} is empty")
652
+ pending_tool_results.append(wrapped)
653
+ continue
654
+ if pending_tool_results:
655
+ prepared.append({"role": "user", "content": "\n".join(pending_tool_results)})
656
+ pending_tool_results = []
657
+ if role == "user":
658
+ content = message_text(message.get("content"))
659
+ if not content.strip():
660
+ raise ValueError(f"User turn at index {index} is empty")
661
+ prepared.append({"role": "user", "content": content})
662
+ continue
663
+ if role == "assistant":
664
+ rendered = render_assistant_turn(
665
+ message_text(message.get("content")),
666
+ reasoning=message.get("reasoning"),
667
+ tool_calls=message.get("tool_calls"),
668
+ )
669
+ if not rendered["content"].strip():
670
+ raise ValueError(f"Assistant turn at index {index} is empty")
671
+ if message.get("context_only"):
672
+ rendered["context_only"] = True
673
+ prepared.append(rendered)
674
+ continue
675
+ raise ValueError(f"Unsupported role at index {index}: {role!r}")
676
+ if pending_tool_results:
677
+ raise ValueError("Conversation ends with an unanswered tool result")
678
+ if not prepared or prepared[-1]["role"] != "assistant":
679
+ raise ValueError("Conversation must end with an assistant turn")
680
+ return prepared
tiny_gdn/token_file.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Secrets kept in the project's ``token.env``, one ``name=value`` per line.
2
+
3
+ The file is read again whenever its size or modification time changes, so a
4
+ key pasted into it reaches a running server on the next lookup.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import threading
10
+ from pathlib import Path
11
+
12
+ from tiny_gdn.paths import project_root
13
+
14
+ _lock = threading.Lock()
15
+ _cache: dict[Path, tuple[tuple[int, int], dict[str, str]]] = {}
16
+
17
+
18
+ def token_file() -> Path:
19
+ return project_root() / "token.env"
20
+
21
+
22
+ def parse_token_file(text: str) -> dict[str, str]:
23
+ values: dict[str, str] = {}
24
+ for line in text.splitlines():
25
+ stripped = line.strip()
26
+ if not stripped or stripped.startswith("#"):
27
+ continue
28
+ name, separator, value = stripped.partition("=")
29
+ if not separator or not name.strip():
30
+ continue
31
+ value = value.strip()
32
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
33
+ value = value[1:-1].strip()
34
+ values[name.strip()] = value
35
+ return values
36
+
37
+
38
+ def token_value(name: str) -> str:
39
+ """The value named ``name`` in token.env, or "" when the file or the line is missing."""
40
+
41
+ path = token_file()
42
+ try:
43
+ stat = path.stat()
44
+ except OSError:
45
+ return ""
46
+ stamp = (stat.st_mtime_ns, stat.st_size)
47
+ with _lock:
48
+ cached = _cache.get(path)
49
+ if cached is None or cached[0] != stamp:
50
+ try:
51
+ values = parse_token_file(path.read_text(encoding="utf-8"))
52
+ except OSError:
53
+ return ""
54
+ cached = (stamp, values)
55
+ _cache[path] = cached
56
+ return cached[1].get(name, "")
tiny_gdn/tools.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Nemotron Cascade-2 tool protocol (XML in ChatML content).
2
+
3
+ Tercet-R is trained on `nvidia/Nemotron-Cascade-2-SFT-Data`, which inlines
4
+ available tools, calls, and results as `<tools>` / `<tool_call>` /
5
+ `<tool_response>` in message text. That is not OpenAI `tool_calls` JSON and
6
+ not this tokenizer's unused `<|tool_call|>` / `<|tool_response|>` specials.
7
+
8
+ This module matches NVIDIA's Cascade-2 chat template:
9
+ https://huggingface.co/nvidia/Nemotron-Cascade-2-30B-A3B/blob/main/chat_template.jinja
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import ast
15
+ import json
16
+ import re
17
+ import sys
18
+ from dataclasses import dataclass
19
+ from typing import Any
20
+
21
+
22
+ TOOL_CALL_OPEN = "<tool_call>"
23
+ TOOL_CALL_CLOSE = "</tool_call>"
24
+ TOOL_RESPONSE_OPEN = "<tool_response>"
25
+ TOOL_RESPONSE_CLOSE = "</tool_response>"
26
+ TOOLS_OPEN = "<tools>"
27
+ TOOLS_CLOSE = "</tools>"
28
+ THINK_OPEN = "<think>"
29
+ THINK_CLOSE = "</think>"
30
+
31
+ CHATML_START_RE = re.compile(r"^<\|im_start\|>[A-Za-z]+\n")
32
+ CHATML_END_RE = re.compile(r"\n?<\|im_end\|>\s*$")
33
+ TOOL_CALL_BLOCK_RE = re.compile(
34
+ rf"{re.escape(TOOL_CALL_OPEN)}(.*?){re.escape(TOOL_CALL_CLOSE)}",
35
+ re.DOTALL,
36
+ )
37
+ FUNCTION_BLOCK_RE = re.compile(
38
+ r"<function=([^>\s]+)>(.*?)</function>",
39
+ re.DOTALL,
40
+ )
41
+ PARAMETER_BLOCK_RE = re.compile(
42
+ r"<parameter=([^>\s]+)>\n?(.*?)\n?</parameter>",
43
+ re.DOTALL,
44
+ )
45
+ FUNCTION_NAME_RE = re.compile(r"<function=([^>\s]+)")
46
+
47
+ INFERENCE_ROLE_MAP = {
48
+ "system": "system",
49
+ "user": "user",
50
+ "human": "user",
51
+ "assistant": "assistant",
52
+ "gpt": "assistant",
53
+ "tool": "tool",
54
+ "function": "tool",
55
+ }
56
+
57
+ TOOLS_PREAMBLE = "# Tools\n\nYou have access to the following functions:\n\n"
58
+ TOOL_CALL_INSTRUCTIONS = (
59
+ "\n\nIf you choose to call a function ONLY reply in the following format "
60
+ "with NO suffix:\n\n"
61
+ "<tool_call>\n"
62
+ "<function=example_function_name>\n"
63
+ "<parameter=example_parameter_1>\n"
64
+ "value_1\n"
65
+ "</parameter>\n"
66
+ "<parameter=example_parameter_2>\n"
67
+ "This is the value for the second parameter\n"
68
+ "that can span\n"
69
+ "multiple lines\n"
70
+ "</parameter>\n"
71
+ "</function>\n"
72
+ "</tool_call>\n\n"
73
+ "<IMPORTANT>\n"
74
+ "Reminder:\n"
75
+ "- Function calls MUST follow the specified format: an inner "
76
+ "<function=...></function> block must be nested within "
77
+ "<tool_call></tool_call> XML tags\n"
78
+ "- Required parameters MUST be specified\n"
79
+ "- You may provide optional reasoning for your function call in natural "
80
+ "language BEFORE the function call, but NOT after\n"
81
+ "- If there is no function call available, answer the question like "
82
+ "normal with your current knowledge and do not tell the user about "
83
+ "function calls\n"
84
+ "</IMPORTANT>"
85
+ )
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class ParsedToolCall:
90
+ name: str
91
+ arguments: dict[str, Any]
92
+ raw: str
93
+
94
+
95
+ def message_text(raw_content: Any) -> str:
96
+ if raw_content is None:
97
+ return ""
98
+ if isinstance(raw_content, str):
99
+ return raw_content
100
+ if isinstance(raw_content, list):
101
+ parts: list[str] = []
102
+ for item in raw_content:
103
+ if isinstance(item, str):
104
+ parts.append(item)
105
+ continue
106
+ if not isinstance(item, dict):
107
+ continue
108
+ part_type = item.get("type")
109
+ if part_type in {None, "text", "input_text", "output_text"}:
110
+ text = item.get("text")
111
+ if isinstance(text, str):
112
+ parts.append(text)
113
+ return "".join(parts)
114
+ return str(raw_content)
115
+
116
+
117
+ def strip_leaked_chatml(content: str) -> str:
118
+ text = content.strip()
119
+ while True:
120
+ match = CHATML_START_RE.match(text)
121
+ if match is None:
122
+ break
123
+ text = text[match.end() :]
124
+ text = CHATML_END_RE.sub("", text)
125
+ return text.strip()
126
+
127
+
128
+ def has_tools_block(content: str) -> bool:
129
+ return TOOLS_OPEN in content
130
+
131
+
132
+ def wrap_tool_response(content: str) -> str:
133
+ text = strip_leaked_chatml(content)
134
+ if TOOL_RESPONSE_OPEN in text:
135
+ return text
136
+ return f"{TOOL_RESPONSE_OPEN}\n\n\n{text}\n{TOOL_RESPONSE_CLOSE}"
137
+
138
+
139
+ def _xml_value(value: Any) -> str:
140
+ if isinstance(value, dict) or (
141
+ isinstance(value, (list, tuple)) and not isinstance(value, (str, bytes))
142
+ ):
143
+ return json.dumps(value, ensure_ascii=False)
144
+ if value is True or value is False or value is None:
145
+ return str(value)
146
+ return str(value)
147
+
148
+
149
+ def _render_extra_keys(payload: dict[str, Any], handled: set[str]) -> str:
150
+ chunks: list[str] = []
151
+ for key, value in payload.items():
152
+ if key in handled:
153
+ continue
154
+ chunks.append(f"\n<{key}>{_xml_value(value)}</{key}>")
155
+ return "".join(chunks)
156
+
157
+
158
+ def _unwrap_tool(raw_tool: Any) -> dict[str, Any]:
159
+ if not isinstance(raw_tool, dict):
160
+ raise ValueError("Each tool must be an object")
161
+ if isinstance(raw_tool.get("function"), dict):
162
+ tool = dict(raw_tool["function"])
163
+ else:
164
+ tool = dict(raw_tool)
165
+ name = tool.get("name")
166
+ if not isinstance(name, str) or not name.strip():
167
+ raise ValueError("Tool is missing a function name")
168
+ tool["name"] = name.strip()
169
+ return tool
170
+
171
+
172
+ def coerce_tools(raw_tools: Any) -> list[dict[str, Any]]:
173
+ if raw_tools is None:
174
+ return []
175
+ if isinstance(raw_tools, str):
176
+ text = raw_tools.strip()
177
+ if not text:
178
+ return []
179
+ raw_tools = loads_json(text)
180
+ if isinstance(raw_tools, dict):
181
+ raw_tools = [raw_tools]
182
+ if not isinstance(raw_tools, list):
183
+ raise ValueError("tools must be a list of function specs")
184
+ return [_unwrap_tool(item) for item in raw_tools]
185
+
186
+
187
+ def render_function_schema(tool: dict[str, Any]) -> str:
188
+ chunks = [f"\n<function>\n<name>{tool['name']}</name>"]
189
+ description = tool.get("description")
190
+ if isinstance(description, str) and description.strip():
191
+ chunks.append(f"\n<description>{description.strip()}</description>")
192
+ chunks.append("\n<parameters>")
193
+ parameters = tool.get("parameters")
194
+ properties: dict[str, Any] = {}
195
+ if isinstance(parameters, dict):
196
+ raw_properties = parameters.get("properties")
197
+ if isinstance(raw_properties, dict):
198
+ properties = raw_properties
199
+ for param_name, raw_fields in properties.items():
200
+ fields = raw_fields if isinstance(raw_fields, dict) else {}
201
+ chunks.append("\n<parameter>")
202
+ chunks.append(f"\n<name>{param_name}</name>")
203
+ if "type" in fields:
204
+ chunks.append(f"\n<type>{_xml_value(fields['type'])}</type>")
205
+ if isinstance(fields.get("description"), str) and fields["description"].strip():
206
+ chunks.append(
207
+ f"\n<description>{fields['description'].strip()}</description>"
208
+ )
209
+ if "enum" in fields:
210
+ chunks.append(f"\n<enum>{_xml_value(fields['enum'])}</enum>")
211
+ chunks.append(
212
+ _render_extra_keys(
213
+ fields,
214
+ {"name", "type", "description", "enum"},
215
+ )
216
+ )
217
+ chunks.append("\n</parameter>")
218
+ chunks.append(
219
+ _render_extra_keys(parameters, {"type", "properties", "required"})
220
+ )
221
+ if "required" in parameters:
222
+ chunks.append(f"\n<required>{_xml_value(parameters['required'])}</required>")
223
+ chunks.append("\n</parameters>")
224
+ chunks.append(
225
+ _render_extra_keys(
226
+ tool,
227
+ {"type", "name", "description", "parameters"},
228
+ )
229
+ )
230
+ chunks.append("\n</function>")
231
+ return "".join(chunks)
232
+
233
+
234
+ def render_available_tools(raw_tools: Any) -> str:
235
+ tools = coerce_tools(raw_tools)
236
+ if not tools:
237
+ return ""
238
+ body = "".join(render_function_schema(tool) for tool in tools)
239
+ return (
240
+ f"{TOOLS_PREAMBLE}{TOOLS_OPEN}{body}\n{TOOLS_CLOSE}"
241
+ f"{TOOL_CALL_INSTRUCTIONS}"
242
+ )
243
+
244
+
245
+ # Cascade's OpenHands conversations used XML schemas and `<function=…>` calls.
246
+ # Those conversations are not in the served models' training data; `auto` is JSON.
247
+ XML_LAYOUT_TOOL_NAMES = frozenset({"execute_bash", "str_replace_editor"})
248
+
249
+
250
+ def prefers_xml_tool_calls(raw_tools: Any) -> bool:
251
+ """Whether a tool list holds names Cascade rendered only in the XML layout.
252
+
253
+ Served models were not trained on that data, so inference ``auto`` does not
254
+ use this. It remains for callers that still want to detect the old tool set.
255
+ """
256
+
257
+ try:
258
+ tools = coerce_tools(raw_tools)
259
+ except ValueError:
260
+ return False
261
+ return any(tool["name"].lower().replace("-", "_") in XML_LAYOUT_TOOL_NAMES for tool in tools)
262
+
263
+
264
+ def inject_available_tools(system_content: str, raw_tools: Any) -> str:
265
+ block = render_available_tools(raw_tools)
266
+ if not block:
267
+ return system_content
268
+ if has_tools_block(system_content):
269
+ return system_content
270
+ if not system_content.strip():
271
+ return block
272
+ return f"{system_content.rstrip()}\n\n{block}"
273
+
274
+
275
+ def parse_json_int(text: str) -> int | str:
276
+ """Keep oversized JSON integers as strings.
277
+
278
+ Python 3.12 refuses to convert integers longer than
279
+ ``sys.get_int_max_str_digits()`` (default 4300). Tool-call payloads
280
+ sometimes embed hashes or blobs as bare JSON numbers; those must not
281
+ abort packing.
282
+ """
283
+
284
+ digits = text.lstrip("+-")
285
+ limit = sys.get_int_max_str_digits()
286
+ if limit and len(digits) > limit:
287
+ return text
288
+ return int(text)
289
+
290
+
291
+ def loads_json(text: str) -> Any:
292
+ return json.loads(text, parse_int=parse_json_int)
293
+
294
+
295
+ # Models sometimes close a JSON string with `".}` instead of `"}`.
296
+ _TRAILING_STRING_PERIOD_RE = re.compile(r'"\s*\.(?=\s*[}\],])')
297
+ _TRAILING_COMMA_RE = re.compile(r",\s*(?=[}\]])")
298
+ _JSON_NAME_RE = re.compile(r'"name"\s*:\s*"([^"]+)"')
299
+ _JSON_QUERY_RE = re.compile(r'"query"\s*:\s*"([^"]*)"')
300
+
301
+
302
+ def repair_jsonish(text: str) -> str:
303
+ repaired = _TRAILING_STRING_PERIOD_RE.sub('"', text.strip())
304
+ return _TRAILING_COMMA_RE.sub("", repaired)
305
+
306
+
307
+ def loads_jsonish(text: str) -> Any:
308
+ """JSON with common model slips repaired; Python literals (single quotes, True) also parse."""
309
+
310
+ stripped = text.strip()
311
+ if not stripped:
312
+ raise json.JSONDecodeError("Empty JSON", text, 0)
313
+ last_error: Exception | None = None
314
+ for candidate in dict.fromkeys((stripped, repair_jsonish(stripped))):
315
+ try:
316
+ return loads_json(candidate)
317
+ except (json.JSONDecodeError, ValueError, RecursionError) as error:
318
+ last_error = error
319
+ try:
320
+ return json_ready(ast.literal_eval(stripped))
321
+ except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
322
+ pass
323
+ try:
324
+ return loads_json(stripped.replace("'", '"'))
325
+ except (json.JSONDecodeError, ValueError, RecursionError):
326
+ if last_error is not None:
327
+ raise last_error from None
328
+ raise
329
+
330
+
331
+ def extract_json_tool_fields(text: str) -> tuple[str, dict[str, Any]] | None:
332
+ name_match = _JSON_NAME_RE.search(text)
333
+ if name_match is None:
334
+ return None
335
+ arguments: dict[str, Any] = {}
336
+ query_match = _JSON_QUERY_RE.search(text)
337
+ if query_match is not None:
338
+ arguments["query"] = query_match.group(1)
339
+ return name_match.group(1).strip(), arguments
340
+
341
+
342
+ def _json_ready_int(value: int) -> int | str:
343
+ try:
344
+ json.dumps(value)
345
+ except ValueError:
346
+ previous = sys.get_int_max_str_digits()
347
+ sys.set_int_max_str_digits(0)
348
+ try:
349
+ return str(value)
350
+ finally:
351
+ sys.set_int_max_str_digits(previous)
352
+ return value
353
+
354
+
355
+ def json_ready(value: Any) -> Any:
356
+ """Coerce Python literals into JSON-serialisable values.
357
+
358
+ Some SFT sources store tool arguments as Python literals. `ast.literal_eval`
359
+ turns `{1, 2}` into a `set` and `...` into `Ellipsis`, which later
360
+ `json.dumps` calls reject. Oversized ints are stored as decimal strings.
361
+ """
362
+
363
+ if value is None or isinstance(value, (bool, float, str)):
364
+ return value
365
+ if isinstance(value, int):
366
+ return _json_ready_int(value)
367
+ if value is Ellipsis:
368
+ return None
369
+ if isinstance(value, dict):
370
+ return {str(key): json_ready(item) for key, item in value.items()}
371
+ if isinstance(value, (set, frozenset)):
372
+ items = [json_ready(item) for item in value]
373
+ try:
374
+ return sorted(
375
+ items,
376
+ key=lambda item: json.dumps(item, sort_keys=True, default=str),
377
+ )
378
+ except TypeError:
379
+ return items
380
+ if isinstance(value, tuple):
381
+ return [json_ready(item) for item in value]
382
+ if isinstance(value, list):
383
+ return [json_ready(item) for item in value]
384
+ if isinstance(value, bytes):
385
+ try:
386
+ return value.decode("utf-8")
387
+ except UnicodeDecodeError:
388
+ return list(value)
389
+ try:
390
+ json.dumps(value)
391
+ return value
392
+ except (TypeError, ValueError):
393
+ return str(value)
394
+
395
+
396
+ def parse_argument_value(raw: str) -> Any:
397
+ text = raw.strip()
398
+ if not text:
399
+ return ""
400
+ try:
401
+ return loads_json(text)
402
+ except (json.JSONDecodeError, ValueError, RecursionError):
403
+ return text
404
+
405
+
406
+ def parse_arguments_payload(raw: Any) -> dict[str, Any]:
407
+ if raw is None:
408
+ return {}
409
+ ready = json_ready(raw)
410
+ if isinstance(ready, dict):
411
+ return ready
412
+ if isinstance(ready, str):
413
+ text = ready.strip()
414
+ if not text:
415
+ return {}
416
+ try:
417
+ loaded = loads_json(text)
418
+ except (json.JSONDecodeError, ValueError, RecursionError):
419
+ return {"value": ready}
420
+ loaded = json_ready(loaded)
421
+ if isinstance(loaded, dict):
422
+ return loaded
423
+ return {"value": loaded}
424
+ return {"value": ready}
425
+
426
+
427
+ def format_tool_call_xml(name: str, arguments: dict[str, Any]) -> str:
428
+ chunks = [f"{TOOL_CALL_OPEN}\n<function={name}>\n"]
429
+ for key, value in arguments.items():
430
+ chunks.append(f"<parameter={key}>\n{_xml_value(value)}\n</parameter>\n")
431
+ chunks.append(f"</function>\n{TOOL_CALL_CLOSE}\n")
432
+ return "".join(chunks)
433
+
434
+
435
+ def format_tool_calls_xml(raw_tool_calls: Any) -> str:
436
+ if not raw_tool_calls:
437
+ return ""
438
+ if not isinstance(raw_tool_calls, list):
439
+ raise ValueError("tool_calls must be a list")
440
+ chunks: list[str] = []
441
+ for raw_call in raw_tool_calls:
442
+ if not isinstance(raw_call, dict):
443
+ raise ValueError("Each tool_call must be an object")
444
+ payload = raw_call.get("function") if isinstance(raw_call.get("function"), dict) else raw_call
445
+ if not isinstance(payload, dict):
446
+ raise ValueError("tool_call is missing a function object")
447
+ name = payload.get("name")
448
+ if not isinstance(name, str) or not name.strip():
449
+ raise ValueError("tool_call is missing a function name")
450
+ arguments = parse_arguments_payload(payload.get("arguments"))
451
+ chunks.append(format_tool_call_xml(name.strip(), arguments))
452
+ return "".join(chunks)
453
+
454
+
455
+ def _json_tool_call(payload: Any, raw: str) -> ParsedToolCall | None:
456
+ if not isinstance(payload, dict):
457
+ return None
458
+ nested = payload.get("function")
459
+ source = nested if isinstance(nested, dict) else payload
460
+ name = source.get("name")
461
+ if not isinstance(name, str) or not name.strip():
462
+ name = payload.get("name")
463
+ if not isinstance(name, str) or not name.strip():
464
+ return None
465
+ arguments = parse_arguments_payload(
466
+ source.get("arguments", source.get("parameters", payload.get("arguments")))
467
+ )
468
+ return ParsedToolCall(name=name.strip(), arguments=arguments, raw=raw)
469
+
470
+
471
+ def parse_json_tool_calls(
472
+ inner: str, raw: str = "", *, strict: bool = False
473
+ ) -> list[ParsedToolCall] | None:
474
+ """Calls in the JSON body of one `<tool_call>` block, or None when it holds none.
475
+
476
+ The body is one call object or a list of them (``[]`` is an explicit "no call").
477
+ Unless ``strict``, a body that does not parse still yields the call name and
478
+ query it mentions.
479
+ """
480
+
481
+ text = inner.strip()
482
+ if not text:
483
+ return None
484
+ try:
485
+ payload = loads_jsonish(text)
486
+ except (json.JSONDecodeError, ValueError, RecursionError):
487
+ payload = None
488
+ if payload == []:
489
+ return []
490
+ items = payload if isinstance(payload, list) else [payload]
491
+ calls = [call for item in items if (call := _json_tool_call(item, raw)) is not None]
492
+ if strict:
493
+ return calls if calls and len(calls) == len(items) else None
494
+ if calls:
495
+ return calls
496
+ extracted = extract_json_tool_fields(repair_jsonish(text))
497
+ if extracted is None:
498
+ return None
499
+ name, arguments = extracted
500
+ return [ParsedToolCall(name=name, arguments=arguments, raw=raw)]
501
+
502
+
503
+ def parse_tool_call_blocks(
504
+ text: str, *, strict: bool = False
505
+ ) -> list[list[ParsedToolCall] | None]:
506
+ """The calls of each `<tool_call>` block in ``text``; None for a block that does not parse."""
507
+
508
+ blocks: list[list[ParsedToolCall] | None] = []
509
+ for block in TOOL_CALL_BLOCK_RE.finditer(text):
510
+ inner = block.group(1)
511
+ raw = block.group(0).strip()
512
+ calls: list[ParsedToolCall] = []
513
+ for function in FUNCTION_BLOCK_RE.finditer(inner):
514
+ arguments: dict[str, Any] = {}
515
+ for parameter in PARAMETER_BLOCK_RE.finditer(function.group(2)):
516
+ arguments[parameter.group(1).strip()] = parse_argument_value(
517
+ parameter.group(2)
518
+ )
519
+ calls.append(
520
+ ParsedToolCall(
521
+ name=function.group(1).strip(),
522
+ arguments=json_ready(arguments),
523
+ raw=raw,
524
+ )
525
+ )
526
+ blocks.append(calls if calls else parse_json_tool_calls(inner, raw, strict=strict))
527
+ return blocks
528
+
529
+
530
+ def parse_tool_calls(text: str) -> list[ParsedToolCall]:
531
+ return [call for calls in parse_tool_call_blocks(text) if calls for call in calls]
532
+
533
+
534
+ def openai_tool_calls_from_text(text: str) -> list[dict[str, Any]]:
535
+ encoded: list[dict[str, Any]] = []
536
+ for index, call in enumerate(parse_tool_calls(text)):
537
+ encoded.append(
538
+ {
539
+ "id": f"call_{index}_{call.name}",
540
+ "type": "function",
541
+ "function": {
542
+ "name": call.name,
543
+ "arguments": json.dumps(call.arguments, ensure_ascii=False),
544
+ },
545
+ }
546
+ )
547
+ return encoded
548
+
549
+
550
+ def assistant_message_content(message: dict[str, Any]) -> str:
551
+ reasoning = message.get("reasoning_content")
552
+ content = message_text(message.get("content"))
553
+ if isinstance(reasoning, str) and reasoning.strip():
554
+ content = f"{THINK_OPEN}\n{reasoning.strip()}\n{THINK_CLOSE}\n{content}"
555
+ tool_xml = format_tool_calls_xml(message.get("tool_calls"))
556
+ if tool_xml:
557
+ if content.strip():
558
+ return f"{content.rstrip()}\n{tool_xml}"
559
+ return tool_xml
560
+ return content
561
+
562
+
563
+ def _flush_tool_group(
564
+ group: list[str],
565
+ messages: list[dict[str, str]],
566
+ ) -> None:
567
+ if not group:
568
+ return
569
+ messages.append({"role": "user", "content": "\n".join(group)})
570
+ group.clear()
571
+
572
+
573
+ def prepare_inference_messages(
574
+ raw_messages: list[dict[str, Any]],
575
+ *,
576
+ tools: Any | None = None,
577
+ ) -> list[dict[str, str]]:
578
+ if not raw_messages:
579
+ raise ValueError("Chat history cannot be empty")
580
+
581
+ prepared: list[dict[str, str]] = []
582
+ pending_tool_results: list[str] = []
583
+ for index, raw_message in enumerate(raw_messages):
584
+ if not isinstance(raw_message, dict):
585
+ raise ValueError(f"Unsupported chat message at index {index}")
586
+ raw_role = raw_message.get("role")
587
+ if not isinstance(raw_role, str):
588
+ raise ValueError(f"Unsupported chat role at index {index}: {raw_role!r}")
589
+ role = INFERENCE_ROLE_MAP.get(raw_role.strip().lower())
590
+ if role is None:
591
+ raise ValueError(f"Unsupported chat role at index {index}: {raw_role!r}")
592
+ if role == "assistant":
593
+ content = assistant_message_content(raw_message)
594
+ else:
595
+ content = message_text(raw_message.get("content"))
596
+ if role == "tool":
597
+ content = wrap_tool_response(content)
598
+ if not content.strip():
599
+ raise ValueError(f"Chat content at index {index} must be non-empty")
600
+ pending_tool_results.append(content)
601
+ continue
602
+ _flush_tool_group(pending_tool_results, prepared)
603
+ if not content.strip():
604
+ if role == "system":
605
+ continue
606
+ raise ValueError(f"Chat content at index {index} must be non-empty")
607
+ if role == "system":
608
+ content = strip_leaked_chatml(content)
609
+ prepared.append({"role": role, "content": content})
610
+ _flush_tool_group(pending_tool_results, prepared)
611
+
612
+ tools_block = render_available_tools(tools)
613
+ if tools_block:
614
+ if prepared and prepared[0]["role"] == "system":
615
+ prepared[0] = {
616
+ "role": "system",
617
+ "content": inject_available_tools(prepared[0]["content"], tools),
618
+ }
619
+ else:
620
+ prepared.insert(0, {"role": "system", "content": tools_block})
621
+
622
+ if not prepared:
623
+ raise ValueError("Chat history cannot be empty")
624
+ return prepared
tiny_gdn/web_fetch.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute the `fetch-page` tool: read one web page and return its text as Markdown.
2
+
3
+ `fetch-page` sits next to `web-search` and `calculator` on the website and in
4
+ the tool-use distill, so a model sees the same observation in both. HTML is
5
+ reduced to its main content by trafilatura, PDFs to their text, and plain
6
+ text types pass through. Each observation holds at most `PAGE_CHARS`
7
+ characters; a longer page ends with a note naming the `offset` that reads on.
8
+
9
+ Only public addresses are fetched. Every hostname is resolved before the
10
+ request, every address it resolves to must be globally routable, and the
11
+ connection goes to the vetted address itself, so a second DNS answer cannot
12
+ point it inside the network. Redirects are followed by hand and vetted the
13
+ same way.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import ipaddress
19
+ import socket
20
+ import threading
21
+ import time
22
+ from collections import OrderedDict
23
+ from collections.abc import Mapping
24
+ from dataclasses import dataclass
25
+ from io import BytesIO
26
+ from typing import Any
27
+ from urllib.parse import urljoin, urlsplit, urlunsplit
28
+
29
+ import trafilatura
30
+ import urllib3
31
+ from bs4 import BeautifulSoup
32
+ from pypdf import PdfReader
33
+ from pypdf.errors import PdfReadError
34
+
35
+ FETCH_PAGE_TOOL_NAME = "fetch-page"
36
+
37
+ FETCH_PAGE_TOOL: dict[str, Any] = {
38
+ "type": "function",
39
+ "function": {
40
+ "name": FETCH_PAGE_TOOL_NAME,
41
+ "description": "Fetch a web page or PDF by URL and return its readable text as Markdown.",
42
+ "parameters": {
43
+ "type": "object",
44
+ "properties": {
45
+ "url": {
46
+ "type": "string",
47
+ "description": "The http or https URL to fetch.",
48
+ },
49
+ "offset": {
50
+ "type": "integer",
51
+ "description": "Character offset to start reading from, for pages longer than one result.",
52
+ },
53
+ },
54
+ "required": ["url"],
55
+ },
56
+ },
57
+ }
58
+
59
+ PAGE_CHARS = 12_000
60
+ MAX_URL_CHARS = 2_048
61
+ MAX_BODY_BYTES = 8 * 1024 * 1024
62
+ MAX_REDIRECTS = 5
63
+ MAX_PDF_PAGES = 200
64
+ # Longer extracted text is cut here before caching; offsets past it read nothing.
65
+ MAX_DOCUMENT_CHARS = 400_000
66
+ CONNECT_SECONDS = 10.0
67
+ READ_SECONDS = 15.0
68
+ DEADLINE_SECONDS = 30.0
69
+ CACHE_ENTRIES = 128
70
+ CACHE_SECONDS = 15 * 60
71
+ USER_AGENT = (
72
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
73
+ "Chrome/131.0.0.0 Safari/537.36 KerzgrrAI-fetch/1.0 (+https://kerzgrr.ai)"
74
+ )
75
+ REQUEST_HEADERS = {
76
+ "User-Agent": USER_AGENT,
77
+ "Accept": "text/html,application/xhtml+xml,application/pdf;q=0.9,text/plain;q=0.8,*/*;q=0.5",
78
+ "Accept-Language": "en-US,en;q=0.9",
79
+ # urllib3 decodes these two without extra packages.
80
+ "Accept-Encoding": "gzip, deflate",
81
+ }
82
+ REDIRECT_STATUSES = {301, 302, 303, 307, 308}
83
+ TEXT_TYPES = {
84
+ "application/json",
85
+ "application/ld+json",
86
+ "application/xml",
87
+ "application/rss+xml",
88
+ "application/atom+xml",
89
+ "application/javascript",
90
+ "application/x-yaml",
91
+ "application/yaml",
92
+ "application/toml",
93
+ }
94
+ HTML_TYPES = {"text/html", "application/xhtml+xml"}
95
+
96
+
97
+ class FetchError(Exception):
98
+ """A page that could not be fetched; the message is shown to the model."""
99
+
100
+
101
+ @dataclass(frozen=True)
102
+ class FetchOutcome:
103
+ observation: str
104
+ ok: bool
105
+ url: str
106
+ status: int | None = None
107
+ content_type: str | None = None
108
+ # Length of the whole extracted page, not of this observation.
109
+ chars: int = 0
110
+
111
+ def public(self) -> dict[str, Any]:
112
+ return {"url": self.url, "status": self.status, "contentType": self.content_type, "chars": self.chars}
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class _Document:
117
+ url: str
118
+ title: str
119
+ text: str
120
+ status: int
121
+ content_type: str
122
+
123
+
124
+ def is_fetch_page_tool_name(name: str) -> bool:
125
+ return name.strip().lower().replace("_", "-") == FETCH_PAGE_TOOL_NAME
126
+
127
+
128
+ def url_from_arguments(arguments: Mapping[str, Any] | None) -> str:
129
+ if not arguments:
130
+ return ""
131
+ raw = arguments.get("url")
132
+ return raw.strip() if isinstance(raw, str) else ""
133
+
134
+
135
+ def offset_from_arguments(arguments: Mapping[str, Any] | None) -> int:
136
+ if not arguments:
137
+ return 0
138
+ raw = arguments.get("offset")
139
+ if isinstance(raw, bool):
140
+ return 0
141
+ if isinstance(raw, (int, float)):
142
+ return max(0, int(raw))
143
+ if isinstance(raw, str) and raw.strip().isdigit():
144
+ return int(raw.strip())
145
+ return 0
146
+
147
+
148
+ def fetch_page(url: str, *, offset: int = 0, page_chars: int = PAGE_CHARS) -> FetchOutcome:
149
+ """One `fetch-page` observation: the page's text from `offset`, or an error line."""
150
+
151
+ try:
152
+ target = normalize_url(url)
153
+ except FetchError as error:
154
+ return FetchOutcome(f"Error: {error}", False, url.strip())
155
+ try:
156
+ document = _cache.get(target)
157
+ if document is None:
158
+ document = _load(target)
159
+ _cache.put(target, document)
160
+ except FetchError as error:
161
+ return FetchOutcome(f"Error: {error}", False, target)
162
+ except Exception as error: # noqa: BLE001 — a page that breaks a parser is data, not a server fault
163
+ return FetchOutcome(f"Error: could not read {target}: {type(error).__name__}", False, target)
164
+ return FetchOutcome(
165
+ render_observation(document, offset=max(0, int(offset)), page_chars=page_chars),
166
+ True,
167
+ document.url,
168
+ document.status,
169
+ document.content_type,
170
+ len(document.text),
171
+ )
172
+
173
+
174
+ def render_observation(document: _Document, *, offset: int, page_chars: int) -> str:
175
+ total = len(document.text)
176
+ lines = [f"URL: {document.url}"]
177
+ if document.title:
178
+ lines.append(f"Title: {document.title}")
179
+ if total == 0:
180
+ return "\n".join(lines) + "\n\nThe page has no readable text."
181
+ if offset >= total:
182
+ return "\n".join(lines) + f"\n\nThe offset {offset:,} is past the end of the page, which has {total:,} characters."
183
+ end = min(total, offset + page_chars)
184
+ if end < total:
185
+ # Cut at a paragraph or line break near the limit rather than mid-word.
186
+ window = document.text[offset:end]
187
+ cut = max(window.rfind("\n\n"), window.rfind("\n"))
188
+ if cut > page_chars // 2:
189
+ end = offset + cut
190
+ body = document.text[offset:end].strip("\n")
191
+ lines.append("")
192
+ lines.append(body)
193
+ if end < total:
194
+ lines.append("")
195
+ lines.append(
196
+ f"[Showing characters {offset:,}–{end:,} of {total:,}. "
197
+ f"Call fetch-page with offset {end} to read on.]"
198
+ )
199
+ elif offset > 0:
200
+ lines.append("")
201
+ lines.append(f"[Showing characters {offset:,}–{end:,} of {total:,}, the end of the page.]")
202
+ return "\n".join(lines)
203
+
204
+
205
+ def normalize_url(raw: str) -> str:
206
+ text = raw.strip()
207
+ if not text:
208
+ raise FetchError("the URL is empty")
209
+ if len(text) > MAX_URL_CHARS:
210
+ raise FetchError(f"the URL is longer than {MAX_URL_CHARS:,} characters")
211
+ if "://" not in text:
212
+ text = f"https://{text}"
213
+ parts = urlsplit(text)
214
+ scheme = parts.scheme.lower()
215
+ if scheme not in {"http", "https"}:
216
+ raise FetchError(f"only http and https URLs can be fetched, not {parts.scheme}")
217
+ if parts.username is not None or parts.password is not None:
218
+ raise FetchError("URLs with a user name or password cannot be fetched")
219
+ host = (parts.hostname or "").rstrip(".")
220
+ if not host:
221
+ raise FetchError("the URL has no host")
222
+ try:
223
+ ascii_host = host.encode("idna").decode("ascii") if not host.isascii() else host.lower()
224
+ except UnicodeError as error:
225
+ raise FetchError(f"the host {host!r} is not a valid domain name") from error
226
+ try:
227
+ port = parts.port
228
+ except ValueError as error:
229
+ raise FetchError("the URL has an invalid port") from error
230
+ netloc = f"[{ascii_host}]" if ":" in ascii_host else ascii_host
231
+ if port is not None and port != (443 if scheme == "https" else 80):
232
+ netloc = f"{netloc}:{port}"
233
+ return urlunsplit((scheme, netloc, parts.path or "/", parts.query, ""))
234
+
235
+
236
+ def public_addresses(host: str, port: int) -> list[str]:
237
+ """Every address `host` resolves to; raises unless all of them are public."""
238
+
239
+ try:
240
+ infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
241
+ except socket.gaierror as error:
242
+ raise FetchError(f"could not resolve {host}") from error
243
+ addresses: list[str] = []
244
+ for info in infos:
245
+ address = str(info[4][0]).split("%", 1)[0]
246
+ if address not in addresses:
247
+ addresses.append(address)
248
+ if not addresses:
249
+ raise FetchError(f"could not resolve {host}")
250
+ for address in addresses:
251
+ if not is_public_address(address):
252
+ raise FetchError(f"{host} resolves to a private or reserved address, which cannot be fetched")
253
+ return addresses
254
+
255
+
256
+ def is_public_address(address: str) -> bool:
257
+ try:
258
+ ip = ipaddress.ip_address(address)
259
+ except ValueError:
260
+ return False
261
+ if isinstance(ip, ipaddress.IPv6Address):
262
+ mapped = ip.ipv4_mapped or ip.sixtofour
263
+ if mapped is not None:
264
+ ip = mapped
265
+ elif ip.teredo is not None:
266
+ return False
267
+ return ip.is_global and not ip.is_multicast and not ip.is_reserved and not ip.is_unspecified
268
+
269
+
270
+ def _load(url: str) -> _Document:
271
+ deadline = time.monotonic() + DEADLINE_SECONDS
272
+ current = url
273
+ for _hop in range(MAX_REDIRECTS + 1):
274
+ status, headers, body = _request(current, deadline)
275
+ if status in REDIRECT_STATUSES:
276
+ location = headers.get("location")
277
+ if not location:
278
+ raise FetchError(f"{current} redirected without a location")
279
+ current = normalize_url(urljoin(current, location))
280
+ continue
281
+ if status >= 400:
282
+ reason = _REASONS.get(status, "")
283
+ raise FetchError(f"{current} returned HTTP {status}{f' {reason}' if reason else ''}")
284
+ content_type = (headers.get("content-type") or "").split(";", 1)[0].strip().lower()
285
+ title, text = _extract(body, content_type, headers.get("content-type") or "", current)
286
+ return _Document(current, title, text[:MAX_DOCUMENT_CHARS], status, content_type or "unknown")
287
+ raise FetchError(f"{url} redirected more than {MAX_REDIRECTS} times")
288
+
289
+
290
+ def _request(url: str, deadline: float) -> tuple[int, Mapping[str, str], bytes]:
291
+ parts = urlsplit(url)
292
+ host = parts.hostname or ""
293
+ https = parts.scheme == "https"
294
+ port = parts.port or (443 if https else 80)
295
+ address = public_addresses(host, port)[0]
296
+ remaining = deadline - time.monotonic()
297
+ if remaining <= 0:
298
+ raise FetchError(f"{url} took too long to answer")
299
+ timeout = urllib3.Timeout(connect=min(CONNECT_SECONDS, remaining), read=min(READ_SECONDS, remaining))
300
+ bracketed = f"[{host}]" if ":" in host else host
301
+ host_header = bracketed if port == (443 if https else 80) else f"{bracketed}:{port}"
302
+ pool: urllib3.HTTPConnectionPool
303
+ if https:
304
+ pool = urllib3.HTTPSConnectionPool(
305
+ address,
306
+ port=port,
307
+ timeout=timeout,
308
+ retries=False,
309
+ maxsize=1,
310
+ cert_reqs="CERT_REQUIRED",
311
+ server_hostname=host,
312
+ assert_hostname=host,
313
+ )
314
+ else:
315
+ pool = urllib3.HTTPConnectionPool(address, port=port, timeout=timeout, retries=False, maxsize=1)
316
+ path = urlunsplit(("", "", parts.path or "/", parts.query, ""))
317
+ try:
318
+ response = pool.urlopen(
319
+ "GET",
320
+ path,
321
+ headers={**REQUEST_HEADERS, "Host": host_header},
322
+ redirect=False,
323
+ preload_content=False,
324
+ decode_content=True,
325
+ )
326
+ except urllib3.exceptions.SSLError as error:
327
+ pool.close()
328
+ raise FetchError(f"{url} has an invalid TLS certificate") from error
329
+ except (urllib3.exceptions.TimeoutError, socket.timeout) as error:
330
+ pool.close()
331
+ raise FetchError(f"{url} took too long to answer") from error
332
+ except urllib3.exceptions.HTTPError as error:
333
+ pool.close()
334
+ raise FetchError(f"could not connect to {url}") from error
335
+ try:
336
+ headers = {key.lower(): value for key, value in response.headers.items()}
337
+ if response.status in REDIRECT_STATUSES or response.status >= 400:
338
+ return response.status, headers, b""
339
+ chunks: list[bytes] = []
340
+ size = 0
341
+ while size < MAX_BODY_BYTES:
342
+ if time.monotonic() > deadline:
343
+ if not chunks:
344
+ raise FetchError(f"{url} took too long to answer")
345
+ break
346
+ chunk = response.read(64 * 1024)
347
+ if not chunk:
348
+ break
349
+ chunks.append(chunk)
350
+ size += len(chunk)
351
+ return response.status, headers, b"".join(chunks)[:MAX_BODY_BYTES]
352
+ except (urllib3.exceptions.TimeoutError, socket.timeout) as error:
353
+ raise FetchError(f"{url} took too long to answer") from error
354
+ except urllib3.exceptions.HTTPError as error:
355
+ raise FetchError(f"the connection to {url} broke while reading") from error
356
+ finally:
357
+ response.release_conn()
358
+ response.close()
359
+ pool.close()
360
+
361
+
362
+ def _extract(body: bytes, content_type: str, raw_content_type: str, url: str) -> tuple[str, str]:
363
+ if not content_type:
364
+ content_type = _sniff(body)
365
+ if content_type == "application/pdf":
366
+ return _pdf_text(body, url)
367
+ if content_type in HTML_TYPES:
368
+ return _html_text(body, url)
369
+ if content_type.startswith("text/") or content_type in TEXT_TYPES or content_type.endswith(("+json", "+xml")):
370
+ return "", _decode(body, raw_content_type).strip()
371
+ raise FetchError(f"{url} is {content_type}, which fetch-page cannot read")
372
+
373
+
374
+ def _sniff(body: bytes) -> str:
375
+ head = body[:1024].lstrip()
376
+ if head.startswith(b"%PDF"):
377
+ return "application/pdf"
378
+ lowered = head.lower()
379
+ if lowered.startswith((b"<!doctype html", b"<html")) or b"<body" in lowered:
380
+ return "text/html"
381
+ try:
382
+ head.decode("utf-8")
383
+ except UnicodeDecodeError:
384
+ return "application/octet-stream"
385
+ return "text/plain"
386
+
387
+
388
+ def _decode(body: bytes, raw_content_type: str) -> str:
389
+ charset = ""
390
+ for part in raw_content_type.split(";")[1:]:
391
+ name, _, value = part.partition("=")
392
+ if name.strip().lower() == "charset":
393
+ charset = value.strip().strip('"').strip("'")
394
+ for encoding in (charset, "utf-8"):
395
+ if not encoding:
396
+ continue
397
+ try:
398
+ return body.decode(encoding)
399
+ except (LookupError, UnicodeDecodeError):
400
+ continue
401
+ return body.decode("utf-8", errors="replace")
402
+
403
+
404
+ def _html_text(body: bytes, url: str) -> tuple[str, str]:
405
+ metadata = trafilatura.extract_metadata(body, default_url=url)
406
+ title = (metadata.title or "").strip() if metadata is not None else ""
407
+ text = trafilatura.extract(
408
+ body,
409
+ url=url,
410
+ output_format="markdown",
411
+ include_comments=False,
412
+ include_tables=True,
413
+ # Inline links roughly double a page's length, and trafilatura garbles some of them.
414
+ include_links=False,
415
+ include_images=False,
416
+ include_formatting=True,
417
+ favor_recall=True,
418
+ # No `deduplicate`: its cache spans calls, so a page fetched twice would come back emptied.
419
+ )
420
+ if text and text.strip():
421
+ return title, _tidy(text)
422
+ soup = BeautifulSoup(body, "lxml")
423
+ if not title and soup.title and soup.title.string:
424
+ title = soup.title.string.strip()
425
+ for tag in soup(["script", "style", "noscript", "template", "svg", "nav", "footer", "header", "form"]):
426
+ tag.decompose()
427
+ lines = [line.strip() for line in soup.get_text("\n").splitlines()]
428
+ return title, _tidy("\n".join(line for line in lines if line))
429
+
430
+
431
+ def _pdf_text(body: bytes, url: str) -> tuple[str, str]:
432
+ try:
433
+ reader = PdfReader(BytesIO(body))
434
+ if reader.is_encrypted:
435
+ try:
436
+ reader.decrypt("")
437
+ except Exception as error: # noqa: BLE001 — pypdf raises several types for locked files
438
+ raise FetchError(f"{url} is a password-protected PDF") from error
439
+ title = ""
440
+ if reader.metadata is not None and reader.metadata.title:
441
+ title = str(reader.metadata.title).strip()
442
+ pages: list[str] = []
443
+ size = 0
444
+ for page in reader.pages[:MAX_PDF_PAGES]:
445
+ text = (page.extract_text() or "").strip()
446
+ if text:
447
+ pages.append(text)
448
+ size += len(text)
449
+ if size >= MAX_DOCUMENT_CHARS:
450
+ break
451
+ except FetchError:
452
+ raise
453
+ except (PdfReadError, ValueError, KeyError, TypeError) as error:
454
+ raise FetchError(f"{url} is a PDF that could not be read") from error
455
+ return title, _tidy("\n\n".join(pages))
456
+
457
+
458
+ _EDIT_MARKERS = {"[edit]", "\\[edit\\]"}
459
+
460
+
461
+ def _tidy(text: str) -> str:
462
+ lines = [line.rstrip() for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n")]
463
+ tidied: list[str] = []
464
+ blank = 0
465
+ for line in lines:
466
+ if line.strip() in _EDIT_MARKERS:
467
+ continue
468
+ if line.strip():
469
+ blank = 0
470
+ tidied.append(line)
471
+ else:
472
+ blank += 1
473
+ if blank == 1:
474
+ tidied.append("")
475
+ return "\n".join(tidied).strip()
476
+
477
+
478
+ class _DocumentCache:
479
+ """Recently fetched pages, so reading on with `offset` does not fetch again."""
480
+
481
+ def __init__(self, entries: int, seconds: float) -> None:
482
+ self._entries = entries
483
+ self._seconds = seconds
484
+ self._items: OrderedDict[str, tuple[float, _Document]] = OrderedDict()
485
+ self._lock = threading.Lock()
486
+
487
+ def get(self, url: str) -> _Document | None:
488
+ with self._lock:
489
+ item = self._items.get(url)
490
+ if item is None:
491
+ return None
492
+ if time.monotonic() - item[0] > self._seconds:
493
+ del self._items[url]
494
+ return None
495
+ self._items.move_to_end(url)
496
+ return item[1]
497
+
498
+ def put(self, url: str, document: _Document) -> None:
499
+ with self._lock:
500
+ self._items[url] = (time.monotonic(), document)
501
+ self._items.move_to_end(url)
502
+ while len(self._items) > self._entries:
503
+ self._items.popitem(last=False)
504
+
505
+ def clear(self) -> None:
506
+ with self._lock:
507
+ self._items.clear()
508
+
509
+
510
+ _cache = _DocumentCache(CACHE_ENTRIES, CACHE_SECONDS)
511
+
512
+ _REASONS = {
513
+ 400: "Bad Request",
514
+ 401: "Unauthorized",
515
+ 403: "Forbidden",
516
+ 404: "Not Found",
517
+ 405: "Method Not Allowed",
518
+ 406: "Not Acceptable",
519
+ 408: "Request Timeout",
520
+ 410: "Gone",
521
+ 429: "Too Many Requests",
522
+ 451: "Unavailable For Legal Reasons",
523
+ 500: "Internal Server Error",
524
+ 502: "Bad Gateway",
525
+ 503: "Service Unavailable",
526
+ 504: "Gateway Timeout",
527
+ }
tiny_gdn/web_search.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute Nemotron Agentic-v2 `web-search` the way Tercet-R stage-3 SFT saw it.
2
+
3
+ `nvidia/Nemotron-SFT-Agentic-v2` `data/search.jsonl` (packed as
4
+ `agentic_v2_search`) declares a single tool named `web-search` whose
5
+ observations are compact Tavily Search JSON:
6
+
7
+ {"query", "follow_up_questions", "answer", "images", "results",
8
+ "response_time", "request_id"}
9
+
10
+ Each `results[]` item is `{url, title, content, score, raw_content}`
11
+ (about ten hits, with an LLM `answer` when Tavily supplies one). The chat
12
+ template then prefixes that JSON with `<|tool_response|>`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import time
20
+ from collections.abc import Mapping, Sequence
21
+ from dataclasses import dataclass
22
+ from html import unescape
23
+ from html.parser import HTMLParser
24
+ from typing import Any
25
+ from urllib.error import HTTPError, URLError
26
+ from urllib.parse import parse_qs, quote, unquote, urlencode, urlparse
27
+ from urllib.request import Request, urlopen
28
+
29
+ from tiny_gdn.token_file import token_value
30
+
31
+
32
+ NEMOTRON_WEB_SEARCH_TOOL: dict[str, Any] = {
33
+ "type": "function",
34
+ "function": {
35
+ "name": "web-search",
36
+ "description": "Search the web for a query.",
37
+ "parameters": {
38
+ "type": "object",
39
+ "properties": {
40
+ "query": {
41
+ "type": "string",
42
+ "description": "Search query.",
43
+ }
44
+ },
45
+ "required": ["query"],
46
+ },
47
+ },
48
+ }
49
+
50
+ WEB_SEARCH_TOOL_NAME = "web-search"
51
+ DEFAULT_MAX_RESULTS = 10
52
+ TAVILY_SEARCH_URL = "https://api.tavily.com/search"
53
+ DUCKDUCKGO_HTML_URL = "https://html.duckduckgo.com/html/"
54
+ WIKIPEDIA_API_URL = "https://en.wikipedia.org/w/api.php"
55
+ USER_AGENT = (
56
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
57
+ "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
58
+ )
59
+ REQUEST_TIMEOUT_SECONDS = 30.0
60
+ TAVILY_TOKEN_NAME = "tavily-api-key"
61
+
62
+
63
+ def tavily_api_key() -> str:
64
+ """`TAVILY_API_KEY`, else the `tavily-api-key=` line of the project's token.env."""
65
+
66
+ configured = os.environ.get("TAVILY_API_KEY", "").strip()
67
+ return configured or token_value(TAVILY_TOKEN_NAME).strip()
68
+
69
+
70
+ def is_web_search_tool_name(name: str) -> bool:
71
+ return name.strip().lower().replace("_", "-") == WEB_SEARCH_TOOL_NAME
72
+
73
+
74
+ def query_from_arguments(arguments: Mapping[str, Any] | None) -> str:
75
+ if not arguments:
76
+ return ""
77
+ raw = arguments.get("query")
78
+ if isinstance(raw, str):
79
+ return raw.strip()
80
+ if raw is None:
81
+ return ""
82
+ return str(raw).strip()
83
+
84
+
85
+ def dumps_search_payload(payload: Mapping[str, Any]) -> str:
86
+ return json.dumps(canonical_search_payload(payload), ensure_ascii=False)
87
+
88
+
89
+ def canonical_search_payload(payload: Mapping[str, Any]) -> dict[str, Any]:
90
+ results_raw = payload.get("results")
91
+ results: list[dict[str, Any]] = []
92
+ if isinstance(results_raw, Sequence) and not isinstance(results_raw, (str, bytes)):
93
+ for item in results_raw:
94
+ if isinstance(item, Mapping):
95
+ results.append(_canonical_result(item))
96
+ images_raw = payload.get("images")
97
+ images: list[Any] = []
98
+ if isinstance(images_raw, Sequence) and not isinstance(images_raw, (str, bytes)):
99
+ images = list(images_raw)
100
+ return {
101
+ "query": str(payload.get("query") or ""),
102
+ "follow_up_questions": payload.get("follow_up_questions"),
103
+ "answer": payload.get("answer"),
104
+ "images": images,
105
+ "results": results,
106
+ "response_time": payload.get("response_time"),
107
+ "request_id": payload.get("request_id"),
108
+ }
109
+
110
+
111
+ def _canonical_result(item: Mapping[str, Any]) -> dict[str, Any]:
112
+ if item.get("error") and not item.get("url") and not item.get("title"):
113
+ return {"error": str(item["error"])}
114
+ result: dict[str, Any] = {
115
+ "url": str(item.get("url") or ""),
116
+ "title": str(item.get("title") or ""),
117
+ "content": str(item.get("content") or ""),
118
+ "score": _as_score(item.get("score")),
119
+ "raw_content": item.get("raw_content"),
120
+ }
121
+ if item.get("error"):
122
+ result["error"] = str(item["error"])
123
+ return result
124
+
125
+
126
+ def _as_score(value: Any) -> float | None:
127
+ if value is None or value == "":
128
+ return None
129
+ try:
130
+ return float(value)
131
+ except (TypeError, ValueError):
132
+ return None
133
+
134
+
135
+ @dataclass(frozen=True)
136
+ class SearchOutcome:
137
+ """One `web-search` observation and the backend whose results it holds."""
138
+
139
+ observation: str
140
+ # "tavily", "duckduckgo", "wikipedia", "duckduckgo+wikipedia", or "none" when no results came back.
141
+ backend: str
142
+
143
+
144
+ def search_web(
145
+ query: str,
146
+ *,
147
+ max_results: int = DEFAULT_MAX_RESULTS,
148
+ api_key: str | None = None,
149
+ ) -> str:
150
+ """Return a Tavily-shaped JSON string for one `web-search` observation."""
151
+
152
+ return run_web_search(query, max_results=max_results, api_key=api_key).observation
153
+
154
+
155
+ def run_web_search(
156
+ query: str,
157
+ *,
158
+ max_results: int = DEFAULT_MAX_RESULTS,
159
+ api_key: str | None = None,
160
+ ) -> SearchOutcome:
161
+ """Search with Tavily when a key is configured, else DuckDuckGo and Wikipedia."""
162
+
163
+ cleaned = query.strip()
164
+ started = time.perf_counter()
165
+ if not cleaned:
166
+ return SearchOutcome(
167
+ dumps_search_payload(
168
+ _empty_payload(query, error="Search query was empty", response_time=time.perf_counter() - started)
169
+ ),
170
+ "none",
171
+ )
172
+ key = (api_key if api_key is not None else tavily_api_key()).strip()
173
+ fallback_error: str | None = None
174
+ if key:
175
+ try:
176
+ return SearchOutcome(
177
+ dumps_search_payload(_search_tavily(cleaned, api_key=key, max_results=max_results)),
178
+ "tavily",
179
+ )
180
+ except Exception as error:
181
+ fallback_error = f"Tavily search failed: {error}"
182
+ try:
183
+ payload, backend = _search_without_tavily(cleaned, max_results=max_results, fallback_error=fallback_error)
184
+ return SearchOutcome(dumps_search_payload(payload), backend)
185
+ except Exception as error:
186
+ return SearchOutcome(
187
+ dumps_search_payload(
188
+ _empty_payload(
189
+ cleaned,
190
+ error=fallback_error or str(error),
191
+ response_time=time.perf_counter() - started,
192
+ )
193
+ ),
194
+ "none",
195
+ )
196
+
197
+
198
+ def _empty_payload(
199
+ query: str,
200
+ *,
201
+ error: str,
202
+ response_time: float | None,
203
+ ) -> dict[str, Any]:
204
+ return {
205
+ "query": query,
206
+ "follow_up_questions": None,
207
+ "answer": None,
208
+ "images": [],
209
+ "results": [{"error": error}],
210
+ "response_time": response_time,
211
+ "request_id": None,
212
+ }
213
+
214
+
215
+ def _search_tavily(
216
+ query: str,
217
+ *,
218
+ api_key: str,
219
+ max_results: int,
220
+ ) -> dict[str, Any]:
221
+ body = json.dumps(
222
+ {
223
+ "query": query,
224
+ "max_results": max(1, min(int(max_results), 20)),
225
+ "include_answer": True,
226
+ "include_raw_content": False,
227
+ "include_images": False,
228
+ "search_depth": "basic",
229
+ }
230
+ ).encode("utf-8")
231
+ payload = _read_json(
232
+ TAVILY_SEARCH_URL,
233
+ data=body,
234
+ headers={
235
+ "Authorization": f"Bearer {api_key}",
236
+ "Content-Type": "application/json",
237
+ "Accept": "application/json",
238
+ },
239
+ method="POST",
240
+ )
241
+ if not isinstance(payload, dict):
242
+ raise RuntimeError("Tavily returned a non-object payload")
243
+ payload.setdefault("query", query)
244
+ return payload
245
+
246
+
247
+ def _search_without_tavily(
248
+ query: str,
249
+ *,
250
+ max_results: int,
251
+ fallback_error: str | None = None,
252
+ ) -> tuple[dict[str, Any], str]:
253
+ started = time.perf_counter()
254
+ results: list[dict[str, Any]] = []
255
+ errors: list[str] = []
256
+ backends: list[str] = []
257
+ if fallback_error:
258
+ errors.append(fallback_error)
259
+ try:
260
+ results.extend(_search_duckduckgo_html(query, max_results=max_results))
261
+ if results:
262
+ backends.append("duckduckgo")
263
+ except Exception as error:
264
+ errors.append(f"DuckDuckGo search failed: {error}")
265
+ if len(results) < max_results:
266
+ try:
267
+ wiki = _search_wikipedia(query, max_results=max_results)
268
+ seen = {item["url"] for item in results}
269
+ added = 0
270
+ for item in wiki:
271
+ if item["url"] in seen:
272
+ continue
273
+ results.append(item)
274
+ added += 1
275
+ if len(results) >= max_results:
276
+ break
277
+ if added:
278
+ backends.append("wikipedia")
279
+ except Exception as error:
280
+ errors.append(f"Wikipedia search failed: {error}")
281
+ elapsed = time.perf_counter() - started
282
+ if not results:
283
+ message = "; ".join(errors) if errors else "Search returned no results"
284
+ return _empty_payload(query, error=message, response_time=elapsed), "none"
285
+ clipped = results[: max(1, min(int(max_results), 20))]
286
+ for index, item in enumerate(clipped):
287
+ if item.get("score") is None:
288
+ item["score"] = round(max(0.05, 1.0 - (index * 0.07)), 8)
289
+ item.setdefault("raw_content", None)
290
+ answer = clipped[0].get("content") if clipped else None
291
+ if isinstance(answer, str) and not answer.strip():
292
+ answer = None
293
+ payload = {
294
+ "query": query,
295
+ "follow_up_questions": None,
296
+ "answer": answer,
297
+ "images": [],
298
+ "results": clipped,
299
+ "response_time": elapsed,
300
+ "request_id": None,
301
+ }
302
+ return payload, "+".join(backends)
303
+
304
+
305
+ def _search_duckduckgo_html(query: str, *, max_results: int) -> list[dict[str, Any]]:
306
+ encoded = urlencode({"q": query, "kl": "us-en"})
307
+ html = _read_text(
308
+ DUCKDUCKGO_HTML_URL,
309
+ data=encoded.encode("utf-8"),
310
+ headers={
311
+ "Content-Type": "application/x-www-form-urlencoded",
312
+ "Accept": "text/html",
313
+ },
314
+ method="POST",
315
+ )
316
+ parser = _DuckDuckGoParser()
317
+ parser.feed(html)
318
+ parser.close()
319
+ results: list[dict[str, Any]] = []
320
+ seen: set[str] = set()
321
+ for item in parser.results:
322
+ url = item["url"]
323
+ if not url or url in seen:
324
+ continue
325
+ seen.add(url)
326
+ results.append(
327
+ {
328
+ "url": url,
329
+ "title": item["title"],
330
+ "content": item["content"],
331
+ "score": None,
332
+ "raw_content": None,
333
+ }
334
+ )
335
+ if len(results) >= max_results:
336
+ break
337
+ return results
338
+
339
+
340
+ def _search_wikipedia(query: str, *, max_results: int) -> list[dict[str, Any]]:
341
+ params = urlencode(
342
+ {
343
+ "action": "query",
344
+ "list": "search",
345
+ "srsearch": query,
346
+ "srlimit": max(1, min(int(max_results), 10)),
347
+ "srprop": "snippet",
348
+ "format": "json",
349
+ "utf8": "1",
350
+ }
351
+ )
352
+ payload = _read_json(
353
+ f"{WIKIPEDIA_API_URL}?{params}",
354
+ headers={"Accept": "application/json"},
355
+ method="GET",
356
+ )
357
+ if not isinstance(payload, dict):
358
+ return []
359
+ query_block = payload.get("query")
360
+ hits = query_block.get("search") if isinstance(query_block, dict) else None
361
+ if not isinstance(hits, list):
362
+ return []
363
+ results: list[dict[str, Any]] = []
364
+ for hit in hits:
365
+ if not isinstance(hit, dict):
366
+ continue
367
+ title = str(hit.get("title") or "").strip()
368
+ if not title:
369
+ continue
370
+ snippet = unescape(_strip_tags(str(hit.get("snippet") or ""))).strip()
371
+ results.append(
372
+ {
373
+ "url": f"https://en.wikipedia.org/wiki/{quote(title.replace(' ', '_'))}",
374
+ "title": title,
375
+ "content": snippet,
376
+ "score": None,
377
+ "raw_content": None,
378
+ }
379
+ )
380
+ return results
381
+
382
+
383
+ def unwrap_ddg_url(href: str) -> str:
384
+ raw = href.strip()
385
+ if raw.startswith("//"):
386
+ raw = f"https:{raw}"
387
+ parsed = urlparse(raw)
388
+ host = parsed.netloc.lower()
389
+ if "duckduckgo.com" in host:
390
+ values = parse_qs(parsed.query).get("uddg") or []
391
+ if values:
392
+ return unquote(values[0])
393
+ return raw
394
+
395
+
396
+ def _strip_tags(value: str) -> str:
397
+ return _TagStripper.strip(value)
398
+
399
+
400
+ class _TagStripper(HTMLParser):
401
+ def __init__(self) -> None:
402
+ super().__init__()
403
+ self.chunks: list[str] = []
404
+
405
+ def handle_data(self, data: str) -> None:
406
+ self.chunks.append(data)
407
+
408
+ @classmethod
409
+ def strip(cls, value: str) -> str:
410
+ parser = cls()
411
+ parser.feed(value)
412
+ parser.close()
413
+ return "".join(parser.chunks)
414
+
415
+
416
+ class _DuckDuckGoParser(HTMLParser):
417
+ def __init__(self) -> None:
418
+ super().__init__()
419
+ self.results: list[dict[str, str]] = []
420
+ self._in_title = False
421
+ self._in_snippet = False
422
+ self._href = ""
423
+ self._buffer: list[str] = []
424
+ self._pending: dict[str, str] | None = None
425
+
426
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
427
+ classes = {item for item in (dict(attrs).get("class") or "").split() if item}
428
+ if tag == "a" and "result__a" in classes:
429
+ self._flush_pending()
430
+ self._in_title = True
431
+ self._href = dict(attrs).get("href") or ""
432
+ self._buffer = []
433
+ return
434
+ if tag in {"a", "div"} and "result__snippet" in classes:
435
+ self._in_snippet = True
436
+ self._buffer = []
437
+
438
+ def handle_endtag(self, tag: str) -> None:
439
+ if tag == "a" and self._in_title:
440
+ title = unescape("".join(self._buffer)).strip()
441
+ url = unwrap_ddg_url(self._href)
442
+ self._pending = {"title": title, "url": url, "content": ""}
443
+ self._in_title = False
444
+ self._buffer = []
445
+ return
446
+ if self._in_snippet and tag in {"a", "div"}:
447
+ snippet = unescape("".join(self._buffer)).strip()
448
+ if self._pending is not None:
449
+ self._pending["content"] = snippet
450
+ self.results.append(self._pending)
451
+ self._pending = None
452
+ self._in_snippet = False
453
+ self._buffer = []
454
+
455
+ def handle_data(self, data: str) -> None:
456
+ if self._in_title or self._in_snippet:
457
+ self._buffer.append(data)
458
+
459
+ def close(self) -> None:
460
+ self._flush_pending()
461
+ super().close()
462
+
463
+ def _flush_pending(self) -> None:
464
+ if self._pending is None:
465
+ return
466
+ self.results.append(self._pending)
467
+ self._pending = None
468
+
469
+
470
+ def _read_json(
471
+ url: str,
472
+ *,
473
+ data: bytes | None = None,
474
+ headers: Mapping[str, str],
475
+ method: str,
476
+ ) -> Any:
477
+ text = _read_text(url, data=data, headers=headers, method=method)
478
+ return json.loads(text)
479
+
480
+
481
+ def _read_text(
482
+ url: str,
483
+ *,
484
+ data: bytes | None = None,
485
+ headers: Mapping[str, str],
486
+ method: str,
487
+ ) -> str:
488
+ merged = {"User-Agent": USER_AGENT, **dict(headers)}
489
+ request = Request(url, data=data, headers=merged, method=method)
490
+ try:
491
+ with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
492
+ raw = response.read()
493
+ charset = response.headers.get_content_charset() or "utf-8"
494
+ except HTTPError as error:
495
+ detail = error.read().decode("utf-8", errors="replace")
496
+ raise RuntimeError(
497
+ f"{error.code} {error.reason} from {url}: {detail[:500]}"
498
+ ) from error
499
+ except URLError as error:
500
+ raise RuntimeError(f"Could not reach {url}: {error.reason}") from error
501
+ return raw.decode(charset, errors="replace")
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "bos_token": "<|begin_of_text|>",
5
+ "eos_token": "<|end_of_text|>",
6
+ "pad_token": "<|padding|>",
7
+ "unk_token": "<|unknown|>",
8
+ "model_max_length": 2048,
9
+ "clean_up_tokenization_spaces": false,
10
+ "tokenizer_class": "PreTrainedTokenizerFast",
11
+ "chat_template": "{%- set ns = namespace(xml_tools=none, tools_emitted=false) -%}\n{%- if xml_tools is defined and xml_tools -%}\n{%- set ns.xml_tools = xml_tools -%}\n{%- elif tools is defined and tools -%}\n{%- set ns.xml_tools = tools -%}\n{%- endif -%}\n{%- set tools_preamble = 'You may call one or more functions to assist with the user query.\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\\n' -%}\n{%- set tools_epilogue = '</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>' -%}\n{%- for message in messages -%}\n{%- if loop.first -%}{{- bos_token -}}{%- endif -%}\n{%- if loop.first and ns.xml_tools and message['role'] != 'system' -%}\n{{- '<|im_start|>system\\n' + tools_preamble -}}\n{%- for tool in ns.xml_tools -%}\n{%- if tool is string -%}{{- (tool | replace('<tools>', '') | replace('</tools>', '') | trim) + '\\n' -}}\n{%- else -%}{{- tool | tojson + '\\n' -}}\n{%- endif -%}\n{%- endfor -%}\n{{- tools_epilogue + '<|im_end|>\\n' -}}\n{%- set ns.tools_emitted = true -%}\n{%- endif -%}\n{%- set raw_role = message['role'] -%}\n{%- set role = 'user' if raw_role == 'tool' or raw_role == 'function' else raw_role -%}\n{%- set content_text = namespace(value='') -%}\n{%- if message['content'] is string -%}\n{%- set content_text.value = message['content'] -%}\n{%- elif message['content'] is iterable -%}\n{%- for item in message['content'] -%}\n{%- if item['type'] == 'text' -%}{%- set content_text.value = content_text.value + item['text'] -%}{%- endif -%}\n{%- endfor -%}\n{%- endif -%}\n{%- set is_tool = raw_role == 'tool' or raw_role == 'function' -%}\n{%- set prev_is_tool = loop.previtem is defined and (loop.previtem['role'] == 'tool' or loop.previtem['role'] == 'function') -%}\n{%- set next_is_tool = loop.nextitem is defined and (loop.nextitem['role'] == 'tool' or loop.nextitem['role'] == 'function') -%}\n{%- if raw_role == 'system' and not (content_text.value | trim) and not (ns.xml_tools and not ns.tools_emitted) -%}\n{%- else -%}\n{%- if is_tool and prev_is_tool -%}\n{{- '\\n' -}}\n{%- else -%}\n{{- '<|im_start|>' + role + '\\n' -}}\n{%- endif -%}\n{%- if raw_role == 'assistant' and enable_thinking is defined -%}\n{{- ('<|think|>\\n' if enable_thinking else '<|no_think|>\\n') -}}\n{%- endif -%}\n{%- if is_tool -%}\n{{- '<|tool_response|>\\n' + (content_text.value | replace('<tool_response>', '') | replace('</tool_response>', '') | trim) -}}\n{%- elif raw_role == 'system' -%}\n{{- content_text.value | replace('/system_override', '') | replace('/no_think', '') | replace('/think', '') | trim -}}\n{%- else -%}\n{{- content_text.value -}}\n{%- endif -%}\n{%- if raw_role == 'system' and ns.xml_tools and not ns.tools_emitted and '<tools>' not in content_text.value -%}\n{%- if content_text.value | trim -%}{{- '\\n\\n' -}}{%- endif -%}\n{{- tools_preamble -}}\n{%- for tool in ns.xml_tools -%}\n{%- if tool is string -%}{{- (tool | replace('<tools>', '') | replace('</tools>', '') | trim) + '\\n' -}}\n{%- else -%}{{- tool | tojson + '\\n' -}}\n{%- endif -%}\n{%- endfor -%}\n{{- tools_epilogue -}}\n{%- set ns.tools_emitted = true -%}\n{%- endif -%}\n{%- if raw_role == 'assistant' and message['tool_calls'] is defined and message['tool_calls'] -%}\n{%- if '<tool_call>' not in content_text.value -%}\n{%- for tool_call in message['tool_calls'] -%}\n{%- set fn = tool_call['function'] if tool_call['function'] is defined else tool_call -%}\n{%- if loop.first and not (content_text.value | trim) -%}\n{{- '<tool_call>\\n{\"name\": \"' + fn['name'] + '\", \"arguments\": ' -}}\n{%- else -%}\n{{- '\\n<tool_call>\\n{\"name\": \"' + fn['name'] + '\", \"arguments\": ' -}}\n{%- endif -%}\n{%- if fn['arguments'] is string -%}{{- fn['arguments'] -}}\n{%- else -%}{{- fn['arguments'] | tojson -}}\n{%- endif -%}\n{{- '}\\n</tool_call>' -}}\n{%- endfor -%}\n{%- endif -%}\n{%- endif -%}\n{%- if not (is_tool and next_is_tool) -%}\n{{- '<|im_end|>\\n' -}}\n{%- endif -%}\n{%- endif -%}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n{{- '<|im_start|>assistant\\n' -}}\n{%- if enable_thinking is defined -%}{{- ('<|think|>\\n' if enable_thinking else '<|no_think|>\\n') -}}{%- endif -%}\n{%- endif -%}",
12
+ "extra_special_tokens": [
13
+ "<|im_start|>",
14
+ "<|im_end|>",
15
+ "<|tool_call|>",
16
+ "<|tool_response|>",
17
+ "<think>",
18
+ "</think>",
19
+ "<|fim_prefix|>",
20
+ "<|fim_middle|>",
21
+ "<|fim_suffix|>",
22
+ "<|fim_pad|>",
23
+ "<|no_think|>",
24
+ "<|think|>",
25
+ "<|reserved_002|>",
26
+ "<|reserved_003|>",
27
+ "<|reserved_004|>",
28
+ "<|reserved_005|>",
29
+ "<|reserved_006|>",
30
+ "<|reserved_007|>",
31
+ "<|reserved_008|>",
32
+ "<|reserved_009|>",
33
+ "<|reserved_010|>",
34
+ "<|reserved_011|>",
35
+ "<|reserved_012|>",
36
+ "<|reserved_013|>",
37
+ "<|reserved_014|>",
38
+ "<|reserved_015|>",
39
+ "<|reserved_016|>",
40
+ "<|reserved_017|>",
41
+ "<|reserved_018|>",
42
+ "<|reserved_019|>",
43
+ "<|reserved_020|>",
44
+ "<|reserved_021|>",
45
+ "<|reserved_022|>",
46
+ "<|reserved_023|>",
47
+ "<|reserved_024|>",
48
+ "<|reserved_025|>",
49
+ "<|reserved_026|>",
50
+ "<|reserved_027|>",
51
+ "<|reserved_028|>",
52
+ "<|reserved_029|>",
53
+ "<|reserved_030|>",
54
+ "<|reserved_031|>",
55
+ "<|reserved_032|>",
56
+ "<|reserved_033|>",
57
+ "<|reserved_034|>",
58
+ "<|reserved_035|>",
59
+ "<|reserved_036|>",
60
+ "<|reserved_037|>",
61
+ "<|reserved_038|>",
62
+ "<|reserved_039|>",
63
+ "<|reserved_040|>",
64
+ "<|reserved_041|>",
65
+ "<|reserved_042|>",
66
+ "<|reserved_043|>",
67
+ "<|reserved_044|>",
68
+ "<|reserved_045|>",
69
+ "<|reserved_046|>",
70
+ "<|reserved_047|>",
71
+ "<|reserved_048|>",
72
+ "<|reserved_049|>"
73
+ ]
74
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
windows_fla_patches/fla/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023-2026, Songlin Yang, Yu Zhang, Zhiyuan Li
2
+ #
3
+ # Keep package import light. Eagerly importing fla.layers pulls every Triton
4
+ # kernel and breaks on Windows + Triton 3.7.
5
+
6
+ from pkgutil import extend_path
7
+
8
+ __path__ = extend_path(__path__, __name__)
9
+ __version__ = "0.5.2"
10
+ __all__: list[str] = []
windows_fla_patches/fla/layers/__init__.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023-2026, Songlin Yang, Yu Zhang, Zhiyuan Li
2
+ #
3
+ # Lazy layer exports — avoid compiling every Triton kernel at import time.
4
+
5
+ from __future__ import annotations
6
+
7
+ import importlib
8
+ from typing import Any
9
+
10
+ _EXPORTS: dict[str, tuple[str, str]] = {
11
+ "ABCAttention": (".abc", "ABCAttention"),
12
+ "Attention": (".attn", "Attention"),
13
+ "BasedLinearAttention": (".based", "BasedLinearAttention"),
14
+ "BitAttention": (".bitattn", "BitAttention"),
15
+ "Comba": (".comba", "Comba"),
16
+ "DeltaNet": (".delta_net", "DeltaNet"),
17
+ "DeltaFormerAttention": (".deltaformer", "DeltaFormerAttention"),
18
+ "ForgettingAttention": (".forgetting_attn", "ForgettingAttention"),
19
+ "GatedDeltaNet": (".gated_deltanet", "GatedDeltaNet"),
20
+ "GatedDeltaProduct": (".gated_deltaproduct", "GatedDeltaProduct"),
21
+ "GatedDeltaNet2": (".gdn2", "GatedDeltaNet2"),
22
+ "GatedLinearAttention": (".gla", "GatedLinearAttention"),
23
+ "GatedSlotAttention": (".gsa", "GatedSlotAttention"),
24
+ "HGRNAttention": (".hgrn", "HGRNAttention"),
25
+ "HGRN2Attention": (".hgrn2", "HGRN2Attention"),
26
+ "KimiDeltaAttention": (".kda", "KimiDeltaAttention"),
27
+ "LightNetAttention": (".lightnet", "LightNetAttention"),
28
+ "LinearAttention": (".linear_attn", "LinearAttention"),
29
+ "LogLinearMamba2": (".log_linear_mamba2", "LogLinearMamba2"),
30
+ "Mamba": (".mamba", "Mamba"),
31
+ "Mamba2": (".mamba2", "Mamba2"),
32
+ "Mamba3": (".mamba3", "Mamba3"),
33
+ "MesaNet": (".mesa_net", "MesaNet"),
34
+ "MultiheadLatentAttention": (".mla", "MultiheadLatentAttention"),
35
+ "MoBA": (".moba", "MoBA"),
36
+ "MomAttention": (".mom", "MomAttention"),
37
+ "MultiScaleRetention": (".multiscale_retention", "MultiScaleRetention"),
38
+ "NativeSparseAttention": (".nsa", "NativeSparseAttention"),
39
+ "Parallax": (".parallax", "Parallax"),
40
+ "PaTHAttention": (".path_attn", "PaTHAttention"),
41
+ "Raven": (".raven", "Raven"),
42
+ "ReBasedLinearAttention": (".rebased", "ReBasedLinearAttention"),
43
+ "RodimusAttention": (".rodimus", "RodimusAttention"),
44
+ "SlidingWindowSharedKeyAttention": (".rodimus", "SlidingWindowSharedKeyAttention"),
45
+ "RWKV6Attention": (".rwkv6", "RWKV6Attention"),
46
+ "RWKV7Attention": (".rwkv7", "RWKV7Attention"),
47
+ "WallAttention": (".wall_attn", "WallAttention"),
48
+ "YOCOCrossAttention": (".yoco", "YOCOCrossAttention"),
49
+ "YOCOGatedRetention": (".yoco", "YOCOGatedRetention"),
50
+ "YOCOSharedKVBuilder": (".yoco", "YOCOSharedKVBuilder"),
51
+ }
52
+
53
+ __all__ = list(_EXPORTS)
54
+
55
+
56
+ def __getattr__(name: str) -> Any:
57
+ spec = _EXPORTS.get(name)
58
+ if spec is None:
59
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
60
+ module_name, attr = spec
61
+ value = getattr(importlib.import_module(module_name, __name__), attr)
62
+ globals()[name] = value
63
+ return value
windows_fla_patches/fla/ops/__init__.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023-2026, Songlin Yang, Yu Zhang, Zhiyuan Li
2
+ #
3
+ # Lazy public exports so importing fla.ops.utils / fla.ops.gdn2 does not
4
+ # eagerly compile every Triton kernel (needed on Windows + Triton 3.7).
5
+
6
+ from __future__ import annotations
7
+
8
+ import importlib
9
+ from typing import Any
10
+
11
+ _EXPORTS: dict[str, str] = {
12
+ "chunk_abc": "fla.ops.abc",
13
+ "parallel_attn": "fla.ops.attn",
14
+ "fused_attnres": "fla.ops.attnres",
15
+ "fused_chunk_based": "fla.ops.based",
16
+ "parallel_based": "fla.ops.based",
17
+ "chunk_comba": "fla.ops.comba",
18
+ "fused_recurrent_comba": "fla.ops.comba",
19
+ "chunk_delta_rule": "fla.ops.delta_rule",
20
+ "fused_chunk_delta_rule": "fla.ops.delta_rule",
21
+ "fused_recurrent_delta_rule": "fla.ops.delta_rule",
22
+ "parallel_forgetting_attn": "fla.ops.forgetting_attn",
23
+ "chunk_gated_delta_rule": "fla.ops.gated_delta_rule",
24
+ "chunk_gdn": "fla.ops.gated_delta_rule",
25
+ "fused_recurrent_gated_delta_rule": "fla.ops.gated_delta_rule",
26
+ "fused_recurrent_gdn": "fla.ops.gated_delta_rule",
27
+ "chunk_dplr_delta_rule": "fla.ops.generalized_delta_rule",
28
+ "chunk_iplr_delta_rule": "fla.ops.generalized_delta_rule",
29
+ "fused_recurrent_dplr_delta_rule": "fla.ops.generalized_delta_rule",
30
+ "fused_recurrent_iplr_delta_rule": "fla.ops.generalized_delta_rule",
31
+ "chunk_gla": "fla.ops.gla",
32
+ "fused_chunk_gla": "fla.ops.gla",
33
+ "fused_recurrent_gla": "fla.ops.gla",
34
+ "chunk_gsa": "fla.ops.gsa",
35
+ "fused_recurrent_gsa": "fla.ops.gsa",
36
+ "fused_recurrent_hgrn": "fla.ops.hgrn",
37
+ "chunk_kda": "fla.ops.kda",
38
+ "fused_recurrent_kda": "fla.ops.kda",
39
+ "chunk_lightning_attn": "fla.ops.lightning_attn",
40
+ "fused_recurrent_lightning_attn": "fla.ops.lightning_attn",
41
+ "chunk_linear_attn": "fla.ops.linear_attn",
42
+ "fused_chunk_linear_attn": "fla.ops.linear_attn",
43
+ "fused_recurrent_linear_attn": "fla.ops.linear_attn",
44
+ "chunk_log_linear_attn": "fla.ops.log_linear_attn",
45
+ "chunk_mesa_net": "fla.ops.mesa_net",
46
+ "parallel_nsa": "fla.ops.nsa",
47
+ "parallel_parallax": "fla.ops.parallax",
48
+ "parallel_path_attn": "fla.ops.path_attn",
49
+ "chunk_retention": "fla.ops.retention",
50
+ "fused_chunk_retention": "fla.ops.retention",
51
+ "fused_recurrent_retention": "fla.ops.retention",
52
+ "parallel_retention": "fla.ops.retention",
53
+ "chunk_rwkv6": "fla.ops.rwkv6",
54
+ "fused_recurrent_rwkv6": "fla.ops.rwkv6",
55
+ "chunk_rwkv7": "fla.ops.rwkv7",
56
+ "fused_recurrent_rwkv7": "fla.ops.rwkv7",
57
+ "chunk_simple_gla": "fla.ops.simple_gla",
58
+ "fused_chunk_simple_gla": "fla.ops.simple_gla",
59
+ "fused_recurrent_simple_gla": "fla.ops.simple_gla",
60
+ "parallel_simple_gla": "fla.ops.simple_gla",
61
+ "parallel_wall_attn": "fla.ops.wall_attn",
62
+ "parallel_wall_attn_decode": "fla.ops.wall_attn",
63
+ "chunk_gdn2": "fla.ops.gdn2",
64
+ "fused_recurrent_gdn2": "fla.ops.gdn2",
65
+ }
66
+
67
+ __all__ = list(_EXPORTS)
68
+
69
+
70
+ def __getattr__(name: str) -> Any:
71
+ module_name = _EXPORTS.get(name)
72
+ if module_name is None:
73
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
74
+ value = getattr(importlib.import_module(module_name), name)
75
+ globals()[name] = value
76
+ return value
windows_fla_patches/fla/ops/simple_gla/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2023-2026, Songlin Yang, Yu Zhang, Zhiyuan Li
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+ # For a list of all contributors, visit:
6
+ # https://github.com/fla-org/flash-linear-attention/graphs/contributors
7
+
8
+ from .chunk import chunk_simple_gla
9
+ from .fused_chunk import fused_chunk_simple_gla
10
+ from .fused_recurrent import fused_recurrent_simple_gla
11
+
12
+ # Triton 3.7 on Windows can fail while decorating parallel kernels at import time.
13
+ try:
14
+ from .parallel import parallel_simple_gla
15
+ except Exception: # noqa: BLE001
16
+ parallel_simple_gla = None
17
+
18
+ __all__ = [
19
+ 'chunk_simple_gla',
20
+ 'fused_chunk_simple_gla',
21
+ 'fused_recurrent_simple_gla',
22
+ 'parallel_simple_gla',
23
+ ]