Text Generation
Transformers
Safetensors
English
moeloop
looptitan
mixture-of-experts
Mixture of Experts
looped-moe
looped-transformer
looped-language-model
recurrent-depth
weight-sharing
custom_code
adamw
conversational
Eval Results (legacy)
Instructions to use NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW
- SGLang
How to use NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW with Docker Model Runner:
docker model run hf.co/NaturalScale/LoopTitan-Looped-1.3B-A0.2B-AdamW
Add release files
Browse files- .gitattributes +1 -0
- LICENSE +21 -0
- README.md +93 -0
- banner.svg +6 -0
- budgets.svg +6 -0
- cache.py +81 -0
- chat_template.jinja +89 -0
- config.json +73 -0
- config.py +365 -0
- eval-test.json +35 -0
- eval-validation.json +35 -0
- export_provenance.json +87 -0
- generation_config.json +10 -0
- hf.py +212 -0
- latent.py +64 -0
- memory.py +60 -0
- model.py +637 -0
- model.safetensors +3 -0
- moe.py +98 -0
- release_provenance.json +24 -0
- tokenizer.json +3 -0
- tokenizer_config.json +33 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 The LoopTitan authors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
library_name: transformers
|
| 4 |
+
pipeline_tag: text-generation
|
| 5 |
+
tags:
|
| 6 |
+
- "looptitan"
|
| 7 |
+
- "mixture-of-experts"
|
| 8 |
+
- "looped-moe"
|
| 9 |
+
- "custom_code"
|
| 10 |
+
- "adamw"
|
| 11 |
+
datasets:
|
| 12 |
+
- "mlfoundations/dclm-baseline-1.0-parquet"
|
| 13 |
+
model-index:
|
| 14 |
+
- name: "looptitan-p1-loop6x2-adamw"
|
| 15 |
+
results:
|
| 16 |
+
- task:
|
| 17 |
+
type: text-generation
|
| 18 |
+
dataset:
|
| 19 |
+
name: "mlfoundations/dclm-baseline-1.0-parquet"
|
| 20 |
+
type: "mlfoundations/dclm-baseline-1.0-parquet"
|
| 21 |
+
metrics:
|
| 22 |
+
- name: Test BPB
|
| 23 |
+
type: bpb
|
| 24 |
+
value: 0.990544
|
| 25 |
+
- name: Validation BPB
|
| 26 |
+
type: bpb
|
| 27 |
+
value: 0.992211
|
| 28 |
+
---
|
| 29 |
+
|
| 30 |
+

|
| 31 |
+
|
| 32 |
+
# Looped MoE: the middle 6 layers run twice
|
| 33 |
+
|
| 34 |
+
AdamW · LoopTitan Phase 1
|
| 35 |
+
|
| 36 |
+
Chain-end loop: 12 layers at width 1056, 88 experts per layer, expert hidden size 384; the middle 6 looped twice, residual ×0.5; every part shared across visits. A base language model trained from scratch, not instruction tuned.
|
| 37 |
+
|
| 38 |
+
## Results
|
| 39 |
+
|
| 40 |
+
| Test BPB | Validation BPB | Δ test vs ordinary MoE (AdamW) |
|
| 41 |
+
|---:|---:|---:|
|
| 42 |
+
| 0.990544 | 0.992211 | -8.99 mBPB |
|
| 43 |
+
|
| 44 |
+
Bits per byte on the complete held-out test and validation splits after the last update. The ordinary MoE is [`recipes/phase1/m0-adamw.json`](https://github.com/datamllab/LoopTitan/blob/main/recipes/phase1/m0-adamw.json); 1 mBPB is 0.001 BPB.
|
| 45 |
+
|
| 46 |
+
## Budgets
|
| 47 |
+
|
| 48 |
+
Matched budgets: all three within 5% of the ordinary MoE (AdamW).
|
| 49 |
+
|
| 50 |
+

|
| 51 |
+
|
| 52 |
+
## Training
|
| 53 |
+
|
| 54 |
+
5.0B tokens of [mlfoundations/dclm-baseline-1.0-parquet](https://huggingface.co/datasets/mlfoundations/dclm-baseline-1.0-parquet) at revision `817d6752765f6a41261085171dd546b104f60626` (CC-BY-4.0): 4,769 updates of 1,048,576 tokens in sequences of 4,096, warmup-stable-decay schedule, seed 42. AdamW at learning rate 1.2e-3, the value tuned once per optimizer on the ordinary MoE; the same grid on this model selects the same value ([#180](https://github.com/datamllab/LoopTitan/issues/180)). The full protocol: [results page](https://github.com/datamllab/LoopTitan/blob/main/docs/results/phase1.md).
|
| 55 |
+
|
| 56 |
+
## Use
|
| 57 |
+
|
| 58 |
+
```python
|
| 59 |
+
import torch
|
| 60 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 61 |
+
|
| 62 |
+
repo = "NaturalScale/looptitan-p1-loop6x2-adamw"
|
| 63 |
+
tokenizer = AutoTokenizer.from_pretrained(repo)
|
| 64 |
+
model = AutoModelForCausalLM.from_pretrained(repo, trust_remote_code=True).eval()
|
| 65 |
+
ids = torch.tensor([[tokenizer.bos_token_id] + tokenizer.encode("The model", add_special_tokens=False)])
|
| 66 |
+
out = model.generate(ids, attention_mask=torch.ones_like(ids), max_new_tokens=32, do_sample=False)
|
| 67 |
+
print(tokenizer.decode(out[0], skip_special_tokens=True))
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
The model runs Python code from this repository: read it first, or pin `revision=`.
|
| 71 |
+
|
| 72 |
+
## Links
|
| 73 |
+
|
| 74 |
+
- Code: [LoopTitan](https://github.com/datamllab/LoopTitan)
|
| 75 |
+
- Configuration: [`recipes/phase1/m3-adamw.json`](https://github.com/datamllab/LoopTitan/blob/main/recipes/phase1/m3-adamw.json)
|
| 76 |
+
- Documentation: [docs](https://github.com/datamllab/LoopTitan/tree/main/docs)
|
| 77 |
+
- Results: [results page](https://github.com/datamllab/LoopTitan/blob/main/docs/results/phase1.md)
|
| 78 |
+
- Run record: [#180](https://github.com/datamllab/LoopTitan/issues/180)
|
| 79 |
+
|
| 80 |
+
## Citation
|
| 81 |
+
|
| 82 |
+
```bibtex
|
| 83 |
+
@software{looptitan,
|
| 84 |
+
title = {{LoopTitan}},
|
| 85 |
+
author = {{The LoopTitan authors}},
|
| 86 |
+
version = {1.0.0rc1},
|
| 87 |
+
url = {https://github.com/datamllab/LoopTitan}
|
| 88 |
+
}
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
## Licence
|
| 92 |
+
|
| 93 |
+
[MIT](https://github.com/datamllab/LoopTitan/blob/main/LICENSE).
|
banner.svg
ADDED
|
|
budgets.svg
ADDED
|
|
cache.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact, inference-only KV storage indexed by logical attention calls."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass, field
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
CacheSlot = tuple[str, int, int]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class DecodeCache:
|
| 16 |
+
"""Fixed-depth KV cache. Shared attention weights still have separate slots.
|
| 17 |
+
|
| 18 |
+
``length`` counts stored columns (including padding), while ``valid_mask``
|
| 19 |
+
and ``positions`` retain each row's valid-token and RoPE metadata. Use
|
| 20 |
+
:meth:`reorder` for beam/batch reordering; never reorder slots individually.
|
| 21 |
+
During a forward every attention call appends to its slot; ``advance`` then
|
| 22 |
+
records the forward's columns. A forward that raises midway leaves some
|
| 23 |
+
slots longer than ``length``, and the next forward on this cache fails, so
|
| 24 |
+
``clear`` it or start a new cache.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
num_visits: int
|
| 28 |
+
length: int = field(default=0, init=False)
|
| 29 |
+
slots: dict[CacheSlot, tuple[Tensor, Tensor]] = field(default_factory=dict, init=False)
|
| 30 |
+
positions: Tensor | None = field(default=None, init=False)
|
| 31 |
+
valid_mask: Tensor | None = field(default=None, init=False)
|
| 32 |
+
|
| 33 |
+
def next_positions(self, valid_mask: Tensor) -> Tensor:
|
| 34 |
+
"""Standard padding-aware positions for the new query columns."""
|
| 35 |
+
offset = valid_mask.new_zeros((valid_mask.size(0), 1), dtype=torch.long)
|
| 36 |
+
if self.valid_mask is not None:
|
| 37 |
+
if self.valid_mask.size(0) != valid_mask.size(0):
|
| 38 |
+
raise ValueError("cache batch size changed without reorder")
|
| 39 |
+
columns = torch.arange(self.length, device=self.valid_mask.device)
|
| 40 |
+
last = torch.where(self.valid_mask, columns, -1).amax(-1, keepdim=True)
|
| 41 |
+
offset = self.positions.gather(1, last.clamp_min(0)) + 1
|
| 42 |
+
offset = torch.where(last >= 0, offset, 0)
|
| 43 |
+
positions = offset + valid_mask.long().cumsum(-1) - 1
|
| 44 |
+
return positions.clamp_min(0)
|
| 45 |
+
|
| 46 |
+
def append(self, slot: CacheSlot, key: Tensor, value: Tensor) -> tuple[Tensor, Tensor]:
|
| 47 |
+
"""Append this forward's [batch, kv_heads, tokens, head_dim] K/V; return the slot's whole K/V."""
|
| 48 |
+
if slot in self.slots:
|
| 49 |
+
old_key, old_value = self.slots[slot]
|
| 50 |
+
key, value = torch.cat((old_key, key), dim=-2), torch.cat((old_value, value), dim=-2)
|
| 51 |
+
self.slots[slot] = (key, value)
|
| 52 |
+
return key, value
|
| 53 |
+
|
| 54 |
+
def advance(self, positions: Tensor, valid_mask: Tensor, expected_slots: tuple[CacheSlot, ...]) -> None:
|
| 55 |
+
"""Record a finished forward's columns; every expected slot must hold all of them."""
|
| 56 |
+
if self.positions is not None:
|
| 57 |
+
positions = torch.cat((self.positions, positions), dim=1)
|
| 58 |
+
valid_mask = torch.cat((self.valid_mask, valid_mask), dim=1)
|
| 59 |
+
length = positions.size(1)
|
| 60 |
+
if set(self.slots) != set(expected_slots) or any(key.size(-2) != length for key, _ in self.slots.values()):
|
| 61 |
+
raise ValueError("forward did not update every logical cache slot; "
|
| 62 |
+
"clear() the cache after a failed forward")
|
| 63 |
+
self.positions, self.valid_mask, self.length = positions, valid_mask, length
|
| 64 |
+
|
| 65 |
+
def reorder(self, indices: Tensor) -> "DecodeCache":
|
| 66 |
+
if indices.ndim != 1 or indices.dtype not in (torch.int32, torch.int64):
|
| 67 |
+
raise ValueError("cache reorder indices must be integer [new_batch]")
|
| 68 |
+
self.slots = {
|
| 69 |
+
slot: (key.index_select(0, indices.to(key.device, dtype=torch.long)),
|
| 70 |
+
value.index_select(0, indices.to(value.device, dtype=torch.long)))
|
| 71 |
+
for slot, (key, value) in self.slots.items()
|
| 72 |
+
}
|
| 73 |
+
if self.positions is not None:
|
| 74 |
+
self.positions = self.positions.index_select(0, indices.to(self.positions.device, dtype=torch.long))
|
| 75 |
+
self.valid_mask = self.valid_mask.index_select(0, indices.to(self.valid_mask.device, dtype=torch.long))
|
| 76 |
+
return self
|
| 77 |
+
|
| 78 |
+
def clear(self) -> None:
|
| 79 |
+
self.slots.clear()
|
| 80 |
+
self.length = 0
|
| 81 |
+
self.positions = self.valid_mask = None
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- if tools %}
|
| 2 |
+
{{- '<|im_start|>system\n' }}
|
| 3 |
+
{%- if messages[0].role == 'system' %}
|
| 4 |
+
{{- messages[0].content + '\n\n' }}
|
| 5 |
+
{%- endif %}
|
| 6 |
+
{{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
|
| 7 |
+
{%- for tool in tools %}
|
| 8 |
+
{{- "\n" }}
|
| 9 |
+
{{- tool | tojson }}
|
| 10 |
+
{%- endfor %}
|
| 11 |
+
{{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
|
| 12 |
+
{%- else %}
|
| 13 |
+
{%- if messages[0].role == 'system' %}
|
| 14 |
+
{{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
|
| 15 |
+
{%- endif %}
|
| 16 |
+
{%- endif %}
|
| 17 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 18 |
+
{%- for message in messages[::-1] %}
|
| 19 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
| 20 |
+
{%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
|
| 21 |
+
{%- set ns.multi_step_tool = false %}
|
| 22 |
+
{%- set ns.last_query_index = index %}
|
| 23 |
+
{%- endif %}
|
| 24 |
+
{%- endfor %}
|
| 25 |
+
{%- for message in messages %}
|
| 26 |
+
{%- if message.content is string %}
|
| 27 |
+
{%- set content = message.content %}
|
| 28 |
+
{%- else %}
|
| 29 |
+
{%- set content = '' %}
|
| 30 |
+
{%- endif %}
|
| 31 |
+
{%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
|
| 32 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 33 |
+
{%- elif message.role == "assistant" %}
|
| 34 |
+
{%- set reasoning_content = '' %}
|
| 35 |
+
{%- if message.reasoning_content is string %}
|
| 36 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 37 |
+
{%- else %}
|
| 38 |
+
{%- if '</think>' in content %}
|
| 39 |
+
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
|
| 40 |
+
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
|
| 41 |
+
{%- endif %}
|
| 42 |
+
{%- endif %}
|
| 43 |
+
{%- if loop.index0 > ns.last_query_index %}
|
| 44 |
+
{%- if loop.last or (not loop.last and reasoning_content) %}
|
| 45 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
|
| 46 |
+
{%- else %}
|
| 47 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 48 |
+
{%- endif %}
|
| 49 |
+
{%- else %}
|
| 50 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 51 |
+
{%- endif %}
|
| 52 |
+
{%- if message.tool_calls %}
|
| 53 |
+
{%- for tool_call in message.tool_calls %}
|
| 54 |
+
{%- if (loop.first and content) or (not loop.first) %}
|
| 55 |
+
{{- '\n' }}
|
| 56 |
+
{%- endif %}
|
| 57 |
+
{%- if tool_call.function %}
|
| 58 |
+
{%- set tool_call = tool_call.function %}
|
| 59 |
+
{%- endif %}
|
| 60 |
+
{{- '<tool_call>\n{"name": "' }}
|
| 61 |
+
{{- tool_call.name }}
|
| 62 |
+
{{- '", "arguments": ' }}
|
| 63 |
+
{%- if tool_call.arguments is string %}
|
| 64 |
+
{{- tool_call.arguments }}
|
| 65 |
+
{%- else %}
|
| 66 |
+
{{- tool_call.arguments | tojson }}
|
| 67 |
+
{%- endif %}
|
| 68 |
+
{{- '}\n</tool_call>' }}
|
| 69 |
+
{%- endfor %}
|
| 70 |
+
{%- endif %}
|
| 71 |
+
{{- '<|im_end|>\n' }}
|
| 72 |
+
{%- elif message.role == "tool" %}
|
| 73 |
+
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
|
| 74 |
+
{{- '<|im_start|>user' }}
|
| 75 |
+
{%- endif %}
|
| 76 |
+
{{- '\n<tool_response>\n' }}
|
| 77 |
+
{{- content }}
|
| 78 |
+
{{- '\n</tool_response>' }}
|
| 79 |
+
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
|
| 80 |
+
{{- '<|im_end|>\n' }}
|
| 81 |
+
{%- endif %}
|
| 82 |
+
{%- endif %}
|
| 83 |
+
{%- endfor %}
|
| 84 |
+
{%- if add_generation_prompt %}
|
| 85 |
+
{{- '<|im_start|>assistant\n' }}
|
| 86 |
+
{%- if enable_thinking is defined and enable_thinking is false %}
|
| 87 |
+
{{- '<think>\n\n</think>\n\n' }}
|
| 88 |
+
{%- endif %}
|
| 89 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"MoeloopForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "hf.MoeloopConfig",
|
| 7 |
+
"AutoModelForCausalLM": "hf.MoeloopForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"bos_token_id": 151645,
|
| 10 |
+
"dtype": "float32",
|
| 11 |
+
"eos_token_id": 151645,
|
| 12 |
+
"hidden_size": 1056,
|
| 13 |
+
"labels_objective": "terminal_ce",
|
| 14 |
+
"max_position_embeddings": 4096,
|
| 15 |
+
"model_config": {
|
| 16 |
+
"always_on_hidden_dim": 0,
|
| 17 |
+
"attention_per_visit": false,
|
| 18 |
+
"core": {
|
| 19 |
+
"always_on_hidden_dim": null,
|
| 20 |
+
"hidden_dim": null,
|
| 21 |
+
"num_experts": null,
|
| 22 |
+
"residual_scale": 0.5,
|
| 23 |
+
"top_k": null
|
| 24 |
+
},
|
| 25 |
+
"dim": 1056,
|
| 26 |
+
"exit_distribution": false,
|
| 27 |
+
"hidden_dim": 384,
|
| 28 |
+
"init_std": 0.02,
|
| 29 |
+
"initial_state": "input",
|
| 30 |
+
"injection_decay": 1.0,
|
| 31 |
+
"injection_dt": 0.8047189562170501,
|
| 32 |
+
"injection_eps": 1e-06,
|
| 33 |
+
"injection_scale": 1.0,
|
| 34 |
+
"input_injection": "none",
|
| 35 |
+
"latent_init_std": 0.6324555320336759,
|
| 36 |
+
"latent_truncation": 3.0,
|
| 37 |
+
"lora_attention_rank": 0,
|
| 38 |
+
"lora_ffn_rank": 0,
|
| 39 |
+
"max_seq_len": 4096,
|
| 40 |
+
"memory_beta": 0.5,
|
| 41 |
+
"memory_scale": 0.5,
|
| 42 |
+
"norm_per_visit": false,
|
| 43 |
+
"num_cells": 6,
|
| 44 |
+
"num_experts": 88,
|
| 45 |
+
"num_heads": 12,
|
| 46 |
+
"num_kv_heads": 1,
|
| 47 |
+
"num_visits": 2,
|
| 48 |
+
"order": "stack",
|
| 49 |
+
"prefix": null,
|
| 50 |
+
"prefix_cells": 3,
|
| 51 |
+
"qk_norm": false,
|
| 52 |
+
"residual_scale": 1.0,
|
| 53 |
+
"rms_eps": 1e-06,
|
| 54 |
+
"rope_theta": 10000.0,
|
| 55 |
+
"router_per_visit": false,
|
| 56 |
+
"schema_version": 4,
|
| 57 |
+
"state_update": "residual",
|
| 58 |
+
"suffix": null,
|
| 59 |
+
"suffix_cells": 3,
|
| 60 |
+
"top_k": 8,
|
| 61 |
+
"visit_capacity": null,
|
| 62 |
+
"vocab_size": 151669
|
| 63 |
+
},
|
| 64 |
+
"model_type": "moeloop",
|
| 65 |
+
"num_attention_heads": 12,
|
| 66 |
+
"num_hidden_layers": 18,
|
| 67 |
+
"num_key_value_heads": 1,
|
| 68 |
+
"pad_token_id": 151645,
|
| 69 |
+
"tie_word_embeddings": false,
|
| 70 |
+
"transformers_version": "5.20.2",
|
| 71 |
+
"use_cache": true,
|
| 72 |
+
"vocab_size": 151669
|
| 73 |
+
}
|
config.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model and training configurations as plain dataclasses.
|
| 2 |
+
|
| 3 |
+
This module imports no torch, so recipe specs, cost estimates and comparisons
|
| 4 |
+
load and run without it. ``moeloop.model`` and ``moeloop.training`` re-export
|
| 5 |
+
these classes under their original names.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import math
|
| 12 |
+
import random
|
| 13 |
+
from dataclasses import asdict, dataclass, fields, replace
|
| 14 |
+
from typing import Any, Literal, Mapping
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True)
|
| 18 |
+
class RegionConfig:
|
| 19 |
+
"""Local geometry, residual scale and output-projection scales; None inherits the model default.
|
| 20 |
+
|
| 21 |
+
Regions keep a common residual width and attention geometry. Reusing an
|
| 22 |
+
override never shares modules or parameters between physical cells. The
|
| 23 |
+
resolved :class:`ModelConfig` validates these values together.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
hidden_dim: int | None = None
|
| 27 |
+
num_experts: int | None = None
|
| 28 |
+
top_k: int | None = None
|
| 29 |
+
always_on_hidden_dim: int | None = None
|
| 30 |
+
residual_scale: float | None = None
|
| 31 |
+
output_lr_scale: float | None = None
|
| 32 |
+
output_init_scale: float | None = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# Written by to_dict only when on, so records from before these fields existed keep their bytes.
|
| 36 |
+
WRITTEN_WHEN_ON = ("sandwich_norm", "visit_final_norm", "qk_bias", "residual_norm", "core_final_norm")
|
| 37 |
+
# Written by to_dict only when not 1 (in a region: when set), for the same reason.
|
| 38 |
+
WRITTEN_WHEN_SCALED = ("output_lr_scale", "output_init_scale")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass(frozen=True)
|
| 42 |
+
class ModelConfig:
|
| 43 |
+
vocab_size: int = 32000
|
| 44 |
+
dim: int = 512
|
| 45 |
+
hidden_dim: int = 1536
|
| 46 |
+
num_heads: int = 8
|
| 47 |
+
num_kv_heads: int | None = None
|
| 48 |
+
num_experts: int = 8
|
| 49 |
+
top_k: int = 2
|
| 50 |
+
num_cells: int = 2
|
| 51 |
+
num_visits: int = 2
|
| 52 |
+
visit_capacity: int | None = None
|
| 53 |
+
prefix_cells: int = 0
|
| 54 |
+
suffix_cells: int = 0
|
| 55 |
+
order: Literal["stack", "layer"] = "stack"
|
| 56 |
+
attention_per_visit: bool = False
|
| 57 |
+
router_per_visit: bool = False
|
| 58 |
+
norm_per_visit: bool = False
|
| 59 |
+
# Per-visit LoRA on the shared core (Relaxed Recursive Transformers); rank 0 is none. See Cell.
|
| 60 |
+
lora_attention_rank: int = 0
|
| 61 |
+
lora_ffn_rank: int = 0
|
| 62 |
+
residual_scale: float = 1.0
|
| 63 |
+
# One residual scale per core visit (LatentLoop's alpha_v): core visit v scales its attention and FFN
|
| 64 |
+
# branches by visit_residual_scales[v] in place of the core residual_scale, which must stay 1. Empty: none.
|
| 65 |
+
visit_residual_scales: tuple[float, ...] = ()
|
| 66 |
+
# Only the core cells' branch output projections use these (CORE_OUTPUT_PATTERN in model.py):
|
| 67 |
+
# attention out_proj and the down projection w2 of routed experts and of the dense or always-on
|
| 68 |
+
# FFN. The LR scale multiplies their learning rate and divides their weight decay, so
|
| 69 |
+
# lr * weight_decay per step is kept (moeloop.optim); the init scale multiplies their init std
|
| 70 |
+
# (LoopedLM.initialize_weights). Under Adam or Muon, core residual_scale a is the same training
|
| 71 |
+
# as residual 1 with both scales a, up to Adam's eps and global gradient-norm clipping, when
|
| 72 |
+
# sandwich_norm is off and there is no LoRA (an output norm or LoRA B is not scaled by these).
|
| 73 |
+
output_lr_scale: float = 1.0
|
| 74 |
+
output_init_scale: float = 1.0
|
| 75 |
+
rms_eps: float = 1e-6
|
| 76 |
+
rope_theta: float = 10000.0
|
| 77 |
+
max_seq_len: int = 4096
|
| 78 |
+
qk_norm: bool = False
|
| 79 |
+
# A bias on the query and key projections, zero at initialization. See Attention.
|
| 80 |
+
qk_bias: bool = False
|
| 81 |
+
# Sandwich norm: an RMSNorm also on each attention/FFN output before its residual add. See Cell.
|
| 82 |
+
sandwich_norm: bool = False
|
| 83 |
+
# Residual norm: an RMSNorm also on the residual stream after each residual add. See Cell.
|
| 84 |
+
residual_norm: bool = False
|
| 85 |
+
# The final norm also closes every core visit: visit v > 0 starts from final_norm(state). See LoopedLM.forward.
|
| 86 |
+
visit_final_norm: bool = False
|
| 87 |
+
# The final norm also closes the core: readouts apply it before the suffix cells too. See LoopedLM.readout.
|
| 88 |
+
core_final_norm: bool = False
|
| 89 |
+
always_on_hidden_dim: int = 0
|
| 90 |
+
input_injection: Literal["none", "add", "linear", "diag_decay", "orthogonal"] = "none"
|
| 91 |
+
injection_scale: float = 1.0
|
| 92 |
+
# diag_decay/orthogonal only: initial dt and a, and the OrthoInj eps; see InputAdapter.
|
| 93 |
+
injection_dt: float = 0.5 * math.log(5)
|
| 94 |
+
injection_decay: float = 1.0
|
| 95 |
+
injection_eps: float = 1e-6
|
| 96 |
+
initial_state: Literal["input", "zero", "random"] = "input"
|
| 97 |
+
latent_init_std: float = math.sqrt(2 / 5)
|
| 98 |
+
latent_truncation: float = 3.0
|
| 99 |
+
state_update: Literal["residual", "ema"] = "residual"
|
| 100 |
+
memory_scale: float = 0.5
|
| 101 |
+
memory_beta: float = 0.5
|
| 102 |
+
exit_distribution: bool = False
|
| 103 |
+
init_std: float = 0.02
|
| 104 |
+
schema_version: int = 4
|
| 105 |
+
prefix: RegionConfig | None = None
|
| 106 |
+
core: RegionConfig | None = None
|
| 107 |
+
suffix: RegionConfig | None = None
|
| 108 |
+
|
| 109 |
+
def __post_init__(self) -> None:
|
| 110 |
+
positive = ("vocab_size", "dim", "hidden_dim", "num_heads", "num_cells", "num_visits", "max_seq_len")
|
| 111 |
+
nonnegative = ("num_experts", "prefix_cells", "suffix_cells", "always_on_hidden_dim",
|
| 112 |
+
"lora_attention_rank", "lora_ffn_rank")
|
| 113 |
+
for name in positive + nonnegative:
|
| 114 |
+
value = getattr(self, name)
|
| 115 |
+
if type(value) is not int or value < (1 if name in positive else 0):
|
| 116 |
+
raise ValueError(f"{name} must be {'positive' if name in positive else 'nonnegative'} integer")
|
| 117 |
+
for name in ("attention_per_visit", "router_per_visit", "norm_per_visit", "qk_norm", "exit_distribution",
|
| 118 |
+
"sandwich_norm", "visit_final_norm", "qk_bias", "residual_norm", "core_final_norm"):
|
| 119 |
+
if type(getattr(self, name)) is not bool:
|
| 120 |
+
raise ValueError(f"{name} must be bool")
|
| 121 |
+
kv = self.num_heads if self.num_kv_heads is None else self.num_kv_heads
|
| 122 |
+
if type(kv) is not int or kv < 1 or self.num_heads % kv:
|
| 123 |
+
raise ValueError("num_kv_heads must be positive and divide num_heads")
|
| 124 |
+
object.__setattr__(self, "num_kv_heads", kv)
|
| 125 |
+
if self.dim % self.num_heads or (self.dim // self.num_heads) % 2:
|
| 126 |
+
raise ValueError("dim / num_heads must be a positive even head dimension")
|
| 127 |
+
if type(self.top_k) is not int or self.top_k < 1 or (self.num_experts and self.top_k > self.num_experts):
|
| 128 |
+
raise ValueError("top_k must be positive and no larger than num_experts for sparse models")
|
| 129 |
+
if self.num_experts == 0 and (self.router_per_visit or self.always_on_hidden_dim):
|
| 130 |
+
raise ValueError("dense cells have no router or separate always-on sparse branch")
|
| 131 |
+
if self.order not in ("stack", "layer") or self.initial_state not in ("input", "zero", "random"):
|
| 132 |
+
raise ValueError("unknown order or initial_state")
|
| 133 |
+
if self.state_update not in ("residual", "ema"):
|
| 134 |
+
raise ValueError("unknown state_update")
|
| 135 |
+
if self.state_update == "ema" and (self.order != "stack" or self.input_injection != "none"
|
| 136 |
+
or self.initial_state != "input" or self.norm_per_visit):
|
| 137 |
+
raise ValueError("EMA state uses stack order, input initial state and shared norms without input adapter")
|
| 138 |
+
if self.state_update == "ema" and (self.lora_attention_rank or self.lora_ffn_rank):
|
| 139 |
+
raise ValueError("per-visit LoRA is defined for the residual cell, not the EMA memory cell")
|
| 140 |
+
if self.state_update == "ema" and self.num_experts and not self.router_per_visit:
|
| 141 |
+
raise ValueError("EMA state requires an independently owned router per visit")
|
| 142 |
+
if self.state_update == "ema" and self.sandwich_norm:
|
| 143 |
+
raise ValueError("sandwich norm is defined for the residual cell, not the EMA memory cell")
|
| 144 |
+
if self.state_update == "ema" and self.residual_norm:
|
| 145 |
+
raise ValueError("residual norm is defined for the residual cell, not the EMA memory cell")
|
| 146 |
+
if self.visit_final_norm and self.order != "stack":
|
| 147 |
+
raise ValueError("visit_final_norm closes complete stack visits")
|
| 148 |
+
if self.exit_distribution and self.order != "stack":
|
| 149 |
+
raise ValueError("exit distributions require complete stack visits")
|
| 150 |
+
if self.input_injection not in ("none", "add", "linear", "diag_decay", "orthogonal"):
|
| 151 |
+
raise ValueError("input_injection must be none, add, linear, diag_decay or orthogonal")
|
| 152 |
+
if self.order == "layer" and self.input_injection != "none":
|
| 153 |
+
raise ValueError("stage input injection is defined only for stack order")
|
| 154 |
+
for name in ("residual_scale", "output_lr_scale", "output_init_scale", "rms_eps", "rope_theta",
|
| 155 |
+
"injection_scale", "injection_dt", "injection_decay", "injection_eps", "init_std",
|
| 156 |
+
"latent_init_std", "latent_truncation", "memory_scale", "memory_beta"):
|
| 157 |
+
value = getattr(self, name)
|
| 158 |
+
if type(value) not in (float, int) or not math.isfinite(value):
|
| 159 |
+
raise ValueError(f"{name} must be finite")
|
| 160 |
+
if min(self.rms_eps, self.rope_theta, self.init_std, self.output_lr_scale, self.output_init_scale) <= 0:
|
| 161 |
+
raise ValueError("rms_eps, rope_theta, init_std and the output scales must be positive")
|
| 162 |
+
for name in ("injection_dt", "injection_decay", "injection_eps"):
|
| 163 |
+
if getattr(self, name) <= 0:
|
| 164 |
+
raise ValueError(f"{name} must be positive")
|
| 165 |
+
if self.input_injection in ("diag_decay", "orthogonal") and self.injection_scale != 1:
|
| 166 |
+
raise ValueError("injection_scale applies only to add and linear injection")
|
| 167 |
+
if min(self.latent_init_std, self.latent_truncation) <= 0 or self.memory_scale < 0 or not 0 <= self.memory_beta < 1:
|
| 168 |
+
raise ValueError("invalid latent initialization or EMA coefficients")
|
| 169 |
+
if type(self.schema_version) is not int or self.schema_version not in (1, 2, 3, 4):
|
| 170 |
+
raise ValueError(f"unsupported model schema version: {self.schema_version}")
|
| 171 |
+
if self.schema_version == 1 and any(getattr(self, region) is not None for region in ("prefix", "core", "suffix")):
|
| 172 |
+
raise ValueError("model schema version 1 does not support region overrides; use schema version 2")
|
| 173 |
+
if self.schema_version < 4 and self.input_injection in ("diag_decay", "orthogonal"):
|
| 174 |
+
raise ValueError(f"model schema version {self.schema_version} has no {self.input_injection} injection; use schema version 4")
|
| 175 |
+
# Schemas 1-3 acquire only inactive defaults for the new state and
|
| 176 |
+
# injection paths. Existing state-dict names and physical parameter
|
| 177 |
+
# ownership are unchanged.
|
| 178 |
+
object.__setattr__(self, "schema_version", 4)
|
| 179 |
+
if self.independent_visits:
|
| 180 |
+
capacity = self.num_visits if self.visit_capacity is None else self.visit_capacity
|
| 181 |
+
if type(capacity) is not int or capacity < self.num_visits:
|
| 182 |
+
raise ValueError("visit_capacity must cover num_visits for independent owners")
|
| 183 |
+
object.__setattr__(self, "visit_capacity", capacity)
|
| 184 |
+
elif self.visit_capacity is not None:
|
| 185 |
+
raise ValueError("fully shared owners have no visit_capacity; use num_visits for default depth")
|
| 186 |
+
for region in ("prefix", "core", "suffix"):
|
| 187 |
+
override = getattr(self, region)
|
| 188 |
+
if override is not None:
|
| 189 |
+
if not isinstance(override, RegionConfig):
|
| 190 |
+
raise ValueError(f"{region} region must be RegionConfig or None")
|
| 191 |
+
try:
|
| 192 |
+
self.region_config(region)
|
| 193 |
+
except ValueError as error:
|
| 194 |
+
raise ValueError(f"invalid {region} region configuration: {error}") from error
|
| 195 |
+
for region in ("prefix", "suffix"):
|
| 196 |
+
override = getattr(self, region)
|
| 197 |
+
if override is not None and (override.output_lr_scale, override.output_init_scale) != (None, None):
|
| 198 |
+
raise ValueError("output_lr_scale and output_init_scale apply only to the core cells")
|
| 199 |
+
core_scale = self.residual_scale if self.core is None or self.core.residual_scale is None else self.core.residual_scale
|
| 200 |
+
scales = self.visit_residual_scales
|
| 201 |
+
if not isinstance(scales, (tuple, list)) or any(
|
| 202 |
+
type(value) not in (float, int) or not math.isfinite(value) for value in scales):
|
| 203 |
+
raise ValueError("visit_residual_scales must be a sequence of finite numbers")
|
| 204 |
+
object.__setattr__(self, "visit_residual_scales", tuple(scales))
|
| 205 |
+
if scales and (len(scales) != self.num_visits or core_scale != 1 or self.state_update != "residual"):
|
| 206 |
+
raise ValueError("visit_residual_scales needs one scale per visit, core residual_scale 1 and the "
|
| 207 |
+
"residual state update")
|
| 208 |
+
if self.state_update == "ema" and core_scale != 1:
|
| 209 |
+
raise ValueError("EMA core residual_scale must be 1; memory_scale defines its stabilization")
|
| 210 |
+
if self.lora_ffn_rank:
|
| 211 |
+
core = self if self.core is None else self.region_config("core")
|
| 212 |
+
if core.num_experts and not core.always_on_hidden_dim:
|
| 213 |
+
raise ValueError("FFN LoRA needs a dense or always-on core FFN; routed experts take no LoRA")
|
| 214 |
+
|
| 215 |
+
@property
|
| 216 |
+
def independent_visits(self) -> bool:
|
| 217 |
+
return (self.attention_per_visit or self.router_per_visit or self.norm_per_visit
|
| 218 |
+
or self.lora_attention_rank > 0 or self.lora_ffn_rank > 0)
|
| 219 |
+
|
| 220 |
+
def region_config(self, region: Literal["prefix", "core", "suffix"]) -> "ModelConfig":
|
| 221 |
+
"""Resolve the actual config passed to cells and native factories.
|
| 222 |
+
|
| 223 |
+
LoRA relaxes the shared core only: prefix and suffix cells own their
|
| 224 |
+
matrices, so their configs carry no LoRA ranks.
|
| 225 |
+
"""
|
| 226 |
+
if region not in ("prefix", "core", "suffix"):
|
| 227 |
+
raise ValueError(f"unknown model region: {region}")
|
| 228 |
+
override = getattr(self, region)
|
| 229 |
+
values = {} if override is None else {
|
| 230 |
+
field.name: getattr(override, field.name) for field in fields(RegionConfig)
|
| 231 |
+
if getattr(override, field.name) is not None
|
| 232 |
+
}
|
| 233 |
+
if self.state_update == "ema" and region != "core":
|
| 234 |
+
values["state_update"] = "residual"
|
| 235 |
+
if region != "core":
|
| 236 |
+
values.update(lora_attention_rank=0, lora_ffn_rank=0, visit_residual_scales=())
|
| 237 |
+
if not (self.attention_per_visit or self.router_per_visit or self.norm_per_visit):
|
| 238 |
+
values["visit_capacity"] = None # LoRA was the only per-visit owner.
|
| 239 |
+
return replace(self, **values, prefix=None, core=None, suffix=None)
|
| 240 |
+
|
| 241 |
+
def to_dict(self) -> dict[str, Any]:
|
| 242 |
+
value = asdict(self)
|
| 243 |
+
for name in WRITTEN_WHEN_ON:
|
| 244 |
+
if not value[name]:
|
| 245 |
+
del value[name]
|
| 246 |
+
for name in WRITTEN_WHEN_SCALED:
|
| 247 |
+
if value[name] == 1:
|
| 248 |
+
del value[name]
|
| 249 |
+
for region in ("prefix", "core", "suffix"):
|
| 250 |
+
if value[region] is not None and value[region][name] is None:
|
| 251 |
+
del value[region][name]
|
| 252 |
+
# Written only when set, for the same reason; as a JSON array, as RecipeSpec writes tuples.
|
| 253 |
+
if self.visit_residual_scales:
|
| 254 |
+
value["visit_residual_scales"] = list(self.visit_residual_scales)
|
| 255 |
+
else:
|
| 256 |
+
del value["visit_residual_scales"]
|
| 257 |
+
return value
|
| 258 |
+
|
| 259 |
+
@classmethod
|
| 260 |
+
def from_dict(cls, values: Mapping[str, Any]) -> "ModelConfig":
|
| 261 |
+
unknown = set(values) - {field.name for field in fields(cls)}
|
| 262 |
+
if unknown:
|
| 263 |
+
raise ValueError(f"unknown model configuration fields: {sorted(unknown)}")
|
| 264 |
+
values = dict(values)
|
| 265 |
+
for region in ("prefix", "core", "suffix"):
|
| 266 |
+
override = values.get(region)
|
| 267 |
+
if override is not None and not isinstance(override, RegionConfig):
|
| 268 |
+
if not isinstance(override, Mapping):
|
| 269 |
+
raise ValueError(f"{region} region must be a configuration mapping")
|
| 270 |
+
unknown = set(override) - {field.name for field in fields(RegionConfig)}
|
| 271 |
+
if unknown:
|
| 272 |
+
raise ValueError(f"unknown {region} region configuration fields: {sorted(unknown)}")
|
| 273 |
+
values[region] = RegionConfig(**dict(override))
|
| 274 |
+
return cls(**values)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@dataclass(frozen=True)
|
| 278 |
+
class TrainingRecipe:
|
| 279 |
+
"""Explicit fixed/update/microbatch depth policies, outside model replay."""
|
| 280 |
+
|
| 281 |
+
num_visits: int = 1
|
| 282 |
+
sampled_visits: tuple[int, ...] = ()
|
| 283 |
+
grad_visits: int | None = None
|
| 284 |
+
balance_coeff: float = 0.01
|
| 285 |
+
z_loss_coeff: float = 0.0
|
| 286 |
+
depth_seed: int = 0
|
| 287 |
+
depth_rule: str = "uniform_update_v1"
|
| 288 |
+
# Recorded by archived recipes; the one implemented rule (titan.py) averages over local microbatch calls.
|
| 289 |
+
aux_reduction: str = "local_micro_call_mean"
|
| 290 |
+
depth_mean: float = 4.0
|
| 291 |
+
depth_log_std: float = 0.5
|
| 292 |
+
objective: str = "terminal_ce"
|
| 293 |
+
entropy_coeff: float = 0.0
|
| 294 |
+
|
| 295 |
+
def __post_init__(self) -> None:
|
| 296 |
+
for name in ("num_visits", "depth_seed"):
|
| 297 |
+
if type(getattr(self, name)) is not int:
|
| 298 |
+
raise ValueError(f"{name} must be an integer")
|
| 299 |
+
for name in ("balance_coeff", "z_loss_coeff", "depth_mean", "depth_log_std", "entropy_coeff"):
|
| 300 |
+
if type(getattr(self, name)) not in (float, int):
|
| 301 |
+
raise ValueError(f"{name} must be a number")
|
| 302 |
+
depths = self.sampled_visits or (self.num_visits,)
|
| 303 |
+
if self.num_visits < 1 or any(type(d) is not int or d < 1 for d in depths):
|
| 304 |
+
raise ValueError("num_visits and sampled_visits must be positive integers")
|
| 305 |
+
if len(set(depths)) != len(depths):
|
| 306 |
+
raise ValueError("sampled_visits must contain distinct depths")
|
| 307 |
+
sampled_micro = self.depth_rule == "poisson_lognormal_micro_v1"
|
| 308 |
+
if self.grad_visits is not None and (type(self.grad_visits) is not int or self.grad_visits < 1
|
| 309 |
+
or (not sampled_micro and self.grad_visits > min(depths))):
|
| 310 |
+
raise ValueError("grad_visits must be positive and no larger than fixed/finite training depths")
|
| 311 |
+
for name in ("balance_coeff", "z_loss_coeff", "entropy_coeff"):
|
| 312 |
+
value = getattr(self, name)
|
| 313 |
+
if not math.isfinite(value) or value < 0:
|
| 314 |
+
raise ValueError(f"{name} must be finite and nonnegative")
|
| 315 |
+
if self.depth_rule not in ("uniform_update_v1", "poisson_lognormal_micro_v1"):
|
| 316 |
+
raise ValueError("unsupported depth sampling rule")
|
| 317 |
+
if sampled_micro and self.sampled_visits:
|
| 318 |
+
raise ValueError("Poisson-lognormal depths cannot also specify sampled_visits")
|
| 319 |
+
if not math.isfinite(self.depth_mean) or self.depth_mean <= 1 or not math.isfinite(self.depth_log_std) or self.depth_log_std < 0:
|
| 320 |
+
raise ValueError("depth_mean must exceed one and depth_log_std must be nonnegative")
|
| 321 |
+
if self.objective not in ("terminal_ce", "expected_ce"):
|
| 322 |
+
raise ValueError("unknown training objective")
|
| 323 |
+
if self.aux_reduction != "local_micro_call_mean":
|
| 324 |
+
raise ValueError("unsupported auxiliary reduction")
|
| 325 |
+
|
| 326 |
+
def depth_at(self, completed_updates: int, microbatch: int = 0) -> int:
|
| 327 |
+
"""Training depth of one microbatch of an update.
|
| 328 |
+
|
| 329 |
+
``uniform_update_v1`` draws once per update, so its depth sequence does
|
| 330 |
+
not depend on the number of ranks. ``poisson_lognormal_micro_v1``
|
| 331 |
+
draws per microbatch. FSDP needs one depth per accumulation step on
|
| 332 |
+
every rank, so the trainer uses rank 0's microbatch index; the depth
|
| 333 |
+
sequence then depends on the accumulation steps, global batch /
|
| 334 |
+
(local batch x ranks).
|
| 335 |
+
"""
|
| 336 |
+
if completed_updates < 0:
|
| 337 |
+
raise ValueError("completed_updates cannot be negative")
|
| 338 |
+
if self.depth_rule == "poisson_lognormal_micro_v1":
|
| 339 |
+
from .latent import sampled_depth
|
| 340 |
+
return sampled_depth(seed=self.depth_seed, completed_updates=completed_updates,
|
| 341 |
+
microbatch=microbatch, mean=self.depth_mean, log_std=self.depth_log_std)
|
| 342 |
+
if not self.sampled_visits:
|
| 343 |
+
return self.num_visits
|
| 344 |
+
key = f"{self.depth_rule}:{self.depth_seed}:{completed_updates}".encode()
|
| 345 |
+
seed = int.from_bytes(hashlib.sha256(key).digest(), "big")
|
| 346 |
+
return random.Random(seed).choice(self.sampled_visits)
|
| 347 |
+
|
| 348 |
+
def validate_model(self, config: Any) -> None:
|
| 349 |
+
depths = self.sampled_visits or (self.num_visits,)
|
| 350 |
+
independent = config.independent_visits
|
| 351 |
+
stochastic = bool(self.sampled_visits) or self.depth_rule == "poisson_lognormal_micro_v1"
|
| 352 |
+
if independent and (stochastic or self.grad_visits is not None):
|
| 353 |
+
raise ValueError("per-visit owners support fixed depth and full BPTT in v1")
|
| 354 |
+
if independent and max(depths) > config.visit_capacity:
|
| 355 |
+
raise ValueError("training depth exceeds per-visit owner capacity")
|
| 356 |
+
if independent and self.num_visits != config.visit_capacity:
|
| 357 |
+
raise ValueError("fixed training depth must use all allocated per-visit owners")
|
| 358 |
+
if self.grad_visits is not None and config.order != "stack":
|
| 359 |
+
raise ValueError("grad_visits means complete stack visits; layer order uses full BPTT")
|
| 360 |
+
if config.state_update == "ema" and (stochastic or self.grad_visits is not None):
|
| 361 |
+
raise ValueError("EMA state currently supports fixed depth and full BPTT")
|
| 362 |
+
if (self.objective == "expected_ce") != config.exit_distribution:
|
| 363 |
+
raise ValueError("expected CE and model exit_distribution must be selected together")
|
| 364 |
+
if self.objective == "expected_ce" and (stochastic or self.grad_visits is not None):
|
| 365 |
+
raise ValueError("expected CE requires fixed depth and full BPTT")
|
eval-test.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention": "document_causal_block_local",
|
| 3 |
+
"batch_size": 4,
|
| 4 |
+
"batches": 611,
|
| 5 |
+
"bpb": 0.9905439020553065,
|
| 6 |
+
"bpb_unavailable": null,
|
| 7 |
+
"byte_table_sha256": "b504f8826a5ed6fc6a83ceb55c1c96f6c757ada30c6e38c46995ae2e5b74e17c",
|
| 8 |
+
"ce": 3.0450502045402303,
|
| 9 |
+
"ce_sum": 30480614.546875,
|
| 10 |
+
"ce_sum_text": 30465162.98024187,
|
| 11 |
+
"complete_split": true,
|
| 12 |
+
"input_tokens": 10009889,
|
| 13 |
+
"label_bytes": 44371521,
|
| 14 |
+
"label_contract": "already_aligned_document_internal_next_token",
|
| 15 |
+
"manifest_fingerprint": "e67a956d2fe51dd1784505a6f58d7790f397a09624330700c0ebaffcd344f152",
|
| 16 |
+
"max_batches": null,
|
| 17 |
+
"num_visits": 2,
|
| 18 |
+
"perplexity": 21.01108602831457,
|
| 19 |
+
"seq_len": 4096,
|
| 20 |
+
"source_counts": {
|
| 21 |
+
"public": {
|
| 22 |
+
"blocks": 2444,
|
| 23 |
+
"documents": 8212,
|
| 24 |
+
"input_tokens": 10009889,
|
| 25 |
+
"label_tokens": 10009889
|
| 26 |
+
}
|
| 27 |
+
},
|
| 28 |
+
"split": "test",
|
| 29 |
+
"tokenizer": {
|
| 30 |
+
"id": "Qwen/Qwen3-30B-A3B",
|
| 31 |
+
"revision": "ae659febe817e4b3ebd7355f47792725801204c9",
|
| 32 |
+
"vocab_size": 151669
|
| 33 |
+
},
|
| 34 |
+
"valid_tokens": 10009889
|
| 35 |
+
}
|
eval-validation.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention": "document_causal_block_local",
|
| 3 |
+
"batch_size": 4,
|
| 4 |
+
"batches": 611,
|
| 5 |
+
"bpb": 0.9922113684592596,
|
| 6 |
+
"bpb_unavailable": null,
|
| 7 |
+
"byte_table_sha256": "b504f8826a5ed6fc6a83ceb55c1c96f6c757ada30c6e38c46995ae2e5b74e17c",
|
| 8 |
+
"ce": 3.0513609905565886,
|
| 9 |
+
"ce_sum": 30518177.79296875,
|
| 10 |
+
"ce_sum_text": 30502634.826961704,
|
| 11 |
+
"complete_split": true,
|
| 12 |
+
"input_tokens": 10001497,
|
| 13 |
+
"label_bytes": 44351437,
|
| 14 |
+
"label_contract": "already_aligned_document_internal_next_token",
|
| 15 |
+
"manifest_fingerprint": "e67a956d2fe51dd1784505a6f58d7790f397a09624330700c0ebaffcd344f152",
|
| 16 |
+
"max_batches": null,
|
| 17 |
+
"num_visits": 2,
|
| 18 |
+
"perplexity": 21.1441017717002,
|
| 19 |
+
"seq_len": 4096,
|
| 20 |
+
"source_counts": {
|
| 21 |
+
"public": {
|
| 22 |
+
"blocks": 2442,
|
| 23 |
+
"documents": 8167,
|
| 24 |
+
"input_tokens": 10001497,
|
| 25 |
+
"label_tokens": 10001497
|
| 26 |
+
}
|
| 27 |
+
},
|
| 28 |
+
"split": "validation",
|
| 29 |
+
"tokenizer": {
|
| 30 |
+
"id": "Qwen/Qwen3-30B-A3B",
|
| 31 |
+
"revision": "ae659febe817e4b3ebd7355f47792725801204c9",
|
| 32 |
+
"vocab_size": 151669
|
| 33 |
+
},
|
| 34 |
+
"valid_tokens": 10001497
|
| 35 |
+
}
|
export_provenance.json
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"artifact_sha256": {
|
| 3 |
+
"LICENSE": "a0c4279f95ed7ca7a54c3477e4de0ab0dff2b58c09d42b0bacbff90d46f0d34f",
|
| 4 |
+
"cache.py": "783309daf95ee202a3cf8fdff98c2b29dca63a8c9420a2765b2f13a752f57158",
|
| 5 |
+
"chat_template.jinja": "a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8",
|
| 6 |
+
"config.json": "82938df077f7e9827e04e501ff656fe2a3957465785f1d316b4a9e784c707798",
|
| 7 |
+
"config.py": "90b82f090b6660531abc4162b83b447d65af3b607249a01c60164f1edded362d",
|
| 8 |
+
"generation_config.json": "051acf146b4142eeb0b8a3b618dacd024c6ac49fca1278efb22411e9f80b7111",
|
| 9 |
+
"hf.py": "4ad460cecd848b3fedb81f7677a393ce2e02c94a811afa0fc7f2b5198d9cc154",
|
| 10 |
+
"latent.py": "dc9df417ef6258635ed6e881ba10311ae3533233c642173d072bac91ee33c14c",
|
| 11 |
+
"memory.py": "841579b0be46e967d2026e70ce4423867af8d877d99e769f018b75517422af14",
|
| 12 |
+
"model.py": "db156d725ac81aee86dd9a19fae45e6558bf377505181813c5e188f0bab04706",
|
| 13 |
+
"model.safetensors": "4bbfd277973958d3779fa93e59209e94d8e158be167cd534ac1709637f02f824",
|
| 14 |
+
"moe.py": "77176d615438087bdda4fc5f357ff0b12f4ae82b676afa92edf22727b500cd87",
|
| 15 |
+
"tokenizer.json": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506",
|
| 16 |
+
"tokenizer_config.json": "abf803ee0d500a6496ea7cbb82ca1d0fb3efbdd917f2389d01003f222fe1a98b"
|
| 17 |
+
},
|
| 18 |
+
"checkpoint": {
|
| 19 |
+
"format": "torch_model_only",
|
| 20 |
+
"key_layout": "huggingface",
|
| 21 |
+
"name": "looptitan-p1-loop6x2-adamw.pt",
|
| 22 |
+
"sha256": "c4997a82a2e595940474100008d85579690814866680bbbaccf397d029d20267",
|
| 23 |
+
"weights": "model"
|
| 24 |
+
},
|
| 25 |
+
"format": "moeloop-hf-export",
|
| 26 |
+
"model_config": {
|
| 27 |
+
"always_on_hidden_dim": 0,
|
| 28 |
+
"attention_per_visit": false,
|
| 29 |
+
"core": {
|
| 30 |
+
"always_on_hidden_dim": null,
|
| 31 |
+
"hidden_dim": null,
|
| 32 |
+
"num_experts": null,
|
| 33 |
+
"residual_scale": 0.5,
|
| 34 |
+
"top_k": null
|
| 35 |
+
},
|
| 36 |
+
"dim": 1056,
|
| 37 |
+
"exit_distribution": false,
|
| 38 |
+
"hidden_dim": 384,
|
| 39 |
+
"init_std": 0.02,
|
| 40 |
+
"initial_state": "input",
|
| 41 |
+
"injection_decay": 1.0,
|
| 42 |
+
"injection_dt": 0.8047189562170501,
|
| 43 |
+
"injection_eps": 1e-06,
|
| 44 |
+
"injection_scale": 1.0,
|
| 45 |
+
"input_injection": "none",
|
| 46 |
+
"latent_init_std": 0.6324555320336759,
|
| 47 |
+
"latent_truncation": 3.0,
|
| 48 |
+
"lora_attention_rank": 0,
|
| 49 |
+
"lora_ffn_rank": 0,
|
| 50 |
+
"max_seq_len": 4096,
|
| 51 |
+
"memory_beta": 0.5,
|
| 52 |
+
"memory_scale": 0.5,
|
| 53 |
+
"norm_per_visit": false,
|
| 54 |
+
"num_cells": 6,
|
| 55 |
+
"num_experts": 88,
|
| 56 |
+
"num_heads": 12,
|
| 57 |
+
"num_kv_heads": 1,
|
| 58 |
+
"num_visits": 2,
|
| 59 |
+
"order": "stack",
|
| 60 |
+
"prefix": null,
|
| 61 |
+
"prefix_cells": 3,
|
| 62 |
+
"qk_norm": false,
|
| 63 |
+
"residual_scale": 1.0,
|
| 64 |
+
"rms_eps": 1e-06,
|
| 65 |
+
"rope_theta": 10000.0,
|
| 66 |
+
"router_per_visit": false,
|
| 67 |
+
"schema_version": 4,
|
| 68 |
+
"state_update": "residual",
|
| 69 |
+
"suffix": null,
|
| 70 |
+
"suffix_cells": 3,
|
| 71 |
+
"top_k": 8,
|
| 72 |
+
"visit_capacity": null,
|
| 73 |
+
"vocab_size": 151669
|
| 74 |
+
},
|
| 75 |
+
"tokenizer_source_files": {
|
| 76 |
+
"merges.txt": "8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5",
|
| 77 |
+
"special_tokens_map.json": "fcf9d46fd7374d49338e4a22c2b454eec94ca363744ff19611b1e33257ea6370",
|
| 78 |
+
"tokenizer.json": "a63080b4b30dc861fe1b0e420c53a241304dc81aff3d9bb315e6e33e2a1ab794",
|
| 79 |
+
"tokenizer_config.json": "e79b8ea9cc55f61ca0aa41ad9cd62102f806edb7f7e04edee9a496422ab0ce58",
|
| 80 |
+
"vocab.json": "ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910"
|
| 81 |
+
},
|
| 82 |
+
"version": 1,
|
| 83 |
+
"versions": {
|
| 84 |
+
"torch": "2.14.0",
|
| 85 |
+
"transformers": "5.20.2"
|
| 86 |
+
}
|
| 87 |
+
}
|
generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 151645,
|
| 4 |
+
"eos_token_id": 151645,
|
| 5 |
+
"output_attentions": false,
|
| 6 |
+
"output_hidden_states": false,
|
| 7 |
+
"pad_token_id": 151645,
|
| 8 |
+
"transformers_version": "5.20.2",
|
| 9 |
+
"use_cache": true
|
| 10 |
+
}
|
hf.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Portable Transformers delivery; the recurrent mathematics stays in model.py."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import replace
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from transformers import PretrainedConfig, PreTrainedModel
|
| 11 |
+
from transformers.cache_utils import Cache
|
| 12 |
+
from transformers.generation import GenerationMixin
|
| 13 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 14 |
+
|
| 15 |
+
from .cache import DecodeCache
|
| 16 |
+
from .model import ModelConfig, RecursiveLM
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MoeloopConfig(PretrainedConfig):
|
| 20 |
+
model_type = "moeloop"
|
| 21 |
+
|
| 22 |
+
def __init__(self, model_config: dict | None = None, **kwargs):
|
| 23 |
+
core = ModelConfig.from_dict(model_config or {})
|
| 24 |
+
use_cache = kwargs.pop("use_cache", core.state_update == "residual" and core.initial_state != "random")
|
| 25 |
+
if kwargs.pop("tie_word_embeddings", False):
|
| 26 |
+
raise ValueError("MoE-Loop v1 uses independent embedding and output weights")
|
| 27 |
+
if kwargs.pop("labels_objective", "terminal_ce") != "terminal_ce":
|
| 28 |
+
raise ValueError("HF labels evaluate terminal CE; expected-loss training uses the native training objective")
|
| 29 |
+
for key in ("vocab_size", "hidden_size", "num_attention_heads", "num_key_value_heads", "num_hidden_layers", "max_position_embeddings", "is_encoder_decoder"):
|
| 30 |
+
kwargs.pop(key, None)
|
| 31 |
+
super().__init__(tie_word_embeddings=False, is_encoder_decoder=False, **kwargs)
|
| 32 |
+
self.model_config = core.to_dict()
|
| 33 |
+
self.vocab_size = core.vocab_size
|
| 34 |
+
self.hidden_size = core.dim
|
| 35 |
+
self.num_attention_heads = core.num_heads
|
| 36 |
+
self.num_key_value_heads = core.num_kv_heads
|
| 37 |
+
self.num_hidden_layers = core.prefix_cells + core.num_cells * core.num_visits + core.suffix_cells
|
| 38 |
+
self.max_position_embeddings = core.max_seq_len
|
| 39 |
+
self.use_cache = use_cache
|
| 40 |
+
self.labels_objective = "terminal_ce"
|
| 41 |
+
|
| 42 |
+
def to_model_config(self) -> ModelConfig:
|
| 43 |
+
return ModelConfig.from_dict(self.model_config)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class MoeloopCache(Cache):
|
| 47 |
+
"""HF operations over one Torch-only logical KV store, without copying KV."""
|
| 48 |
+
|
| 49 |
+
def __init__(self, num_visits: int):
|
| 50 |
+
super().__init__(layers=[])
|
| 51 |
+
self.store = DecodeCache(num_visits)
|
| 52 |
+
|
| 53 |
+
def get_seq_length(self, layer_idx: int = 0) -> int:
|
| 54 |
+
return self.store.length
|
| 55 |
+
|
| 56 |
+
def get_mask_sizes(self, query_length: int, layer_idx: int = 0) -> tuple[int, int]:
|
| 57 |
+
return self.store.length + query_length, 0
|
| 58 |
+
|
| 59 |
+
def get_max_cache_shape(self, layer_idx: int = 0) -> int:
|
| 60 |
+
return -1
|
| 61 |
+
|
| 62 |
+
def reorder_cache(self, beam_idx: Tensor) -> None:
|
| 63 |
+
self.store.reorder(beam_idx)
|
| 64 |
+
|
| 65 |
+
def batch_select_indices(self, indices: Tensor) -> None:
|
| 66 |
+
self.store.reorder(indices)
|
| 67 |
+
|
| 68 |
+
def batch_repeat_interleave(self, repeats: int) -> None:
|
| 69 |
+
if self.store.valid_mask is not None:
|
| 70 |
+
indices = torch.arange(self.store.valid_mask.size(0), device=self.store.valid_mask.device)
|
| 71 |
+
self.store.reorder(indices.repeat_interleave(repeats))
|
| 72 |
+
|
| 73 |
+
def reset(self) -> None:
|
| 74 |
+
self.store.clear()
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def is_compileable(self) -> bool:
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def is_initialized(self) -> bool:
|
| 82 |
+
return self.store.length > 0
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def is_croppable(self) -> bool:
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class MoeloopForCausalLM(PreTrainedModel, GenerationMixin):
|
| 90 |
+
config_class = MoeloopConfig
|
| 91 |
+
base_model_prefix = "model"
|
| 92 |
+
main_input_name = "input_ids"
|
| 93 |
+
_no_split_modules = ["Cell", "MemoryCell"]
|
| 94 |
+
|
| 95 |
+
def __init__(self, config: MoeloopConfig):
|
| 96 |
+
super().__init__(config)
|
| 97 |
+
self.model = RecursiveLM(config.to_model_config())
|
| 98 |
+
self.post_init()
|
| 99 |
+
|
| 100 |
+
def _init_weights(self, module):
|
| 101 |
+
# RecursiveLM initializes its canonical owners once; HF must not reset them.
|
| 102 |
+
pass
|
| 103 |
+
|
| 104 |
+
def get_input_embeddings(self):
|
| 105 |
+
return self.model.embedding
|
| 106 |
+
|
| 107 |
+
def set_input_embeddings(self, value):
|
| 108 |
+
self.model.embedding = value
|
| 109 |
+
|
| 110 |
+
def get_output_embeddings(self):
|
| 111 |
+
return self.model.lm_head
|
| 112 |
+
|
| 113 |
+
def set_output_embeddings(self, value):
|
| 114 |
+
self.model.lm_head = value
|
| 115 |
+
|
| 116 |
+
def resize_token_embeddings(self, new_num_tokens=None, pad_to_multiple_of=None, mean_resizing=True):
|
| 117 |
+
old_size = self.model.embedding.weight.shape[0]
|
| 118 |
+
embeddings = super().resize_token_embeddings(
|
| 119 |
+
new_num_tokens, pad_to_multiple_of=pad_to_multiple_of, mean_resizing=mean_resizing)
|
| 120 |
+
size = embeddings.weight.shape[0]
|
| 121 |
+
if size > old_size and not mean_resizing:
|
| 122 |
+
# _init_weights skips already-initialized core owners. New rows
|
| 123 |
+
# still need the core's declared initialization rather than nn defaults.
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
for owner in (embeddings, self.model.lm_head):
|
| 126 |
+
torch.nn.init.normal_(owner.weight[old_size:], std=self.model.config.init_std)
|
| 127 |
+
self.model.config = replace(self.model.config, vocab_size=size)
|
| 128 |
+
self.config.model_config = self.model.config.to_dict()
|
| 129 |
+
return embeddings
|
| 130 |
+
|
| 131 |
+
@classmethod
|
| 132 |
+
def _supports_default_dynamic_cache(cls) -> bool:
|
| 133 |
+
return False
|
| 134 |
+
|
| 135 |
+
def _prepare_cache_for_generation(self, generation_config, model_kwargs, generation_mode, batch_size, max_cache_length):
|
| 136 |
+
if generation_config.cache_implementation is not None:
|
| 137 |
+
raise ValueError("MoE-Loop supports its exact logical cache; omit cache_implementation")
|
| 138 |
+
if model_kwargs.get("past_key_values") is not None and not isinstance(model_kwargs["past_key_values"], MoeloopCache):
|
| 139 |
+
raise TypeError("past_key_values must be a MoeloopCache")
|
| 140 |
+
if generation_config.use_cache and model_kwargs.get("past_key_values") is None:
|
| 141 |
+
depth = model_kwargs.get("num_visits")
|
| 142 |
+
depth = self.model.config.num_visits if depth is None else depth
|
| 143 |
+
model_kwargs["past_key_values"] = MoeloopCache(depth)
|
| 144 |
+
|
| 145 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, position_ids=None, **kwargs):
|
| 146 |
+
past = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 147 |
+
if past:
|
| 148 |
+
input_ids = input_ids[:, past:] if input_ids.size(1) > past else input_ids[:, -1:]
|
| 149 |
+
if position_ids is None and attention_mask is not None:
|
| 150 |
+
position_ids = (attention_mask.long().cumsum(-1) - 1).clamp_min(0)
|
| 151 |
+
if position_ids is not None:
|
| 152 |
+
position_ids = position_ids[:, -input_ids.size(1):]
|
| 153 |
+
return {
|
| 154 |
+
"input_ids": input_ids,
|
| 155 |
+
"past_key_values": past_key_values,
|
| 156 |
+
"attention_mask": attention_mask,
|
| 157 |
+
"position_ids": position_ids,
|
| 158 |
+
"use_cache": kwargs.get("use_cache", True),
|
| 159 |
+
"num_visits": kwargs.get("num_visits"),
|
| 160 |
+
"logits_to_keep": kwargs.get("logits_to_keep", 1),
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None, past_key_values=None,
|
| 164 |
+
labels=None, use_cache=None, num_visits=None, logits_to_keep=0, return_dict=True,
|
| 165 |
+
output_attentions=False, output_hidden_states=False, **kwargs):
|
| 166 |
+
if input_ids is None:
|
| 167 |
+
raise ValueError("input_ids are required; inputs_embeds is not a v1 interface")
|
| 168 |
+
if output_attentions:
|
| 169 |
+
raise ValueError("attention weight materialization is not supported")
|
| 170 |
+
if kwargs.get("inputs_embeds") is not None:
|
| 171 |
+
raise ValueError("inputs_embeds is not supported")
|
| 172 |
+
if labels is not None and past_key_values is not None:
|
| 173 |
+
raise ValueError("labels and an existing inference cache cannot be combined")
|
| 174 |
+
depth = self.model.config.num_visits if num_visits is None else num_visits
|
| 175 |
+
cache_enabled = self.config.use_cache if use_cache is None else use_cache
|
| 176 |
+
cache_enabled = cache_enabled and not self.training and labels is None and not torch.is_grad_enabled()
|
| 177 |
+
if past_key_values is not None and not isinstance(past_key_values, MoeloopCache):
|
| 178 |
+
raise TypeError("past_key_values must be a MoeloopCache")
|
| 179 |
+
if past_key_values is not None and not cache_enabled:
|
| 180 |
+
raise ValueError("past_key_values requires use_cache=True in inference mode")
|
| 181 |
+
cache = past_key_values if cache_enabled else None
|
| 182 |
+
if cache_enabled and cache is None:
|
| 183 |
+
cache = MoeloopCache(depth)
|
| 184 |
+
if cache is not None and cache.store.num_visits != depth:
|
| 185 |
+
raise ValueError("generation depth cannot change within a cache session")
|
| 186 |
+
valid = None if attention_mask is None else attention_mask[:, -input_ids.size(1):].bool()
|
| 187 |
+
out = self.model(input_ids, positions=position_ids, attention_mask=None if attention_mask is None else attention_mask.bool(),
|
| 188 |
+
router_mask=valid, num_visits=depth, cache=None if cache is None else cache.store,
|
| 189 |
+
return_hidden=True, collect_readouts=False)
|
| 190 |
+
hidden = out.hidden_states
|
| 191 |
+
if labels is None and isinstance(logits_to_keep, int) and logits_to_keep > 0:
|
| 192 |
+
hidden = hidden[:, -logits_to_keep:]
|
| 193 |
+
elif labels is None and isinstance(logits_to_keep, Tensor):
|
| 194 |
+
hidden = hidden[:, logits_to_keep]
|
| 195 |
+
logits = self.model.lm_head(hidden)
|
| 196 |
+
loss = None
|
| 197 |
+
if labels is not None:
|
| 198 |
+
if labels.shape != input_ids.shape:
|
| 199 |
+
raise ValueError("HF labels must have the same shape as input_ids")
|
| 200 |
+
targets = labels[:, 1:].contiguous()
|
| 201 |
+
count = (targets != -100).sum()
|
| 202 |
+
if count.item() == 0:
|
| 203 |
+
raise ValueError("HF labels have no valid next-token targets")
|
| 204 |
+
loss = F.cross_entropy(logits[:, :-1].float().reshape(-1, logits.size(-1)), targets.reshape(-1), reduction="sum", ignore_index=-100) / count
|
| 205 |
+
result = CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=cache,
|
| 206 |
+
hidden_states=(out.hidden_states,) if output_hidden_states else None)
|
| 207 |
+
return result if return_dict else result.to_tuple()
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# save_pretrained copies this file and its same-directory relative dependencies.
|
| 211 |
+
MoeloopConfig.register_for_auto_class("AutoConfig")
|
| 212 |
+
MoeloopForCausalLM.register_for_auto_class("AutoModelForCausalLM")
|
latent.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent latent initialization and stateless microbatch depth sampling."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch import Tensor, nn
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def initial_latent(
|
| 13 |
+
anchor: Tensor, *, training: bool, std: float = math.sqrt(2 / 5),
|
| 14 |
+
truncation: float = 3.0,
|
| 15 |
+
) -> Tensor:
|
| 16 |
+
"""Draw an independent training state; evaluation explicitly starts at zero.
|
| 17 |
+
|
| 18 |
+
Training uses the device's global Torch RNG, which the trainer checkpoints.
|
| 19 |
+
``std`` describes the normal before truncation, not the resulting variance.
|
| 20 |
+
Neither branch creates a gradient path from the initial state to the anchor.
|
| 21 |
+
The live anchor must still be passed separately to the recurrent update.
|
| 22 |
+
|
| 23 |
+
Precondition: finite positive ``std`` and ``truncation``; ``ModelConfig``
|
| 24 |
+
enforces this for ``latent_init_std`` and ``latent_truncation``.
|
| 25 |
+
"""
|
| 26 |
+
if not isinstance(anchor, Tensor) or not anchor.is_floating_point():
|
| 27 |
+
raise ValueError("initial latent needs a floating-point anchor tensor")
|
| 28 |
+
if type(training) is not bool:
|
| 29 |
+
raise ValueError("training must be bool")
|
| 30 |
+
if not training:
|
| 31 |
+
return torch.zeros_like(anchor)
|
| 32 |
+
return nn.init.trunc_normal_(torch.empty_like(anchor), mean=0.0, std=std,
|
| 33 |
+
a=-truncation * std, b=truncation * std)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def sampled_depth(
|
| 37 |
+
*, seed: int, completed_updates: int, microbatch: int,
|
| 38 |
+
mean: float = 4.0, log_std: float = 0.5,
|
| 39 |
+
) -> int:
|
| 40 |
+
"""Sample ``1 + Poisson(LogNormal)`` with the requested expected depth.
|
| 41 |
+
|
| 42 |
+
The coordinate, rather than a rank's mutable RNG, determines the draw. All
|
| 43 |
+
ranks using the same recipe/update/microbatch therefore agree, including
|
| 44 |
+
after restoration. No upper depth cap or reconstructed global RNG is used.
|
| 45 |
+
|
| 46 |
+
Precondition: finite ``mean`` > 1 and finite ``log_std`` >= 0;
|
| 47 |
+
``TrainingRecipe`` enforces this for ``depth_mean`` and ``depth_log_std``.
|
| 48 |
+
"""
|
| 49 |
+
if type(seed) is not int:
|
| 50 |
+
raise ValueError("depth seed must be an integer")
|
| 51 |
+
for name, value in (("completed_updates", completed_updates), ("microbatch", microbatch)):
|
| 52 |
+
if type(value) is not int or value < 0:
|
| 53 |
+
raise ValueError(f"{name} must be a nonnegative integer")
|
| 54 |
+
location = math.log(mean - 1) - 0.5 * log_std * log_std
|
| 55 |
+
if not math.isfinite(location):
|
| 56 |
+
raise ValueError("lognormal depth location must be finite")
|
| 57 |
+
key = f"poisson_lognormal_micro_v1:{seed}:{completed_updates}:{microbatch}".encode()
|
| 58 |
+
local_seed = int.from_bytes(hashlib.sha256(key).digest()[:8], "big")
|
| 59 |
+
generator = torch.Generator(device="cpu").manual_seed(local_seed)
|
| 60 |
+
epsilon = torch.randn((), dtype=torch.float64, generator=generator)
|
| 61 |
+
rate = torch.exp(location + log_std * epsilon)
|
| 62 |
+
if not torch.isfinite(rate).item():
|
| 63 |
+
raise ValueError("sampled depth rate overflowed; change the declared distribution")
|
| 64 |
+
return 1 + int(torch.poisson(rate, generator=generator).item())
|
memory.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functional normalized memories; callers own forward and visit resets."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import NamedTuple
|
| 7 |
+
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class EMACarry(NamedTuple):
|
| 12 |
+
"""A differentiable numerator and its scalar normalization, never a buffer."""
|
| 13 |
+
|
| 14 |
+
numerator: Tensor | None = None
|
| 15 |
+
denominator: float = 0.0
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def ema_update(carry: EMACarry, write: Tensor, *, beta: float = .5) -> tuple[EMACarry, Tensor]:
|
| 19 |
+
"""Return new carry and its updated read without mutating or detaching history.
|
| 20 |
+
|
| 21 |
+
Start a new forward with ``EMACarry()`` for global memory; separately start
|
| 22 |
+
each visit with ``EMACarry()`` for local memory. Add the two returned reads
|
| 23 |
+
directly to the residual stream. This function neither combines memories
|
| 24 |
+
nor adds a separate attention residual.
|
| 25 |
+
|
| 26 |
+
Precondition: ``beta`` is finite and in [0, 1); ``ModelConfig`` enforces
|
| 27 |
+
this for ``memory_beta``. The carry and write are checked here.
|
| 28 |
+
"""
|
| 29 |
+
if not isinstance(write, Tensor) or not write.is_floating_point():
|
| 30 |
+
raise ValueError("write must be a floating-point tensor")
|
| 31 |
+
numerator, denominator = carry
|
| 32 |
+
if type(denominator) not in (int, float) or not math.isfinite(denominator):
|
| 33 |
+
raise ValueError("carry denominator must be finite")
|
| 34 |
+
if numerator is None:
|
| 35 |
+
if denominator != 0:
|
| 36 |
+
raise ValueError("empty carry must have zero denominator")
|
| 37 |
+
numerator = write
|
| 38 |
+
else:
|
| 39 |
+
if (denominator <= 0 or numerator.shape != write.shape
|
| 40 |
+
or numerator.device != write.device or numerator.dtype != write.dtype):
|
| 41 |
+
raise ValueError("carry must have positive normalization and match the write shape/device/dtype")
|
| 42 |
+
numerator = beta * numerator + write
|
| 43 |
+
denominator = beta * denominator + 1.0
|
| 44 |
+
return EMACarry(numerator, denominator), numerator / denominator
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def residual_gain(num_cells: int, num_visits: int, *, scale: float = .5) -> float:
|
| 48 |
+
"""Scale a residual write by ``scale / (num_visits * sqrt(num_cells))``.
|
| 49 |
+
|
| 50 |
+
Precondition: positive integer ``num_cells`` and ``num_visits`` and finite
|
| 51 |
+
nonnegative ``scale``; ``ModelConfig`` and ``RecursiveLM.forward`` enforce them.
|
| 52 |
+
"""
|
| 53 |
+
return scale / (num_visits * math.sqrt(num_cells))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def reinjection_gain(num_cells: int, visit: int, *, scale: float = .5) -> float:
|
| 57 |
+
"""Gain for a one-based visit >= 2; visit 1 starts from the input itself."""
|
| 58 |
+
if type(visit) is not int or visit < 2:
|
| 59 |
+
raise ValueError("reinjection requires a one-based visit >= 2")
|
| 60 |
+
return residual_gain(num_cells, visit, scale=scale)
|
model.py
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Plain PyTorch recursive language models with explicit physical owners.
|
| 2 |
+
|
| 3 |
+
Read ``LoopedLM.forward`` for execution/gradient order and ``Cell.forward``
|
| 4 |
+
for the state update. Paper names belong in recipes rather than this module.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from contextlib import nullcontext
|
| 10 |
+
import math
|
| 11 |
+
import re
|
| 12 |
+
from typing import Callable, Iterator, Literal, NamedTuple
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from torch import Tensor, nn
|
| 16 |
+
from torch.distributed.tensor import DTensor, distribute_tensor
|
| 17 |
+
from torch.distributed.tensor.experimental import implicit_replication
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
|
| 20 |
+
from .cache import CacheSlot, DecodeCache
|
| 21 |
+
from .config import ModelConfig, RegionConfig # RegionConfig: documented import path
|
| 22 |
+
from .moe import DenseFFN, ExpertBank, Router
|
| 23 |
+
from .latent import initial_latent
|
| 24 |
+
from .memory import EMACarry, ema_update, residual_gain, reinjection_gain
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# The core cells' branch output projections, the last matrix before each residual add, which
|
| 28 |
+
# ModelConfig.output_lr_scale and output_init_scale act on. It matches LoopedLM names (core.0...)
|
| 29 |
+
# and TitanModel names (core.core.0...), with or without the activation-checkpoint wrapper segment.
|
| 30 |
+
CORE_OUTPUT_PATTERN = (r"(?:^|\.)core\.\d+\.(?:_checkpoint_wrapped_module\.)?"
|
| 31 |
+
r"(?:attentions\.\d+\.out_proj\.weight|experts\.(?:routed\.inner_experts\.)?w2_EDF"
|
| 32 |
+
r"|(?:dense_ffn|always_on_ffn)\.w2\.weight)$")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ModelOutput(NamedTuple):
|
| 36 |
+
"""Counts retain physical aggregation and logical-call identity.
|
| 37 |
+
|
| 38 |
+
``router_counts`` has one row per physical prefix/core/suffix cell. Both
|
| 39 |
+
tensors pad to the largest expert count; per-call widths distinguish real
|
| 40 |
+
experts from padding, including dense cells with width zero. Call rows
|
| 41 |
+
follow the actual stack/layer execution order.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
logits: Tensor | None
|
| 45 |
+
hidden_states: Tensor
|
| 46 |
+
balance_sum: Tensor
|
| 47 |
+
z_sum: Tensor
|
| 48 |
+
aux_calls: int
|
| 49 |
+
router_counts: Tensor
|
| 50 |
+
router_call_counts: Tensor | None = None
|
| 51 |
+
router_call_slots: tuple[CacheSlot, ...] = ()
|
| 52 |
+
router_call_widths: tuple[int, ...] = ()
|
| 53 |
+
visit_hidden_states: tuple[Tensor, ...] = ()
|
| 54 |
+
hazard_logits: Tensor | None = None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class RMSNorm(nn.Module):
|
| 58 |
+
def __init__(self, dim: int, eps: float = 1e-6) -> None:
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.weight = nn.Parameter(torch.empty(dim))
|
| 61 |
+
self.eps = eps
|
| 62 |
+
|
| 63 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 64 |
+
return F.rms_norm(x, (self.weight.numel(),), self.weight, self.eps)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@torch.no_grad()
|
| 68 |
+
def init_normal(parameter: Tensor, std: float, generator: torch.Generator | None) -> None:
|
| 69 |
+
"""Draw the full tensor from normal(0, std) on the default device and write it into ``parameter``.
|
| 70 |
+
|
| 71 |
+
The default device is CPU (meta inside a meta build, which draws nothing). A DTensor
|
| 72 |
+
keeps only this rank's part, cut locally with no communication, so the values depend
|
| 73 |
+
only on the generator, never on the rank count, sharding or GPU model. A plain CPU
|
| 74 |
+
parameter gets exactly the values of an in-place ``normal_``.
|
| 75 |
+
"""
|
| 76 |
+
full = torch.empty(parameter.shape, dtype=parameter.dtype).normal_(0.0, std, generator=generator)
|
| 77 |
+
if isinstance(parameter, DTensor):
|
| 78 |
+
full = distribute_tensor(full, parameter.device_mesh, parameter.placements, src_data_rank=None)
|
| 79 |
+
parameter.copy_(full)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def apply_rotary(x: Tensor, positions: Tensor, theta: float) -> Tensor:
|
| 83 |
+
"""Split-half RoPE on [batch, heads, tokens, head_dim] using [batch,tokens]."""
|
| 84 |
+
half = x.size(-1) // 2
|
| 85 |
+
frequencies = theta ** (-torch.arange(half, dtype=torch.float32, device=x.device) / half)
|
| 86 |
+
angles = positions.float().unsqueeze(-1) * frequencies
|
| 87 |
+
cosine, sine = angles.cos().unsqueeze(1), angles.sin().unsqueeze(1)
|
| 88 |
+
first, second = x.float().chunk(2, dim=-1)
|
| 89 |
+
return torch.cat((first * cosine - second * sine, second * cosine + first * sine), dim=-1).to(x.dtype)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class LoRA(nn.Module):
|
| 93 |
+
"""One visit's low-rank delta ``B A x`` on one shared Linear ``W' x``.
|
| 94 |
+
|
| 95 |
+
Relaxed Recursive Transformers (arXiv 2410.20672v3, Section 2.3, after eq. 3):
|
| 96 |
+
``h = W' x + B A x`` with ``A`` of shape [rank, in] and ``B`` [out, rank],
|
| 97 |
+
and no alpha/rank scaling. ``reset_parameters`` draws ``A`` from
|
| 98 |
+
normal(init_std) and zeroes ``B`` (the paper's "zero initialization",
|
| 99 |
+
Appendix C), so a new model computes exactly its shared-weight model.
|
| 100 |
+
``LoopedLM.initialize_weights`` calls it after every other draw.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def __init__(self, in_features: int, out_features: int, rank: int) -> None:
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.A = nn.Parameter(torch.empty(rank, in_features))
|
| 106 |
+
self.B = nn.Parameter(torch.empty(out_features, rank))
|
| 107 |
+
|
| 108 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 109 |
+
return F.linear(F.linear(x, self.A), self.B)
|
| 110 |
+
|
| 111 |
+
@torch.no_grad()
|
| 112 |
+
def reset_parameters(self, std: float, generator: torch.Generator | None = None) -> None:
|
| 113 |
+
"""Zero initialization: A from normal(std), B = 0."""
|
| 114 |
+
init_normal(self.A, std, generator)
|
| 115 |
+
nn.init.zeros_(self.B)
|
| 116 |
+
|
| 117 |
+
@torch.no_grad()
|
| 118 |
+
def svd_init(self, residual: Tensor) -> None:
|
| 119 |
+
"""The paper's optional SVD initialization (eq. 4): ``B = U_r S_r``, ``A = V_r^T``.
|
| 120 |
+
|
| 121 |
+
``residual`` is ``W_l - W'``: a full-size model's weight at this
|
| 122 |
+
layer and visit minus the shared weight, so ``W' + B A`` is its best
|
| 123 |
+
rank-r approximation. The SVD runs in FP64.
|
| 124 |
+
"""
|
| 125 |
+
u, s, vh = torch.linalg.svd(residual.double(), full_matrices=False)
|
| 126 |
+
rank = self.A.size(0)
|
| 127 |
+
self.B.copy_(u[:, :rank] * s[:rank])
|
| 128 |
+
self.A.copy_(vh[:rank])
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class Attention(nn.Module):
|
| 132 |
+
def __init__(self, config: ModelConfig) -> None:
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.num_heads = config.num_heads
|
| 135 |
+
self.num_kv_heads = config.num_kv_heads
|
| 136 |
+
self.head_dim = config.dim // config.num_heads
|
| 137 |
+
self.rope_theta = config.rope_theta
|
| 138 |
+
self.q_proj = nn.Linear(config.dim, self.num_heads * self.head_dim, bias=config.qk_bias)
|
| 139 |
+
self.k_proj = nn.Linear(config.dim, self.num_kv_heads * self.head_dim, bias=config.qk_bias)
|
| 140 |
+
self.v_proj = nn.Linear(config.dim, self.num_kv_heads * self.head_dim, bias=False)
|
| 141 |
+
self.out_proj = nn.Linear(config.dim, config.dim, bias=False)
|
| 142 |
+
self.q_norm = RMSNorm(self.head_dim, config.rms_eps) if config.qk_norm else nn.Identity()
|
| 143 |
+
self.k_norm = RMSNorm(self.head_dim, config.rms_eps) if config.qk_norm else nn.Identity()
|
| 144 |
+
|
| 145 |
+
def _attention(
|
| 146 |
+
self, query: Tensor, key: Tensor, value: Tensor, attention_mask: object | None, *, is_causal: bool,
|
| 147 |
+
) -> Tensor:
|
| 148 |
+
"""Finite kernel seam: native bindings can override only attention math."""
|
| 149 |
+
if attention_mask is not None and not isinstance(attention_mask, Tensor):
|
| 150 |
+
raise TypeError("reference attention accepts bool tensor masks; use a native attention binding for prepared masks")
|
| 151 |
+
repetitions = self.num_heads // self.num_kv_heads
|
| 152 |
+
if repetitions > 1:
|
| 153 |
+
key = key.repeat_interleave(repetitions, dim=1)
|
| 154 |
+
value = value.repeat_interleave(repetitions, dim=1)
|
| 155 |
+
return F.scaled_dot_product_attention(query, key, value, attn_mask=attention_mask, is_causal=is_causal)
|
| 156 |
+
|
| 157 |
+
def forward(
|
| 158 |
+
self, x: Tensor, *, positions: Tensor, attention_mask: object | None = None,
|
| 159 |
+
cache: DecodeCache | None = None, slot: CacheSlot = ("core", 0, 0),
|
| 160 |
+
lora: nn.ModuleDict | None = None,
|
| 161 |
+
) -> Tensor:
|
| 162 |
+
"""``lora`` holds this visit's LoRA for q_proj, k_proj, v_proj and out_proj."""
|
| 163 |
+
batch, tokens, dim = x.shape
|
| 164 |
+
query, key, value = self.q_proj(x), self.k_proj(x), self.v_proj(x)
|
| 165 |
+
if lora is not None:
|
| 166 |
+
query, key, value = query + lora.q_proj(x), key + lora.k_proj(x), value + lora.v_proj(x)
|
| 167 |
+
query = query.view(batch, tokens, self.num_heads, self.head_dim).transpose(1, 2)
|
| 168 |
+
key = key.view(batch, tokens, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 169 |
+
value = value.view(batch, tokens, self.num_kv_heads, self.head_dim).transpose(1, 2)
|
| 170 |
+
query = apply_rotary(self.q_norm(query), positions, self.rope_theta)
|
| 171 |
+
key = apply_rotary(self.k_norm(key), positions, self.rope_theta)
|
| 172 |
+
if cache is not None:
|
| 173 |
+
key, value = cache.append(slot, key, value)
|
| 174 |
+
result = self._attention(query, key, value, attention_mask, is_causal=attention_mask is None)
|
| 175 |
+
mixed = result.transpose(1, 2).contiguous().view(batch, tokens, dim)
|
| 176 |
+
return self.out_proj(mixed) if lora is None else self.out_proj(mixed) + lora.out_proj(mixed)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def dense_ffn(ffn: DenseFFN, x: Tensor, lora: nn.ModuleDict | None) -> Tensor:
|
| 180 |
+
"""``DenseFFN`` (SwiGLU) with this visit's LoRA on w1, w3 and w2, if any."""
|
| 181 |
+
if lora is None:
|
| 182 |
+
return ffn(x)
|
| 183 |
+
hidden = F.silu(ffn.w1(x) + lora.w1(x)) * (ffn.w3(x) + lora.w3(x))
|
| 184 |
+
return ffn.w2(hidden) + lora.w2(hidden)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class InputAdapter(nn.Module):
|
| 188 |
+
"""Stage input injection: the state entering each core visit, from the state and the anchor.
|
| 189 |
+
|
| 190 |
+
- ``add``: ``h + s e``; ``linear``: ``A h + s W e``.
|
| 191 |
+
- ``diag_decay``: ``exp(-dt * a) * h + dt * (W e)`` with per-channel
|
| 192 |
+
``dt = softplus(dt_bias)`` and ``a = exp(A_log)``; arXiv 2610.06833
|
| 193 |
+
Appendix B.4 equation (24) ("Parcae w/o norm", Table 7) and xllm-loop
|
| 194 |
+
(commit 755c7b3) ``xllm/models/looped.py`` ``InputInjection`` (lines 69-138).
|
| 195 |
+
- ``orthogonal`` (OrthoInj): ``Q_q exp(-dt * a) * h + q`` with ``q = dt * (W e)``
|
| 196 |
+
and ``Q_q = I - q q^T / (|q|^2 + eps)``; arXiv 2610.06833 Section 4.2
|
| 197 |
+
equation (8) and xllm-loop ``OrthogonalInputInjection`` (lines 162-178).
|
| 198 |
+
``Q_q`` is a per-token projector off ``q``, not an orthogonal weight
|
| 199 |
+
matrix; the paper has no orthogonality constraint on ``W``. Its inner
|
| 200 |
+
products run in FP32 (FP64 stays FP64), as in the paper's recipe.
|
| 201 |
+
|
| 202 |
+
Both new kinds start at ``W = I``, ``a = injection_decay`` and
|
| 203 |
+
``dt = injection_dt``. The defaults are the OrthoInj recipe of Appendix B.4
|
| 204 |
+
(a = 1, dt = log(5)/2, retention 1/sqrt(5)); its "Parcae w/o norm" row uses
|
| 205 |
+
dt = 1. The anchor ``e`` is the prefix output with no prelude RMSNorm, so
|
| 206 |
+
Parcae-Decay's normalized input is not expressed here. ``q`` is recomputed
|
| 207 |
+
at every visit, as in the reference code. ``LoopedLM.initialize_weights``
|
| 208 |
+
applies this initialization, also on the TorchTitan path (#90).
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
def __init__(self, config: ModelConfig) -> None:
|
| 212 |
+
super().__init__()
|
| 213 |
+
self.kind, self.scale, self.eps = config.input_injection, config.injection_scale, config.injection_eps
|
| 214 |
+
self.dt_init, self.decay_init = config.injection_dt, config.injection_decay
|
| 215 |
+
if self.kind == "linear":
|
| 216 |
+
self.state_proj = nn.Linear(config.dim, config.dim, bias=False)
|
| 217 |
+
if self.kind != "add":
|
| 218 |
+
self.input_proj = nn.Linear(config.dim, config.dim, bias=False)
|
| 219 |
+
if self.kind in ("diag_decay", "orthogonal"):
|
| 220 |
+
self.A_log = nn.Parameter(torch.empty(config.dim))
|
| 221 |
+
self.dt_bias = nn.Parameter(torch.empty(config.dim))
|
| 222 |
+
|
| 223 |
+
@torch.no_grad()
|
| 224 |
+
def reset_decay(self) -> None:
|
| 225 |
+
"""Declared initialization of the decay kinds: W = I, a and dt by inverse exp/softplus."""
|
| 226 |
+
weight = self.input_proj.weight
|
| 227 |
+
weight.copy_(torch.eye(weight.size(0), dtype=weight.dtype, device=weight.device))
|
| 228 |
+
self.A_log.fill_(math.log(self.decay_init))
|
| 229 |
+
self.dt_bias.fill_(self.dt_init + math.log(-math.expm1(-self.dt_init)))
|
| 230 |
+
|
| 231 |
+
def forward(self, state: Tensor, anchor: Tensor) -> Tensor:
|
| 232 |
+
if self.kind == "add":
|
| 233 |
+
return state + self.scale * anchor
|
| 234 |
+
if self.kind == "linear":
|
| 235 |
+
return self.state_proj(state) + self.scale * self.input_proj(anchor)
|
| 236 |
+
dt = F.softplus(self.dt_bias).to(state.dtype)
|
| 237 |
+
retained = torch.exp(-dt * self.A_log.exp().to(state.dtype)) * state
|
| 238 |
+
injected = dt * self.input_proj(anchor)
|
| 239 |
+
if self.kind == "diag_decay":
|
| 240 |
+
return retained + injected
|
| 241 |
+
compute = torch.float64 if retained.dtype == torch.float64 else torch.float32
|
| 242 |
+
value, q = retained.to(compute), injected.to(compute)
|
| 243 |
+
coefficient = (value * q).sum(-1, keepdim=True) / (q.square().sum(-1, keepdim=True) + self.eps)
|
| 244 |
+
return (value - coefficient * q).to(retained.dtype) + injected
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def per_visit(owners: nn.ModuleList, visit: int) -> nn.Module:
|
| 248 |
+
"""The visit's own module when the cell keeps one per visit, else the shared one."""
|
| 249 |
+
return owners[visit if len(owners) > 1 else 0]
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class Cell(nn.Module):
|
| 253 |
+
"""One physical bank, with singleton or per-visit attention/router/norm owners.
|
| 254 |
+
|
| 255 |
+
Every visit can also own a LoRA on each shared attention projection (rank
|
| 256 |
+
``lora_attention_rank``) and on w1, w3, w2 of the dense or always-on FFN
|
| 257 |
+
(rank ``lora_ffn_rank``); routers and routed experts take no LoRA. A rank
|
| 258 |
+
of 0 builds none; ``region_config`` gives prefix and suffix cells rank 0.
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
def __init__(
|
| 262 |
+
self, config: ModelConfig, visits: int = 1, *,
|
| 263 |
+
expert_factory: Callable[[ModelConfig], nn.Module] | None = None,
|
| 264 |
+
attention_factory: Callable[[ModelConfig], nn.Module] | None = None,
|
| 265 |
+
) -> None:
|
| 266 |
+
super().__init__()
|
| 267 |
+
self.config = config
|
| 268 |
+
attention_factory = attention_factory or Attention
|
| 269 |
+
expert_factory = expert_factory or ExpertBank
|
| 270 |
+
self.attentions = nn.ModuleList(attention_factory(config) for _ in range(visits if config.attention_per_visit else 1))
|
| 271 |
+
self.attention_norms = nn.ModuleList(RMSNorm(config.dim, config.rms_eps) for _ in range(visits if config.norm_per_visit else 1))
|
| 272 |
+
self.ffn_norms = nn.ModuleList(RMSNorm(config.dim, config.rms_eps) for _ in range(visits if config.norm_per_visit else 1))
|
| 273 |
+
norms = visits if config.norm_per_visit else 1 # sandwich output and residual norms, identities when off
|
| 274 |
+
self.attention_output_norms = nn.ModuleList(RMSNorm(config.dim, config.rms_eps) if config.sandwich_norm else nn.Identity() for _ in range(norms))
|
| 275 |
+
self.ffn_output_norms = nn.ModuleList(RMSNorm(config.dim, config.rms_eps) if config.sandwich_norm else nn.Identity() for _ in range(norms))
|
| 276 |
+
self.attention_residual_norms = nn.ModuleList(RMSNorm(config.dim, config.rms_eps) if config.residual_norm else nn.Identity() for _ in range(norms))
|
| 277 |
+
self.ffn_residual_norms = nn.ModuleList(RMSNorm(config.dim, config.rms_eps) if config.residual_norm else nn.Identity() for _ in range(norms))
|
| 278 |
+
self.routers = nn.ModuleList(Router(config) for _ in range(visits if config.router_per_visit else 1)) if config.num_experts else nn.ModuleList()
|
| 279 |
+
self.experts = expert_factory(config) if config.num_experts else None
|
| 280 |
+
self.dense_ffn = DenseFFN(config.dim, config.hidden_dim) if not config.num_experts else None
|
| 281 |
+
self.always_on_ffn = DenseFFN(config.dim, config.always_on_hidden_dim) if config.always_on_hidden_dim else None
|
| 282 |
+
self.residual_scale = config.residual_scale
|
| 283 |
+
self.visit_residual_scales = config.visit_residual_scales # core cells only; see ModelConfig
|
| 284 |
+
d, kv = config.dim, config.num_kv_heads * (config.dim // config.num_heads)
|
| 285 |
+
ffn = config.always_on_hidden_dim if config.num_experts else config.hidden_dim
|
| 286 |
+
|
| 287 |
+
def visit_loras(rank: int, shapes: dict[str, tuple[int, int]]) -> nn.ModuleList | None:
|
| 288 |
+
if not rank:
|
| 289 |
+
return None
|
| 290 |
+
return nn.ModuleList(nn.ModuleDict({name: LoRA(i, o, rank) for name, (i, o) in shapes.items()})
|
| 291 |
+
for _ in range(visits))
|
| 292 |
+
self.attention_loras = visit_loras(config.lora_attention_rank, {
|
| 293 |
+
"q_proj": (d, d), "k_proj": (d, kv), "v_proj": (d, kv), "out_proj": (d, d)})
|
| 294 |
+
self.ffn_loras = visit_loras(config.lora_ffn_rank, {"w1": (d, ffn), "w3": (d, ffn), "w2": (ffn, d)})
|
| 295 |
+
|
| 296 |
+
def feed_forward(self, x: Tensor, *, visit: int, router_mask: Tensor) -> tuple[Tensor, tuple[Tensor, Tensor, Tensor]]:
|
| 297 |
+
"""FFN update of normalized ``x`` and its routing statistics ``(balance, z_loss, counts)``.
|
| 298 |
+
|
| 299 |
+
The visit's FFN LoRA sits on the dense or always-on FFN; a dense cell has zero statistics.
|
| 300 |
+
"""
|
| 301 |
+
lora = None if self.ffn_loras is None else self.ffn_loras[visit]
|
| 302 |
+
if self.experts is None:
|
| 303 |
+
zero = x.new_zeros((), dtype=torch.float32)
|
| 304 |
+
return dense_ffn(self.dense_ffn, x, lora), (zero, zero, x.new_empty((0,), dtype=torch.long))
|
| 305 |
+
routing = per_visit(self.routers, visit)(x, router_mask)
|
| 306 |
+
update = self.experts(x, routing.ids, routing.weights, routing.dispatch_counts)
|
| 307 |
+
if self.always_on_ffn is not None:
|
| 308 |
+
update = update + dense_ffn(self.always_on_ffn, x, lora)
|
| 309 |
+
return update, (routing.balance, routing.z_loss, routing.counts.detach())
|
| 310 |
+
|
| 311 |
+
def forward(
|
| 312 |
+
self, x: Tensor, *, visit: int, positions: Tensor, attention_mask: object | None,
|
| 313 |
+
router_mask: Tensor, cache: DecodeCache | None, slot: CacheSlot,
|
| 314 |
+
memory: object = None, depth: int | None = None,
|
| 315 |
+
) -> tuple[Tensor, tuple[Tensor, Tensor, Tensor], object]:
|
| 316 |
+
"""``x + s attention(norm(x))``, then ``x + s ffn(norm(x))`` with ``s = residual_scale``,
|
| 317 |
+
or ``s = visit_residual_scales[visit]`` when the cell has per-visit scales.
|
| 318 |
+
|
| 319 |
+
With ``sandwich_norm`` each sublayer output is normalized too:
|
| 320 |
+
``x + s out_norm(attention(norm(x)))``; with ``residual_norm`` the sum is normalized:
|
| 321 |
+
``residual_norm(x + s attention(norm(x)))``. Each extra norm is the identity when its flag is off.
|
| 322 |
+
|
| 323 |
+
Every cell takes these keywords and returns ``(x, (balance, z_loss, counts), memory)``.
|
| 324 |
+
``memory`` and ``depth`` are for ``MemoryCell``; a ``Cell`` returns ``memory`` unchanged.
|
| 325 |
+
"""
|
| 326 |
+
# Only attention LoRA passes ``lora=``, so other attention factories keep their signature.
|
| 327 |
+
lora = {} if self.attention_loras is None else {"lora": self.attention_loras[visit]}
|
| 328 |
+
scale = self.visit_residual_scales[visit] if self.visit_residual_scales else self.residual_scale
|
| 329 |
+
update = per_visit(self.attentions, visit)(
|
| 330 |
+
per_visit(self.attention_norms, visit)(x), positions=positions,
|
| 331 |
+
attention_mask=attention_mask, cache=cache, slot=slot, **lora,
|
| 332 |
+
)
|
| 333 |
+
x = per_visit(self.attention_residual_norms, visit)(
|
| 334 |
+
x + scale * per_visit(self.attention_output_norms, visit)(update))
|
| 335 |
+
update, routing = self.feed_forward(per_visit(self.ffn_norms, visit)(x), visit=visit, router_mask=router_mask)
|
| 336 |
+
x = per_visit(self.ffn_residual_norms, visit)(x + scale * per_visit(self.ffn_output_norms, visit)(update))
|
| 337 |
+
return x, routing, memory
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
class MemoryCell(Cell):
|
| 341 |
+
"""LOOM: the attention write enters the ``memory = (global, local)`` EMA streams before the FFN.
|
| 342 |
+
|
| 343 |
+
Both residual writes are scaled by ``residual_gain(num_cells, depth)``.
|
| 344 |
+
"""
|
| 345 |
+
|
| 346 |
+
def __init__(self, config, visits=1, **kwargs):
|
| 347 |
+
super().__init__(config, visits, **kwargs)
|
| 348 |
+
self.ffn_output_norm = RMSNorm(config.dim, config.rms_eps)
|
| 349 |
+
|
| 350 |
+
def forward(self, x, *, visit, positions, attention_mask, router_mask, cache, slot, memory, depth):
|
| 351 |
+
gamma = residual_gain(self.config.num_cells, depth, scale=self.config.memory_scale)
|
| 352 |
+
write = gamma * per_visit(self.attentions, visit)(
|
| 353 |
+
self.attention_norms[0](x), positions=positions, attention_mask=attention_mask, cache=cache, slot=slot)
|
| 354 |
+
global_memory, global_read = ema_update(memory[0], write, beta=self.config.memory_beta)
|
| 355 |
+
local_memory, local_read = ema_update(memory[1], write, beta=self.config.memory_beta)
|
| 356 |
+
x = x + global_read + local_read
|
| 357 |
+
update, routing = self.feed_forward(self.ffn_norms[0](x), visit=visit, router_mask=router_mask)
|
| 358 |
+
return x + gamma * self.ffn_output_norm(update), routing, (global_memory, local_memory)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class CellCall(NamedTuple):
|
| 362 |
+
"""One logical call's routing statistics; ``width`` is 0 for a dense cell."""
|
| 363 |
+
|
| 364 |
+
slot: CacheSlot
|
| 365 |
+
width: int
|
| 366 |
+
differentiated: bool # made with gradients enabled: only these enter the auxiliary sums
|
| 367 |
+
balance: Tensor
|
| 368 |
+
z_loss: Tensor
|
| 369 |
+
counts: Tensor
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def call_cell(
|
| 373 |
+
cell: Cell, state: Tensor, slot: CacheSlot, inputs: dict[str, object], calls: list[CellCall],
|
| 374 |
+
memory: object = None,
|
| 375 |
+
) -> tuple[Tensor, object]:
|
| 376 |
+
"""Run one logical call (``slot`` = region, cell index, visit) and append its statistics to ``calls``."""
|
| 377 |
+
state, (balance, z_loss, counts), memory = cell(state, visit=slot[2], slot=slot, memory=memory, **inputs)
|
| 378 |
+
calls.append(CellCall(slot, cell.config.num_experts, torch.is_grad_enabled(), balance, z_loss, counts))
|
| 379 |
+
return state, memory
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
class LoopedLM(nn.Module):
|
| 383 |
+
def __init__(
|
| 384 |
+
self, config: ModelConfig, *, expert_factory: Callable[[ModelConfig], nn.Module] | None = None,
|
| 385 |
+
attention_factory: Callable[[ModelConfig], nn.Module] | None = None,
|
| 386 |
+
) -> None:
|
| 387 |
+
super().__init__()
|
| 388 |
+
self.config = config
|
| 389 |
+
def cell(region: Literal["prefix", "core", "suffix"], visits: int) -> Cell:
|
| 390 |
+
kind = MemoryCell if region == "core" and config.state_update == "ema" else Cell
|
| 391 |
+
return kind(config.region_config(region), visits, expert_factory=expert_factory, attention_factory=attention_factory)
|
| 392 |
+
self.embedding = nn.Embedding(config.vocab_size, config.dim)
|
| 393 |
+
self.prefix = nn.ModuleList(cell("prefix", 1) for _ in range(config.prefix_cells))
|
| 394 |
+
self.core = nn.ModuleList(cell("core", config.visit_capacity or 1) for _ in range(config.num_cells))
|
| 395 |
+
self.suffix = nn.ModuleList(cell("suffix", 1) for _ in range(config.suffix_cells))
|
| 396 |
+
self.router_count_width = max(cell.config.num_experts for group in (self.prefix, self.core, self.suffix) for cell in group)
|
| 397 |
+
self.input_adapter = InputAdapter(config) if config.input_injection != "none" else None
|
| 398 |
+
self.final_norm = RMSNorm(config.dim, config.rms_eps)
|
| 399 |
+
self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False)
|
| 400 |
+
self.exit_gate = nn.Linear(config.dim, 1) if config.exit_distribution else None
|
| 401 |
+
parameters = list(self.named_parameters(remove_duplicate=False))
|
| 402 |
+
if len(parameters) != len({id(parameter) for _, parameter in parameters}):
|
| 403 |
+
raise ValueError("each parameter needs one canonical owner; factories must return independent modules")
|
| 404 |
+
self.initialize_weights()
|
| 405 |
+
|
| 406 |
+
@torch.no_grad()
|
| 407 |
+
def initialize_weights(self, generator: torch.Generator | None = None) -> None:
|
| 408 |
+
"""Initialize every unique owner once; also call after meta->to_empty.
|
| 409 |
+
|
| 410 |
+
V1 uses explicit normal(init_std) matrices, unit norm scales and zero qk biases; the core
|
| 411 |
+
output projections (``CORE_OUTPUT_PATTERN``) draw normal(init_std * output_init_scale). There
|
| 412 |
+
is no automatic reuse-count rescaling or copy-initialized router alias.
|
| 413 |
+
LoRA draws last (A normal, B zero), so the same seed gives a relaxed
|
| 414 |
+
model the shared weights of its plain counterpart.
|
| 415 |
+
Every matrix is drawn whole on CPU from ``generator`` (the global CPU
|
| 416 |
+
generator when None) in ``canonical_parameters`` order (``init_normal``),
|
| 417 |
+
also when parameters are sharded DTensors, so the values depend only on
|
| 418 |
+
the generator. ``TitanModel.init_states`` calls this method.
|
| 419 |
+
Checkpoint loads must not call this after restoring saved weights.
|
| 420 |
+
"""
|
| 421 |
+
loras = [module for module in self.modules() if isinstance(module, LoRA)]
|
| 422 |
+
lora_parameters = {id(parameter) for module in loras for parameter in module.parameters()}
|
| 423 |
+
output_scale = self.config.region_config("core").output_init_scale
|
| 424 |
+
for name, parameter in self.canonical_parameters():
|
| 425 |
+
if id(parameter) in lora_parameters:
|
| 426 |
+
continue
|
| 427 |
+
if parameter.ndim == 1:
|
| 428 |
+
(nn.init.zeros_ if name.endswith(("q_proj.bias", "k_proj.bias")) else nn.init.ones_)(parameter)
|
| 429 |
+
else:
|
| 430 |
+
scale = output_scale if re.search(CORE_OUTPUT_PATTERN, name) else 1
|
| 431 |
+
init_normal(parameter, self.config.init_std * scale, generator)
|
| 432 |
+
if self.exit_gate is not None:
|
| 433 |
+
nn.init.zeros_(self.exit_gate.weight)
|
| 434 |
+
nn.init.zeros_(self.exit_gate.bias)
|
| 435 |
+
if self.input_adapter is not None and self.input_adapter.kind in ("diag_decay", "orthogonal"):
|
| 436 |
+
# A sharded W takes copy_ of the plain identity as Replicate: each rank keeps its own rows.
|
| 437 |
+
with implicit_replication():
|
| 438 |
+
self.input_adapter.reset_decay()
|
| 439 |
+
for module in loras:
|
| 440 |
+
module.reset_parameters(self.config.init_std, generator)
|
| 441 |
+
|
| 442 |
+
def canonical_parameters(self) -> Iterator[tuple[str, nn.Parameter]]:
|
| 443 |
+
"""Each unique parameter once: exactly ``named_parameters(remove_duplicate=True)``."""
|
| 444 |
+
return self.named_parameters(remove_duplicate=True)
|
| 445 |
+
|
| 446 |
+
def cache_slots(self, num_visits: int | None = None) -> tuple[CacheSlot, ...]:
|
| 447 |
+
depth = self.config.num_visits if num_visits is None else num_visits
|
| 448 |
+
return tuple(
|
| 449 |
+
[("prefix", i, 0) for i in range(len(self.prefix))]
|
| 450 |
+
+ [("core", i, visit) for i in range(len(self.core)) for visit in range(depth)]
|
| 451 |
+
+ [("suffix", i, 0) for i in range(len(self.suffix))]
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
def parse_inputs(
|
| 455 |
+
self, token_ids: Tensor, *, positions: Tensor | None = None,
|
| 456 |
+
attention_mask: object | None = None, router_mask: Tensor | None = None,
|
| 457 |
+
num_visits: int | None = None, grad_visits: int | None = None,
|
| 458 |
+
cache: DecodeCache | None = None, collect_readouts: bool | None = None,
|
| 459 |
+
) -> tuple[dict[str, object], Tensor, int, bool]:
|
| 460 |
+
"""Check one forward's arguments; return ``(inputs, query_valid, grad_visits, collect_readouts)``.
|
| 461 |
+
|
| 462 |
+
``inputs`` are the keywords of every cell call: ``positions``, the prepared
|
| 463 |
+
``attention_mask``, the routing-valid ``router_mask``, ``cache`` and ``depth``.
|
| 464 |
+
The prepared mask is None (SDPA's causal path) for an unpadded full prefix,
|
| 465 |
+
a bool [B,1|H,Q,K] tensor (True allows; causality enforced) built from a bool
|
| 466 |
+
[B,K], [B,Q,K] or [B,1|H,Q,K] mask, or a native kernel's prepared non-Tensor mask.
|
| 467 |
+
"""
|
| 468 |
+
config = self.config
|
| 469 |
+
depth = config.num_visits if num_visits is None else num_visits
|
| 470 |
+
if type(depth) is not int or depth < 1:
|
| 471 |
+
raise ValueError("num_visits must be a positive integer")
|
| 472 |
+
if config.visit_capacity is not None and depth > config.visit_capacity:
|
| 473 |
+
raise ValueError("num_visits exceeds the allocated independent owner visit_capacity")
|
| 474 |
+
if config.visit_residual_scales and depth > len(config.visit_residual_scales):
|
| 475 |
+
raise ValueError("num_visits exceeds the per-visit residual scales")
|
| 476 |
+
differentiated = depth if grad_visits is None else grad_visits
|
| 477 |
+
if type(differentiated) is not int or not 1 <= differentiated <= depth:
|
| 478 |
+
raise ValueError("grad_visits must be in [1, num_visits]")
|
| 479 |
+
if differentiated < depth and (config.order != "stack" or config.independent_visits):
|
| 480 |
+
raise ValueError("tail-only gradients currently require fully shared stack order")
|
| 481 |
+
if differentiated < depth and (config.state_update != "residual" or config.exit_distribution):
|
| 482 |
+
raise ValueError("EMA state and expected exits require full BPTT")
|
| 483 |
+
collect = config.exit_distribution and self.training if collect_readouts is None else collect_readouts
|
| 484 |
+
if collect and (not config.exit_distribution or cache is not None):
|
| 485 |
+
raise ValueError("intermediate readouts require exit_distribution and no inference cache")
|
| 486 |
+
if token_ids.ndim != 2 or token_ids.dtype != torch.long or min(token_ids.shape) < 1:
|
| 487 |
+
raise ValueError("token_ids must be nonempty int64 [batch, tokens]")
|
| 488 |
+
batch, tokens = token_ids.shape
|
| 489 |
+
past = 0 if cache is None else cache.length
|
| 490 |
+
if cache is not None:
|
| 491 |
+
if self.training or torch.is_grad_enabled() or grad_visits is not None:
|
| 492 |
+
raise ValueError("decode cache requires eval(), no_grad() and no gradient truncation")
|
| 493 |
+
if cache.num_visits != depth:
|
| 494 |
+
raise ValueError("cannot change num_visits during a cache session")
|
| 495 |
+
tensor_mask = isinstance(attention_mask, Tensor)
|
| 496 |
+
if tensor_mask:
|
| 497 |
+
if attention_mask.dtype != torch.bool or attention_mask.device != token_ids.device:
|
| 498 |
+
raise ValueError("attention_mask must be bool on the token device")
|
| 499 |
+
if attention_mask.ndim not in (2, 3, 4):
|
| 500 |
+
raise ValueError("attention_mask must have two, three or four dimensions")
|
| 501 |
+
if attention_mask.ndim == 3:
|
| 502 |
+
attention_mask = attention_mask.unsqueeze(1) # [B,Q,K] -> [B,1,Q,K]
|
| 503 |
+
if router_mask is not None and (router_mask.shape != token_ids.shape or router_mask.dtype != torch.bool or router_mask.device != token_ids.device):
|
| 504 |
+
raise ValueError("router_mask must be bool [batch,tokens] on the token device")
|
| 505 |
+
if tensor_mask and attention_mask.ndim == 2:
|
| 506 |
+
if attention_mask.size(0) != batch or attention_mask.size(1) not in (tokens, past + tokens):
|
| 507 |
+
raise ValueError("2D attention_mask must cover query columns or the full cached prefix")
|
| 508 |
+
if past and attention_mask.size(1) == past + tokens and not torch.equal(attention_mask[:, :past], cache.valid_mask):
|
| 509 |
+
raise ValueError("a cache session cannot rewrite past padding metadata")
|
| 510 |
+
query_valid = attention_mask[:, -tokens:]
|
| 511 |
+
elif tensor_mask:
|
| 512 |
+
if attention_mask.size(0) not in (1, batch) or attention_mask.shape[-2:] != (tokens, past + tokens):
|
| 513 |
+
raise ValueError("attention_mask query/key dimensions differ from this forward")
|
| 514 |
+
query_valid = attention_mask.any(dim=-1).any(dim=1).expand(batch, -1) if router_mask is None else router_mask
|
| 515 |
+
elif attention_mask is not None and router_mask is None:
|
| 516 |
+
raise ValueError("prepared native masks require explicit router_mask")
|
| 517 |
+
else:
|
| 518 |
+
query_valid = torch.ones_like(token_ids, dtype=torch.bool) if router_mask is None else router_mask
|
| 519 |
+
if positions is None:
|
| 520 |
+
positions = query_valid.long().cumsum(-1).sub(1).clamp_min(0) if cache is None else cache.next_positions(query_valid)
|
| 521 |
+
if positions.shape != token_ids.shape or positions.dtype != torch.long or positions.device != token_ids.device:
|
| 522 |
+
raise ValueError("positions must be int64 [batch,tokens] on the token device")
|
| 523 |
+
if not torch.compiler.is_compiling() and bool(((positions < 0) | (positions >= config.max_seq_len)).logical_and(query_valid).any()):
|
| 524 |
+
raise ValueError("valid positions must be in [0, max_seq_len)")
|
| 525 |
+
if attention_mask is not None and not tensor_mask:
|
| 526 |
+
if past:
|
| 527 |
+
raise ValueError("prepared native masks do not support decode cache")
|
| 528 |
+
mask = attention_mask
|
| 529 |
+
elif attention_mask is None and router_mask is None and not past:
|
| 530 |
+
mask = None
|
| 531 |
+
else:
|
| 532 |
+
key_valid = query_valid if not past else torch.cat((cache.valid_mask, query_valid), dim=1)
|
| 533 |
+
causal = torch.arange(past + tokens, device=token_ids.device)[None, :] <= (
|
| 534 |
+
past + torch.arange(tokens, device=token_ids.device)[:, None])
|
| 535 |
+
mask = causal[None, None] & key_valid[:, None, None, :] & query_valid[:, None, :, None]
|
| 536 |
+
if tensor_mask and attention_mask.ndim == 4:
|
| 537 |
+
mask = mask & attention_mask
|
| 538 |
+
inputs = dict(positions=positions, attention_mask=mask, cache=cache, depth=depth,
|
| 539 |
+
router_mask=query_valid if router_mask is None else router_mask)
|
| 540 |
+
return inputs, query_valid, differentiated, collect
|
| 541 |
+
|
| 542 |
+
def readout(
|
| 543 |
+
self, state: Tensor, visit: int, inputs: dict[str, object], calls: list[CellCall] | None = None,
|
| 544 |
+
) -> Tensor:
|
| 545 |
+
"""The hidden state the head reads after ``visit``: the suffix cells, then the final norm.
|
| 546 |
+
|
| 547 |
+
With ``core_final_norm`` the final norm also comes first, before the suffix cells.
|
| 548 |
+
The suffix calls' statistics go to ``calls`` when it is given.
|
| 549 |
+
"""
|
| 550 |
+
calls = [] if calls is None else calls
|
| 551 |
+
if self.config.core_final_norm:
|
| 552 |
+
state = self.final_norm(state)
|
| 553 |
+
for index, cell in enumerate(self.suffix):
|
| 554 |
+
state, _ = call_cell(cell, state, ("suffix", index, visit), inputs, calls)
|
| 555 |
+
return self.final_norm(state)
|
| 556 |
+
|
| 557 |
+
def forward(
|
| 558 |
+
self, token_ids: Tensor, *, positions: Tensor | None = None,
|
| 559 |
+
attention_mask: object | None = None, router_mask: Tensor | None = None,
|
| 560 |
+
num_visits: int | None = None, grad_visits: int | None = None,
|
| 561 |
+
cache: DecodeCache | None = None, return_hidden: bool = False,
|
| 562 |
+
collect_readouts: bool | None = None,
|
| 563 |
+
) -> ModelOutput:
|
| 564 |
+
"""Prefix, ``num_visits`` core visits (each read out when collecting), suffix and head.
|
| 565 |
+
|
| 566 |
+
Stack order runs all core cells per visit, layer order all visits per core cell.
|
| 567 |
+
Visits before the last ``grad_visits`` run under no_grad. With
|
| 568 |
+
``visit_final_norm`` every visit after the first starts from
|
| 569 |
+
``final_norm(state)``; without suffix cells each visit's readout is then the next visit's input.
|
| 570 |
+
"""
|
| 571 |
+
config = self.config
|
| 572 |
+
inputs, query_valid, grad_visits, collect = self.parse_inputs(
|
| 573 |
+
token_ids, positions=positions, attention_mask=attention_mask, router_mask=router_mask,
|
| 574 |
+
num_visits=num_visits, grad_visits=grad_visits, cache=cache, collect_readouts=collect_readouts)
|
| 575 |
+
depth = inputs["depth"]
|
| 576 |
+
calls: list[CellCall] = []
|
| 577 |
+
|
| 578 |
+
anchor = self.embedding(token_ids)
|
| 579 |
+
for index, cell in enumerate(self.prefix):
|
| 580 |
+
anchor, _ = call_cell(cell, anchor, ("prefix", index, 0), inputs, calls)
|
| 581 |
+
if config.initial_state == "random":
|
| 582 |
+
state = initial_latent(anchor, training=self.training, std=config.latent_init_std,
|
| 583 |
+
truncation=config.latent_truncation)
|
| 584 |
+
else:
|
| 585 |
+
state = anchor if config.initial_state == "input" else torch.zeros_like(anchor)
|
| 586 |
+
readouts: list[Tensor] = []
|
| 587 |
+
if config.order == "stack":
|
| 588 |
+
memory = (EMACarry(), EMACarry()) # MemoryCell's global and local EMA; other cells pass it on
|
| 589 |
+
for visit in range(depth):
|
| 590 |
+
memory = (memory[0], EMACarry()) # the local stream restarts every visit
|
| 591 |
+
with torch.no_grad() if visit < depth - grad_visits else nullcontext():
|
| 592 |
+
if config.visit_final_norm and visit:
|
| 593 |
+
state = self.final_norm(state)
|
| 594 |
+
if config.state_update == "ema" and visit:
|
| 595 |
+
gain = reinjection_gain(config.num_cells, visit + 1, scale=config.memory_scale)
|
| 596 |
+
state = (1 - gain) * state + gain * anchor
|
| 597 |
+
if self.input_adapter is not None:
|
| 598 |
+
state = self.input_adapter(state, anchor)
|
| 599 |
+
for index, cell in enumerate(self.core):
|
| 600 |
+
state, memory = call_cell(cell, state, ("core", index, visit), inputs, calls, memory)
|
| 601 |
+
if collect:
|
| 602 |
+
readouts.append(self.readout(state, visit, inputs, calls))
|
| 603 |
+
else:
|
| 604 |
+
for index, cell in enumerate(self.core):
|
| 605 |
+
for visit in range(depth):
|
| 606 |
+
state, _ = call_cell(cell, state, ("core", index, visit), inputs, calls)
|
| 607 |
+
hidden = readouts[-1] if collect else self.readout(state, 0, inputs, calls)
|
| 608 |
+
if cache is not None:
|
| 609 |
+
cache.advance(inputs["positions"], query_valid, self.cache_slots(depth))
|
| 610 |
+
return ModelOutput(
|
| 611 |
+
logits=None if return_hidden else self.lm_head(hidden), hidden_states=hidden,
|
| 612 |
+
visit_hidden_states=tuple(readouts),
|
| 613 |
+
hazard_logits=torch.stack([self.exit_gate(h).squeeze(-1) for h in readouts]) if collect else None,
|
| 614 |
+
**self.routing_statistics(calls, token_ids.device),
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
def routing_statistics(self, calls: list[CellCall], device: torch.device) -> dict[str, object]:
|
| 618 |
+
"""ModelOutput's routing fields; the auxiliary sums add the differentiated sparse calls in order."""
|
| 619 |
+
width = self.router_count_width
|
| 620 |
+
padded = [F.pad(call.counts, (0, width - call.width)) for call in calls]
|
| 621 |
+
first = {"prefix": 0, "core": len(self.prefix), "suffix": len(self.prefix) + len(self.core)}
|
| 622 |
+
per_cell = [torch.zeros(width, dtype=torch.long, device=device)
|
| 623 |
+
for _ in range(len(self.prefix) + len(self.core) + len(self.suffix))]
|
| 624 |
+
for row, call in zip(padded, calls): # one row per physical cell
|
| 625 |
+
owner = first[call.slot[0]] + call.slot[1]
|
| 626 |
+
per_cell[owner] = per_cell[owner] + row
|
| 627 |
+
auxiliary = [call for call in calls if call.width and call.differentiated]
|
| 628 |
+
zero = torch.zeros((), dtype=torch.float32, device=device)
|
| 629 |
+
return dict(balance_sum=sum((call.balance for call in auxiliary), zero),
|
| 630 |
+
z_sum=sum((call.z_loss for call in auxiliary), zero), aux_calls=len(auxiliary),
|
| 631 |
+
router_counts=torch.stack(per_cell), router_call_counts=torch.stack(padded),
|
| 632 |
+
router_call_slots=tuple(call.slot for call in calls),
|
| 633 |
+
router_call_widths=tuple(call.width for call in calls))
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
# The same class under its former name: old scripts, pickles and checkpoints name it this way.
|
| 637 |
+
RecursiveLM = LoopedLM
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4bbfd277973958d3779fa93e59209e94d8e158be167cd534ac1709637f02f824
|
| 3 |
+
size 6540400392
|
moe.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, stateless sparse operators and their transparent PyTorch reference."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import TYPE_CHECKING, NamedTuple
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch import Tensor, nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from .model import ModelConfig
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Routing(NamedTuple):
|
| 16 |
+
ids: Tensor
|
| 17 |
+
weights: Tensor
|
| 18 |
+
balance: Tensor
|
| 19 |
+
z_loss: Tensor
|
| 20 |
+
counts: Tensor
|
| 21 |
+
dispatch_counts: Tensor
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Router(nn.Module):
|
| 25 |
+
"""FP32 softmax top-k with selected-set normalization and dropless routing.
|
| 26 |
+
|
| 27 |
+
Balance/z terms are per-call valid-input means. Dispatch counts include all
|
| 28 |
+
rows, whereas auxiliary counts exclude padding. No persistent counters are
|
| 29 |
+
mutated, including during activation-checkpoint replay.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, config: "ModelConfig") -> None:
|
| 33 |
+
super().__init__()
|
| 34 |
+
self.gate = nn.Linear(config.dim, config.num_experts, bias=False)
|
| 35 |
+
self.top_k = config.top_k
|
| 36 |
+
|
| 37 |
+
def forward(self, x: Tensor, router_mask: Tensor | None = None) -> Routing:
|
| 38 |
+
shape = x.shape[:-1]
|
| 39 |
+
if router_mask is None:
|
| 40 |
+
router_mask = torch.ones(shape, dtype=torch.bool, device=x.device)
|
| 41 |
+
if router_mask.shape != shape or router_mask.dtype != torch.bool:
|
| 42 |
+
raise ValueError("router_mask must be bool and match the input token dimensions")
|
| 43 |
+
with torch.autocast(device_type=x.device.type, enabled=False):
|
| 44 |
+
logits = F.linear(x.float(), self.gate.weight.float())
|
| 45 |
+
probs = logits.softmax(-1)
|
| 46 |
+
selected, ids = probs.topk(self.top_k, dim=-1, sorted=False)
|
| 47 |
+
weights = selected / selected.sum(-1, keepdim=True)
|
| 48 |
+
experts = probs.size(-1)
|
| 49 |
+
dispatch_counts = torch.bincount(ids.reshape(-1), minlength=experts)
|
| 50 |
+
assignment_mask = router_mask.unsqueeze(-1).expand_as(ids).reshape(-1)
|
| 51 |
+
counts = torch.zeros(experts, dtype=torch.long, device=x.device)
|
| 52 |
+
counts.scatter_add_(0, ids.reshape(-1), assignment_mask.long())
|
| 53 |
+
valid = router_mask.float()
|
| 54 |
+
denominator = valid.sum().clamp_min(1)
|
| 55 |
+
probability_mean = (probs * valid.unsqueeze(-1)).sum(tuple(range(probs.ndim - 1))) / denominator
|
| 56 |
+
load = counts.float() / (denominator * self.top_k)
|
| 57 |
+
balance = experts * (load * probability_mean).sum()
|
| 58 |
+
z_loss = (logits.logsumexp(-1).square() * valid).sum() / denominator
|
| 59 |
+
return Routing(ids, weights.to(x.dtype), balance, z_loss, counts, dispatch_counts)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class DenseFFN(nn.Module):
|
| 63 |
+
def __init__(self, dim: int, hidden_dim: int) -> None:
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
|
| 66 |
+
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
|
| 67 |
+
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
|
| 68 |
+
|
| 69 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 70 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class ExpertBank(nn.Module):
|
| 74 |
+
"""Packed physical expert owners; no token dropping or hidden capacity.
|
| 75 |
+
|
| 76 |
+
This deliberately readable reference loops over experts. The finite native
|
| 77 |
+
training binding uses the same tensors with a grouped kernel/dispatcher.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def __init__(self, config: "ModelConfig") -> None:
|
| 81 |
+
super().__init__()
|
| 82 |
+
self.w1_EFD = nn.Parameter(torch.empty(config.num_experts, config.hidden_dim, config.dim))
|
| 83 |
+
self.w3_EFD = nn.Parameter(torch.empty(config.num_experts, config.hidden_dim, config.dim))
|
| 84 |
+
self.w2_EDF = nn.Parameter(torch.empty(config.num_experts, config.dim, config.hidden_dim))
|
| 85 |
+
|
| 86 |
+
def forward(
|
| 87 |
+
self, x: Tensor, ids: Tensor, weights: Tensor, dispatch_counts: Tensor | None = None,
|
| 88 |
+
) -> Tensor:
|
| 89 |
+
flat = x.reshape(-1, x.size(-1))
|
| 90 |
+
ids, weights = ids.reshape(flat.size(0), -1), weights.reshape(flat.size(0), -1)
|
| 91 |
+
output = torch.zeros_like(flat)
|
| 92 |
+
for expert in range(self.w1_EFD.size(0)):
|
| 93 |
+
rows, choices = torch.where(ids == expert)
|
| 94 |
+
tokens = flat[rows]
|
| 95 |
+
hidden = F.silu(F.linear(tokens, self.w1_EFD[expert])) * F.linear(tokens, self.w3_EFD[expert])
|
| 96 |
+
update = F.linear(hidden, self.w2_EDF[expert])
|
| 97 |
+
output.index_add_(0, rows, update * weights[rows, choices, None])
|
| 98 |
+
return output.view_as(x)
|
release_provenance.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"conversion": "Original HF tensors serialized as a model-only torch bridge, strictly loaded and saved by the unchanged release export_checkpoint.",
|
| 3 |
+
"driver_sha256": "3238da706a44295ebdc8f4024de6e68d9c95e52e3450829acab1cecba7c7ce52",
|
| 4 |
+
"format": "looptitan-hf-repackage",
|
| 5 |
+
"original_checkpoint_metadata": {
|
| 6 |
+
"format": "dcp",
|
| 7 |
+
"key_layout": "native_grouped",
|
| 8 |
+
"metadata_sha256": "37635adda5db1a863379a4e3d9d29efc07724a3c21651e1888684594084ac4c0",
|
| 9 |
+
"name": "step-4769"
|
| 10 |
+
},
|
| 11 |
+
"original_export_code_commit": "63a0953cc1ed6b9401018907a6d78d79cef07439",
|
| 12 |
+
"original_export_provenance_sha256": "b0d9f8839719fbd68d5d1f8bbc2aac743d0e96d2acf048225a5bdc225b911faf",
|
| 13 |
+
"original_mlflow_run_id": "906217a035ad40f09af6d917b7d2ee4e",
|
| 14 |
+
"original_training_code_commit": "63a0953cc1ed6b9401018907a6d78d79cef07439",
|
| 15 |
+
"original_weight_sha256": {
|
| 16 |
+
"model.safetensors": "4bbfd277973958d3779fa93e59209e94d8e158be167cd534ac1709637f02f824"
|
| 17 |
+
},
|
| 18 |
+
"recipe": "recipes/phase1/m3-adamw.json",
|
| 19 |
+
"release_commit": "49e0148bc2703af29d3abace9ee6ca8b69f5a5d6",
|
| 20 |
+
"release_repository": "https://github.com/datamllab/LoopTitan",
|
| 21 |
+
"version": 1,
|
| 22 |
+
"weight_bits_unchanged": true,
|
| 23 |
+
"weight_source": "Existing HF export from the original training run; no DCP checkpoint was read for this repackaging."
|
| 24 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506
|
| 3 |
+
size 11422650
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"backend": "tokenizers",
|
| 4 |
+
"bos_token": "<|im_end|>",
|
| 5 |
+
"bos_token_id": 151645,
|
| 6 |
+
"clean_up_tokenization_spaces": false,
|
| 7 |
+
"eos_token": "<|im_end|>",
|
| 8 |
+
"eos_token_id": 151645,
|
| 9 |
+
"errors": "replace",
|
| 10 |
+
"extra_special_tokens": [
|
| 11 |
+
"<|im_start|>",
|
| 12 |
+
"<|im_end|>",
|
| 13 |
+
"<|object_ref_start|>",
|
| 14 |
+
"<|object_ref_end|>",
|
| 15 |
+
"<|box_start|>",
|
| 16 |
+
"<|box_end|>",
|
| 17 |
+
"<|quad_start|>",
|
| 18 |
+
"<|quad_end|>",
|
| 19 |
+
"<|vision_start|>",
|
| 20 |
+
"<|vision_end|>",
|
| 21 |
+
"<|vision_pad|>",
|
| 22 |
+
"<|image_pad|>",
|
| 23 |
+
"<|video_pad|>"
|
| 24 |
+
],
|
| 25 |
+
"is_local": true,
|
| 26 |
+
"local_files_only": true,
|
| 27 |
+
"model_max_length": 131072,
|
| 28 |
+
"pad_token": "<|im_end|>",
|
| 29 |
+
"pad_token_id": 151645,
|
| 30 |
+
"split_special_tokens": false,
|
| 31 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 32 |
+
"unk_token": null
|
| 33 |
+
}
|