Publish reviewed PAT training and inference supplement
Browse filesFiles changed (50)
- .gitignoreAdded+15
- CHECKPOINTS.jsonAdded+19
- PAT-supplement.zipAdded+3
- PAT-supplement.zip.sha256Added+1
- README.mdAdded+246
- THIRD_PARTY_NOTICES.mdAdded+18
- THIRD_PARTY_NOTICES/tokenizer/LICENSEAdded+24
- configs/fa32.jsonAdded+96
- configs/fa32_200m.jsonAdded+96
- configs/pat32.jsonAdded+162
- configs/pat32_200m.jsonAdded+162
- docs/architecture.mdAdded+77
- docs/configuration.mdAdded+102
- docs/reproducibility.mdAdded+86
- docs/verification.jsonAdded+2121
- docs/verification.mdAdded+146
- pyproject.tomlAdded+37
- scripts/build_supplement.pyAdded+90
- scripts/train_fa32.shAdded+16
- scripts/train_fa32_200m.shAdded+17
- scripts/train_pat32.shAdded+16
- scripts/train_pat32_200m.shAdded+17
- src/pat/__init__.pyAdded+6
- src/pat/assets/tokenizer.jsonAdded
- src/pat/assets/tokenizer_contract.jsonAdded+21
- src/pat/assets/tokenizer_license.txtAdded+24
- src/pat/attention.pyAdded+195
- src/pat/checkpoint.pyAdded+171
- src/pat/config.pyAdded+118
- src/pat/data.pyAdded+202
- src/pat/generate.pyAdded+103
- src/pat/inference.pyAdded+116
- src/pat/kernels/__init__.pyAdded+1
- src/pat/kernels/attention.pyAdded
- src/pat/kernels/decoding.pyAdded+1415
- src/pat/kernels/layout.pyAdded+153
- src/pat/losses.pyAdded+42
- src/pat/model.pyAdded+284
- src/pat/packing.pyAdded+161
- src/pat/pat_cache.pyAdded+175
- src/pat/prepare.pyAdded+83
- src/pat/rotary.pyAdded+64
- src/pat/serve.pyAdded+68
- src/pat/tokenizer.pyAdded+46
- src/pat/train.pyAdded+275
- src/pat/training.pyAdded+145
- tests/test_checkpoint.pyAdded+59
- tests/test_data.pyAdded+80
- tests/test_generation.pyAdded+49
- tests/test_training.pyAdded+125
123456789101112131415__pycache__/*.py[cod].pytest_cache/.ruff_cache/*.egg-info/build/dist/.venv/data/runs/checkpoints/*.pt*.safetensors*.log.env12345678910111213141516171819{ "schema": "pat-checkpoint-locations-1", "checkpoints": { "PAT-32": { "repo_id": "ICLRPAT27/PAT-32", "revision": "3b88d323731efcac57bf6df2fa6b2aa22a93c792", "url": "https://huggingface.co/ICLRPAT27/PAT-32/tree/3b88d323731efcac57bf6df2fa6b2aa22a93c792", "weights_sha256": "be0a5fd13fbd6d80f8a488f25446a5db246c01c0090c22656d0eda91a344a5e3", "manifest_sha256": "ef2a16983101a74705370c998dbcea80fce023696d52014d1d18485330816717" }, "FA-32": { "repo_id": "ICLRPAT27/FA-32", "revision": "b71320e3a015dc94fc1147fe8891ebd46dfd429f", "url": "https://huggingface.co/ICLRPAT27/FA-32/tree/b71320e3a015dc94fc1147fe8891ebd46dfd429f", "weights_sha256": "994d4b7dcd1ff6a2a612860cf3c9efe096a1739561ac3714f032ffd9a17aa17f", "manifest_sha256": "3e8271c53d211e914280bd51289a248e110f9820c35cbcd3ab499cecdff24aab" } }}123version https://git-lfs.github.com/spec/v1oid sha256:50be4bcbf963a2ba55b53d217a5c58282247bfc749a8eeee53bfefe953fbc765size 766320150be4bcbf963a2ba55b53d217a5c58282247bfc749a8eeee53bfefe953fbc765 PAT-supplement.zip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246# PAT
Training and inference code for the **Predictive Abstraction Transformer (PAT)** and its **full-attention (FA)** ablation. Both models share a Transformer backbone, tokenization, and document-preserving data convention. PAT replaces older lexical attention history with learned chunk memories. FA retains causal lexical attention.
Both models use fixed fused attention implementations: PAT's included kernels and FA's FlashAttention dispatch. The package makes the paper's main model easy to inspect, train, save, load, and generate from. The [architecture guide](docs/architecture.md) explains the fixed model choices; the [reproducibility guide](docs/reproducibility.md) records the training recipe and the [verification record](docs/verification.md) records measured checks and their limits.
## Installation
The anonymous [source repository](https://huggingface.co/ICLRPAT27/PAT-code) contains this code and documentation. Clone it before installing, or extract the supplied source ZIP and open its root directory:
```bashgit clone https://huggingface.co/ICLRPAT27/PAT-codecd PAT-code```
Use Python 3.11 or newer and an NVIDIA Hopper-or-newer CUDA GPU for PAT. The package pins PyTorch 2.11.0, Triton 3.6.0, and Liger Kernel 0.8.1. Install it from the repository root:
```bashpython -m venv .venvsource .venv/bin/activatepython -m pip install --upgrade pippython -m pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cu128python -m pip install -e .```
FA uses PyTorch's required FlashAttention dispatch; PAT uses the included Triton attention kernels. There is no attention implementation selector. Downloading, inspecting, and verifying checkpoint files do not require a GPU. See `pyproject.toml` for dependency pins and the [verification record](docs/verification.md) for measured checks. The CUDA 12.8 wheel installation follows the [official PyTorch instructions](https://pytorch.org/get-started/previous-versions/#v2110).
The CUDA runtime needs a compatible NVIDIA driver. PyTorch compilation also needs a working host C++ compiler. The first training call compiles projection components, and GPU kernels may compile on first use. Initial calls can therefore take longer. The provided training scripts require four visible GPUs for PAT-32 and two for FA-32; inference loads one checkpoint on one GPU.
## Checkpoints
The checkpoint release contains the paper's two 32-layer models with width 2048 and 32 attention heads. Each was trained to a target of 9.52B supervised lexical tokens and reached 9,520,047,061 tokens after its final complete update.
<!-- checkpoint-links:start -->
| Model | Parameters | Training target | Checkpoint publication ||---|---:|---:|---|| PAT-32 | approximately 1.715B | 9.52B tokens | [Pinned weights](https://huggingface.co/ICLRPAT27/PAT-32/tree/3b88d323731efcac57bf6df2fa6b2aa22a93c792) || FA-32 | approximately 1.715B | 9.52B tokens | [Pinned weights](https://huggingface.co/ICLRPAT27/FA-32/tree/b71320e3a015dc94fc1147fe8891ebd46dfd429f) |
Download either model at its immutable revision:
```bashpython -m pat.checkpoint download --repo ICLRPAT27/PAT-32 \ --revision 3b88d323731efcac57bf6df2fa6b2aa22a93c792 --output checkpoints/PAT-32python -m pat.checkpoint verify checkpoints/PAT-32```
```bashpython -m pat.checkpoint download --repo ICLRPAT27/FA-32 \ --revision b71320e3a015dc94fc1147fe8891ebd46dfd429f --output checkpoints/FA-32python -m pat.checkpoint verify checkpoints/FA-32```
<!-- checkpoint-links:end -->
Each bundle contains `config.json`, `model.safetensors`, `tokenizer.json`, `TOKENIZER_LICENSE.txt`, `metadata.json`, and `manifest.json`. Verification checks the file sizes, SHA256 hashes, and tokenizer identity before loading weights. The input/output embedding is tied and stored once. Inference bundles contain model weights; continuing an interrupted optimizer trajectory also requires the trainer's resume state.
Immutable checkpoint locations and hashes are recorded in [CHECKPOINTS.json](CHECKPOINTS.json).
## Generate text
```bashpython -m pat.generate \ --checkpoint checkpoints/PAT-32 \ --prompt "A useful way to understand attention is" \ --max-new-tokens 128 \ --temperature 0```
Change the checkpoint directory to run FA. Temperature zero selects greedy decoding. For sampled output, use a positive temperature and a top-p value:
```bashpython -m pat.generate \ --checkpoint checkpoints/PAT-32 \ --prompt "The experiment began with" \ --max-new-tokens 128 \ --temperature 0.8 \ --top-p 0.95```
These are pretrained continuation models. Enter plain text; there is no chat template or instruction-tuning convention. Generation preserves document boundaries and suppresses internal packing, memory, and vocabulary-padding entries. Use the bundled tokenizer to retain the checkpoint's exact vocabulary.
The checked continuations include repetition and factual errors. Numerical comparisons verify that the release preserves the original checkpoints' behavior; they do not establish answer quality. See the [measured generation checks](docs/verification.md#measured-gpu-checks).
Generation prefills a persistent cache and updates it one token at a time. FA caches its attention keys and values. PAT retains the current lexical window and completed chunks' memory states; prompt ingestion uses the same incremental computation as decoding. Prompt tokens, the requested continuation, and the initial BOS must fit the configured context length. The implementation checks numerical behavior; this supplement does not reproduce the paper's optimized prefill or cached-decoding throughput benchmarks.
## Prepare training data
Provide UTF-8 JSON Lines with one complete document per row:
```json{"text": "The first document's text goes here."}{"text": "Another independent document goes here."}```
Prepare the training and validation sets separately:
```bashpython -m pat.prepare \ --input train.jsonl \ --output data/train \ --context-length 16384
python -m pat.prepare \ --input val.jsonl \ --output data/val \ --context-length 16384```
Preparation uses the bundled byte-pair tokenizer, preserves token order, and divides long documents into consecutive pieces. Each piece receives BOS; only the final piece of a document receives EOD. Training packs pieces efficiently while keeping their attention histories independent. The final shorter piece is retained.
This command prepares supplied text. The [reproducibility guide](docs/reproducibility.md#data-construction) describes the paper corpus and holdout. Matching its numerical results requires the same selected documents, tokenizer, data ordering, batching, and prepared-artifact identities.
## Train
The 32-layer launch scripts use the published distributed layout:
```bashDATA=data/train VALIDATION=data/val OUTPUT=runs/pat32 bash scripts/train_pat32.shDATA=data/train VALIDATION=data/val OUTPUT=runs/fa32 bash scripts/train_fa32.sh```
PAT-32 uses four GPUs with one 25000-token microbatch per rank. FA-32 uses two GPUs with two accumulation microsteps per update. Both target approximately 100000 supervised lexical tokens per global optimizer update. An individual packed microbatch can contain slightly fewer tokens. These launch settings are part of the training configuration, not a guarantee that the model fits every GPU with a given product name.
The corresponding direct invocation is:
```bashtorchrun --standalone --nproc_per_node=4 -m pat.train \ --config configs/pat32.json \ --data data/train \ --validation data/val \ --output runs/pat32```
Each configuration contains a `model` object and a `training` object. See the [configuration reference](docs/configuration.md) for their meanings. The trainer fixes the optimizer family, precision, gradient clipping, and attention implementation to the released recipe. Model depth, width, context span, memory allocation, token horizon, and token batching remain explicit.
Resume an interrupted training run from its saved training state:
```bashTRAINING_STATE="runs/pat32/$(cat runs/pat32/latest.txt)"torchrun --standalone --nproc_per_node=4 -m pat.train \ --config configs/pat32.json \ --data data/train \ --validation data/val \ --output runs/pat32 \ --resume "$TRAINING_STATE"```
`latest.txt` names the most recent complete checkpoint directory, which contains both model weights and `training.pt`. To start a new optimization trajectory from model weights, use `--init-checkpoint checkpoints/PAT-32`. Initializing from weights does not restore optimizer moments, the learning-rate clock, or the data cursor. Preserve the original model and training configuration when resuming an existing trajectory.
Resume restores model weights, optimizer state, random-number state, and the exact data cursor. Validation and periodic checkpoint intervals restart from the restored token count, so their timing can shift when the saved checkpoint falls between those intervals. The training token clock and batch order remain unchanged.
For the 200M-token checks of the actual released checkpoints:
```bashDATA=data/train VALIDATION=data/val CHECKPOINT=checkpoints/PAT-32 \ OUTPUT=runs/pat32-200m bash scripts/train_pat32_200m.sh
DATA=data/train VALIDATION=data/val CHECKPOINT=checkpoints/FA-32 \ OUTPUT=runs/fa32-200m bash scripts/train_fa32_200m.sh```
These use `configs/pat32_200m.json` and `configs/fa32_200m.json`. Each starts from the released weights with a fresh optimizer, a 200M-token total horizon, 100M-token warmup, and final 30% cooldown. They check continued-training stability of the released 32-layer models. They do not recreate the original 9.52B-token trajectory or resume its optimizer state. Separate numerical comparisons start the original and released implementations from identical weights and inputs; the 200M-token runs exercise the released implementation alone.
The 200M launch scripts always initialize a new run from weights. To resume one of these runs, invoke `pat.train` directly with its same 200M configuration and `--resume`; omit `--init-checkpoint`, since the two options are mutually exclusive.
<!-- completed-continuation-checks:start -->The released implementation completed continued-training checks of both actual 32-layer checkpoints: PAT-32 reached 200,087,827 lexical tokens, FA-32 reached 200,087,827 lexical tokens. Final endpoint reload/generation and full-model resume state checks also completed. The [verification record](docs/verification.md) reports exact scopes and numerical limits, including the strict small-PAT validation criterion that remained unmet.<!-- completed-continuation-checks:end -->
`--tokens` overrides the complete schedule horizon for a new run. Resuming an existing run must preserve its declared horizon.
## Python API
```pythonfrom pat.checkpoint import load_checkpoint, save_checkpoint, verify_checkpointfrom pat.generate import generatefrom pat.tokenizer import Tokenizer
verify_checkpoint("checkpoints/PAT-32")model = load_checkpoint("checkpoints/PAT-32", device="cuda")tokenizer = Tokenizer("checkpoints/PAT-32/tokenizer.json")
result = generate( model, "A useful way to understand attention is", tokenizer=tokenizer, max_new_tokens=128, temperature=0,)print(result["text"])
# Writes a new directory and preserves the exact model configuration.save_checkpoint(model, "checkpoints/PAT-32-copy")```
`PATConfig` and `PATModel` are the public configuration and model classes. Checkpoint loading selects PAT or FA from the saved configuration. The [configuration reference](docs/configuration.md) documents model construction and the [architecture guide](docs/architecture.md) explains the corresponding computations.
For token-level integration, `pat.inference.create_cache(model, prompt_ids, capacity)` returns a cache with `next_token_logits` and `append(token_id)`. Call it inside `torch.inference_mode()` and CUDA BF16 autocast. Capacity includes BOS and all tokens ingested by the cache; it cannot exceed the model's context length. Stop when EOD is selected, and append only ordinary text tokens. The higher-level `generate` function handles these boundaries and sampling.
## Serve locally
```bashpython -m pat.serve --checkpoint checkpoints/PAT-32 --port 8000```
The server exposes the same text-continuation behavior as the generation command:
```bashcurl http://127.0.0.1:8000/generate \ -H 'Content-Type: application/json' \ -d '{"prompt":"A useful way to understand attention is","max_new_tokens":64,"temperature":0,"top_p":0.95}'```
Run one model per server process. The server binds to `127.0.0.1`; `--port` changes its port. Responses contain continuation `text`, `token_ids`, `prompt_tokens`, `generated_tokens`, and `stop_reason`. `GET /health` reports readiness and the loaded architecture.
## Code map
| Location | Responsibility ||---|---|| `src/pat/config.py` | Validated model configuration || `src/pat/model.py` | Shared backbone and PAT/FA model behavior || `src/pat/losses.py` | Fixed fused PAT training loss || `src/pat/kernels/` | Required attention and layout operations || `src/pat/tokenizer.py` | Exact bundled tokenizer and special IDs || `src/pat/checkpoint.py` | Portable tensor checkpoints, hashes, and downloads || `src/pat/prepare.py` | Document-preserving data preparation || `src/pat/train.py` | Training, validation, checkpointing, and resume || `src/pat/inference.py` | Cache API and FA cached attention || `src/pat/pat_cache.py` | PAT lexical and memory cache || `src/pat/generate.py` | Text generation || `src/pat/serve.py` | Local inference service || `configs/` | Annotated by the configuration reference || `scripts/` | Reproducible training launches || `tests/` | Implementation and checkpoint checks |
## Verification and reporting
The [reproducibility guide](docs/reproducibility.md#required-release-verification) distinguishes archived paper results from new measurements. Release claims must identify the checked checkpoint, source version, token horizon, runtime, and measured numerical tolerances. A successful short training check does not establish reproduction of a multi-billion-token endpoint.
Each Python command provides `--help`. Launch scripts require the environment variables shown in their examples. Checkpoint integrity errors, incompatible model configurations, missing FlashAttention, and unavailable CUDA should fail explicitly rather than selecting another implementation.
To inspect the source-archive contents, run `python scripts/build_supplement.py --list`. `python scripts/build_supplement.py --output dist/PAT-supplement.zip` writes a ZIP with an internal SHA256 manifest and an external archive checksum. The allowlist includes source, documentation, configurations, tests, and the tokenizer; checkpoints are separate artifacts. Preserve the [third-party notices](THIRD_PARTY_NOTICES.md) when distributing the package.
Identify the code release by the source ZIP's external checksum and its immutable hosted revision. The internal manifest identifies the included files; individual verification runs also record their executed source snapshots. See [code identity](docs/verification.md#identifying-the-released-code).123456789101112131415161718# Third-party notices
The bundled byte-pair vocabulary and merge table are derived from the upstreamOpenAI GPT-2 tokenizer. The checkpoint-compatible serialization also recordsthe document and packing IDs used by this package. Its original license isretained in [the tokenizer license](THIRD_PARTY_NOTICES/tokenizer/LICENSE).
Upstream source: <https://github.com/openai/gpt-2>.The tokenizer is included for exact input compatibility. No upstream modelweights or model implementation are included.
PyTorch, Triton, Liger Kernel, NumPy, Safetensors, Tokenizers, and Hugging Face Hub areinstalled dependencies. Their own distributions supply their respectivelicenses. This source archive does not bundle those dependency distributions.
The original project source did not include a project-wide license grant.This document preserves the included third-party attribution and does notassign a new license to the PAT source or checkpoint weights.123456789101112131415161718192021222324Modified MIT License
Software Copyright (c) 2019 OpenAI
We don’t claim ownership of the content you create with GPT-2, so it is yours to do with as you please.We only ask that you use GPT-2 responsibly and clearly indicate your content was created using GPT-2.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software andassociated documentation files (the "Software"), to deal in the Software without restriction,including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,subject to the following conditions:
The above copyright notice and this permission notice shall be includedin all copies or substantial portions of the Software.The above copyright notice and this permission notice need not be includedwith content created by the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERSBE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USEOR OTHER DEALINGS IN THE SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596{ "model": { "architecture": "FA", "d_model": 2048, "n_heads": 32, "n_layers": 32, "vocab_size": 50304, "chunk_size": 16, "context_length": 16384, "memory_slots": [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "ffw_mult_by_layer": [ 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0 ], "qk_key_counts": [], "qk_reference_key_counts": [], "seed": 42, "ce_chunk_size": 4096 }, "training": { "tokens": 9520000000, "warmup_tokens": 100000000, "decay_fraction": 0.3, "learning_rate": 0.00025, "min_lr_ratio": 0.1, "weight_decay": 0.01, "microbatch_tokens": 25000, "accumulation_steps": 2, "seed": 42, "checkpoint_every": 100000000, "validate_every": 200000000 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596{ "model": { "architecture": "FA", "d_model": 2048, "n_heads": 32, "n_layers": 32, "vocab_size": 50304, "chunk_size": 16, "context_length": 16384, "memory_slots": [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "ffw_mult_by_layer": [ 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0 ], "qk_key_counts": [], "qk_reference_key_counts": [], "seed": 42, "ce_chunk_size": 4096 }, "training": { "tokens": 200000000, "warmup_tokens": 100000000, "decay_fraction": 0.3, "learning_rate": 0.00025, "min_lr_ratio": 0.1, "weight_decay": 0.01, "microbatch_tokens": 25000, "accumulation_steps": 2, "seed": 42, "checkpoint_every": 100000000, "validate_every": 200000000 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162{ "model": { "architecture": "PAT", "d_model": 2048, "n_heads": 32, "n_layers": 32, "vocab_size": 50304, "chunk_size": 16, "context_length": 16384, "memory_slots": [ 2, 2, 2, 2, 2, 2, 2, 2, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 2, 2, 2, 2, 2, 2, 2, 2 ], "ffw_mult_by_layer": [ 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0 ], "qk_key_counts": [ 16.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0 ], "qk_reference_key_counts": [ 16.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0 ], "seed": 42, "ce_chunk_size": 16384 }, "training": { "tokens": 9520000000, "warmup_tokens": 100000000, "decay_fraction": 0.3, "learning_rate": 0.00025, "min_lr_ratio": 0.1, "weight_decay": 0.01, "microbatch_tokens": 25000, "accumulation_steps": 1, "seed": 42, "checkpoint_every": 100000000, "validate_every": 200000000 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162{ "model": { "architecture": "PAT", "d_model": 2048, "n_heads": 32, "n_layers": 32, "vocab_size": 50304, "chunk_size": 16, "context_length": 16384, "memory_slots": [ 2, 2, 2, 2, 2, 2, 2, 2, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 2, 2, 2, 2, 2, 2, 2, 2 ], "ffw_mult_by_layer": [ 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0 ], "qk_key_counts": [ 16.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 7448.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0 ], "qk_reference_key_counts": [ 16.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0, 1874.0 ], "seed": 42, "ce_chunk_size": 16384 }, "training": { "tokens": 200000000, "warmup_tokens": 100000000, "decay_fraction": 0.3, "learning_rate": 0.00025, "min_lr_ratio": 0.1, "weight_decay": 0.01, "microbatch_tokens": 25000, "accumulation_steps": 1, "seed": 42, "checkpoint_every": 100000000, "validate_every": 200000000 }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677# Architecture
**PAT** means **Predictive Abstraction Transformer**. **FA** means **full attention**. FA is the attention ablation: it uses the same Transformer backbone and document-preserving input convention, replacing PAT's attention with causal full attention.
## Shared backbone
| Component | Setting ||---|---|| Block organization | Pre-normalized attention and feedforward residual blocks || Normalization | LayerNorm, epsilon 1e-6 || Position encoding | Rotary positions, base 10000, full head dimension || Feedforward network | SwiGLU; hidden width approximately 8d/3, rounded to a multiple of 8 || Attention heads | Head dimension 64 in the paper configurations || Attention normalization | L2-normalized queries and keys; learned positive scale per head || Biases | Enabled || Dropout | Zero || Embeddings | Input and output weights tied || Vocabulary/output dimension | 50304, including padding and special entries |
Packing combines document pieces for efficient execution while preserving independent attention histories. Packing does not grant one document access to another.
Training targets are the original piece's text tokens and its terminal EOD, when present. FA uses `[BOS] + piece[:-1]` as input and the complete piece as its next-token targets. PAT frames the complete piece before inserting memory rows, with no prediction target on those rows. During generation both models use `[BOS] + prefix`; the final prefix position predicts the next text token or EOD. These distinctions preserve the projection and attention shapes used by the released checkpoints.
## PAT attention
PAT divides the framed input into chunks of 16 tokens, including BOS and any terminal EOD. Each chunk has a small group of memory states. These states summarize information needed for future-token prediction; they receive gradients through that prediction objective and have no direct prediction targets.
Within a layer, a lexical query reads its recent causal lexical window and memories from eligible completed chunks. A memory query reads its completed chunk, earlier memories, and its own memory group bidirectionally. All sources are layer inputs. A memory written in one layer becomes readable in the next layer, so lexical and memory queries can run in parallel during training. The first layer omits earlier-memory reads because its initial memory states have not yet encoded the input.
Tokens and memory states share attention projections. Memory states participate in the attention residual update and bypass the feedforward network. Completed chunks' memories provide historical keys and values; a local lexical window preserves recent token detail.
The source groups participate in **one attention normalization**. If separate kernel calls return outputs `o_b` and log normalizers `z_b`, the combined output is:
```textz = logsumexp_b(z_b)o = sum_b(exp(z_b - z) * o_b)```
Adding independently normalized attention outputs would implement a different model.
## Memory allocation through depth
The paper profile assigns two slots to the first `floor(L/4)` blocks, eight to the next `floor(L/2)` blocks, and two to the remaining blocks. For 32 blocks the allocation is:
```textblocks 1–8: 2 memory slots per chunkblocks 9–24: 8 memory slots per chunkblocks 25–32: 2 memory slots per chunk```
The average is five slots per 16-token chunk. Five is an average across depth, not the slot count in every block.
At a change in allocation, a learned linear map changes the slot count independently for each contiguous feature group of head width. Each group starts with the same interpolation map and then trains independently. The original bank supplies historical keys and values; resized states supply local queries, keys, and values. Changing the number of local writers therefore does not also resize the history they read.
Rotary positions preserve the chronological order of lexical tokens and memory groups. Keys in a memory group share a chunk position, while different writers have distinct query offsets. Resizing preserves existing lexical and chunk-key positions.
## Fixed numerical choices
The released PAT implementation fixes relative rotary products, grouped memory transitions, calibrated query/key scale initialization, and the paper's memory write/read rules. These are architectural behavior, not selectable execution alternatives. PAT uses the included fused Triton kernels and FA uses PyTorch's FlashAttention dispatch.
PAT training uses Liger Kernel 0.8.1 for the fused vocabulary projection and cross entropy, with FP32 loss accumulation. FA uses its ordinary vocabulary projection and cross entropy under BF16 autocast. These loss paths are fixed by architecture. The supplied loss chunk sizes preserve the projection and reduction shapes used for numerical comparisons.
Linear and embedding weights start with standard deviation 0.02. Residual output projections use `0.02 / sqrt(2L)`; biases start at zero and LayerNorm gains at one. Memory slots initially share the same learned memory-token embedding. Transitions start from a constant-preserving interpolation map with deterministic zero-row-sum perturbations of relative row norm 0.01.
Query/key scales start at 10 when the visible-key count is unchanged. For affected PAT layers, the initialization is:
```textscale = 10 * log(K * (K - 1)) / log(K_reference * (K_reference - 1))```
The first layer retains scale 10. The paper's 16K main-training calibration uses `K=7448` and `K_reference=1874` in affected layers, giving approximately 11.8314. Counts come from the training distribution and attention masks; a different geometry or corpus requires corresponding calibration. Restoring a checkpoint restores its learned scales.
## What remains configurable
Depth, width, head count, context span, and memory allocation determine model capacity and must be recorded in each checkpoint. The paper launch configurations supply their published values. Training also records its data identity, tokenizer identity, global token target, effective update size, optimizer settings, learning-rate schedule, and seed.
A checkpoint's architecture is authoritative when loading it. Changing geometry is a new model and is not a checkpoint-resume operation.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# Configuration and API reference
Training JSON files contain `model` and `training` objects. Inference checkpoint `config.json` files contain only the model object. The checkpoint loader reconstructs that exact model before loading learned tensors.
## Model fields
| Field | Meaning | Paper configuration ||---|---|---|| `architecture` | Selects the model family | `PAT` or `FA` || `d_model` | Hidden-state width | 2048 for the released pair || `n_heads` | Number of attention heads | 32 for the released pair || `n_layers` | Number of Transformer blocks | 32 for the released pair || `vocab_size` | Size of the output head and embedding | 50304 || `chunk_size` | Framed input positions per PAT chunk, including document markers | 16 || `context_length` | Maximum lexical tokens per training piece; generation admits BOS and content within this span | 16384 || `memory_slots` | Number of memory rows written by each layer | PAT: eight 2s, sixteen 8s, eight 2s; FA: 32 zeros || `ffw_mult_by_layer` | Feedforward capacity multiplier for each layer | 4.0 per layer; SwiGLU uses two-thirds of this intermediate width, rounded to a multiple of 8 || `qk_key_counts` | Per-layer training-calibrated visible-key counts | Supplied by the PAT configuration || `qk_reference_key_counts` | Corresponding two-slot reference counts | Supplied by the PAT configuration || `seed` | Initialization seed | 42 || `ce_chunk_size` | Rows per explicit vocabulary projection/loss call: FA training and validation for both models | PAT-32: 16384; FA-32: 4096 |
`ce_chunk_size` controls explicit projection workspace and does not shorten attention context. PAT training uses its fixed fused loss, whose workspace is managed internally. Preserve the checkpoint recipe's value for numerical comparisons, because changing projection and reduction shapes can change floating-point results. Width must divide evenly into heads. Supported head dimensions are divisible by four and between 20 and 128. The context span must be a multiple of the chunk size and contain at least four chunks. Chunk sizes 16 and 32 are supported by the implementation; the released paper configuration uses 16.
Memory and feedforward arrays have one value per layer. PAT requires positive slot counts and calibrated key-count arrays. FA has zero memory slots and no calibration arrays; its learned QK scales initialize to 10. Do not reuse another geometry's calibration without measuring the corresponding training-mask counts.
Use the supplied configurations when reproducing the paper. The configuration class permits other valid geometry for new experiments, but the class defaults do not claim to define the paper's complete recipe.
## Training fields
| Field | Meaning | Paper setting ||---|---|---|| `tokens` | Complete supervised-lexical-token horizon | 9520000000 for the released pair || `warmup_tokens` | Linear warmup duration | 100000000 || `decay_fraction` | Final fraction of the horizon devoted to cosine cooldown | 0.3 || `learning_rate` | Peak learning rate | 0.00025 || `min_lr_ratio` | Final learning rate divided by peak | 0.1 || `weight_decay` | AdamW weight decay on decayed parameters | 0.01 || `microbatch_tokens` | Approximate lexical tokens packed on each rank per microstep | 25000 || `accumulation_steps` | Microsteps per optimizer update on each rank | PAT-32: 1 with four ranks; FA-32: 2 with two ranks || `seed` | Training seed | 42 || `checkpoint_every` | Lexical-token interval between saved training states | 100000000 || `validate_every` | Lexical-token interval between validation passes | 200000000 |
The effective global update is approximately `world_size * microbatch_tokens * accumulation_steps`. Actual packed lexical counts govern training progress. The trainer fixes BF16 computation, fused AdamW with beta values `(0.9, 0.999)` and epsilon `1e-8`, and global gradient-norm clipping at `1.0`. Biases, normalization parameters, and learned QK scales are excluded from weight decay.
`pat32_200m.json` and `fa32_200m.json` retain the released model geometry and distributed batching, changing the new-run horizon to 200000000 tokens. Their launch scripts initialize from the actual released checkpoint weights with a fresh optimizer. They are bounded continued-training checks, not reconstructions of the original pretraining trajectory.
The [reproducibility guide](reproducibility.md#paper-training-recipe) gives the fixed PAT and FA objective weighting. Keeping model geometry alone unchanged does not establish an identical optimizer trajectory if batching, world size, data order, or the total schedule changes.
## Model API
```pythonimport jsonimport torchfrom pat import PATConfig, PATModel
with open("configs/pat32.json") as stream: configuration = json.load(stream)config = PATConfig.from_dict(configuration["model"])torch.manual_seed(config.seed)model = PATModel(config).cuda()```
`PATConfig.to_dict()` returns the serializable model configuration. `PATConfig.from_dict(...)` validates supplied fields. `PATModel(config)` builds PAT or FA according to `config.architecture`.
The forward API accepts document pieces:
```pythonfrom pat.tokenizer import Tokenizer
tokenizer = Tokenizer()piece_a = torch.tensor( tokenizer.encode("This is a complete document.") + [tokenizer.eod_token_id], dtype=torch.long, device="cuda",)piece_b = torch.tensor( tokenizer.encode("This document continues in another piece"), dtype=torch.long, device="cuda",)with torch.autocast("cuda", dtype=torch.bfloat16): output = model( pieces=[piece_a, piece_b], document_ends=[True, False], return_logits=False, )```
Each piece is a one-dimensional integer tensor on the model's device. Token content and an EOD marker on actual document ends are represented consistently with the prepared-data format. The model inserts BOS and the internal PAT layout. `document_ends` records which pieces end their document. The output exposes summed training loss and target count, summed lexical-only loss and lexical count, and optional logits/targets. Sum and count are separate so the trainer can apply the correct global objective and token-weighted metrics.
`pat.generate.generate(model, prompt, ...)` performs cached text continuation and handles sampling, internal-ID suppression, and document termination. For token-level use, `pat.inference.create_cache(model, prompt_ids, capacity)` exposes `next_token_logits` and `append(token_id)`. Use CUDA BF16 autocast and inference mode; capacity includes BOS and ingested text. EOD terminates the document and must not be appended. PAT prompt ingestion follows the same incremental cache computation as decoding.
## Checkpoint API
| Function | Purpose ||---|---|| `load_checkpoint(directory, device="cpu", dtype=None)` | Verify and load a model in evaluation mode; preserve stored precision unless a dtype is requested || `save_checkpoint(model, directory, metadata=None)` | Write a new inference bundle without overwriting an existing directory || `verify_checkpoint(directory)` | Check every listed file's size and SHA256 plus the tokenizer identity || `download_checkpoint(repo_id, revision, directory)` | Download an immutable Hub model revision, verify it, then install the directory |
These functions live in `pat.checkpoint`. A model-only bundle can initialize a new run. An exact resume additionally needs optimizer, random-number-generator, token-clock, and data-cursor state; use the trainer's complete saved directory with `--resume`.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Reproducibility
This supplement covers the main PAT and FA language-model training and inference implementations. The paper's main PAT configuration uses grouped memory transitions and calibrated query/key scale initialization. Earlier context experiments used a different transition-sharing and scale-initialization recipe; the fixed implementation in this supplement should not be described as reproducing that separate recipe.
## Paper training recipe
| Setting | Value ||---|---|| Initialization seed | 42 || Compute precision | bfloat16 || Optimizer | AdamW || Adam beta values | 0.9, 0.999 || Adam epsilon | 1e-8 || Weight decay | 0.01 || Global gradient norm clipping | 1.0 || Peak learning rate | 2.5e-4 || Final learning rate | 2.5e-5 || Warmup | First 100000000 supervised lexical tokens || Stable phase | Peak rate until 70% of the target token horizon || Cooldown | Cosine decay over the final 30% of the horizon || Effective optimizer update | Approximately 100000 supervised lexical tokens globally |
Warmup is part of the initial 70%, not an addition to the total horizon. Training stops after a complete optimizer update, so the realized token count can slightly exceed the requested horizon. Biases, normalization parameters, and learned query/key scales are excluded from weight decay.
The token clock and loss denominator serve different purposes. Supervised lexical tokens determine batching and learning-rate progress. Validation reports lexical-token loss with special targets excluded. Training preserves the exact objective used by each released model family, including their different weighting under accumulation.
For PAT, the objective is the sum of loss over all valid training targets divided by their count over the complete optimizer update, including all ranks and accumulation microsteps.
For FA, let `w` be the world size, `S_rm` the summed valid-target CE for rank `r` and microstep `m`, `C_m` the valid-target count across ranks in that microstep, `l_rm` that rank's lexical-token count, and `L` the lexical-token count across the complete optimizer update. The effective objective after distributed gradient averaging is:
```textFA objective = sum_(r,m) [w * l_rm / (C_m * L)] * S_rm```
On one rank, this is a lexical-count-weighted average of the microbatch valid-target mean losses. PAT instead uses `sum(S_rm) / sum(C_m)`. The distinction is fixed by model family to preserve checkpoint-training behavior; it is not an additional configuration option. Consequently, changing world size or accumulation can affect FA's objective when ranks contain different lexical and special-target proportions.
The implementation also preserves the arithmetic order: normalize each microstep's summed loss, then multiply by its accumulation weight. Distributed gradients synchronize after every microstep. Collapsing the factors or postponing communication until the final microstep can change floating-point results.
## Data construction
The paper uses approximately 100.001B content tokens, 44.05M documents, and 45.59M document pieces. The sources are FineWeb-Edu from [SmolLM-Corpus](https://huggingface.co/datasets/HuggingFaceTB/smollm-corpus) and the Algebraic Stack, arXiv, peS2o, and StarCoder components of [OLMo-Mix-1124](https://huggingface.co/datasets/allenai/olmo-mix-1124).
| Source | Approximate content tokens ||---|---:|| FineWeb-Edu | 49.827B || Algebraic Stack | 12.545B || arXiv | 12.543B || peS2o | 12.543B || StarCoder | 12.543B |
Selection uses seed 42. One branch selects 60B tokens without a minimum document length; another selects 40B additional tokens from documents of at least 8192 tokens. The first branch also contains long documents. Exact duplicates are removed across sources and exact validation copies are excluded. No additional near-duplicate filter is part of this construction.
Ordinary byte-pair encoding treats literal special-token spellings as ordinary source text. Document order is retained within each document. Long documents become consecutive pieces capped at 16384 content tokens, including the final shorter remainder. Every piece receives BOS; only a document's final piece receives EOD. PAT memory states are introduced by the model. Unrelated documents never share an attention history.
Batch planning groups pieces into length buckets of width 20 while measuring each bin's budget in lexical tokens. Training uses preallocated bins, deterministic seeded placement, and a final batch shuffle; overflow and incomplete distributed optimizer windows are dropped for that epoch. Validation uses its fixed preallocated placement order and adds overflow bins, preserving every held-out piece. Neither behavior is exposed as an alternative batching mode.
Reproducing the paper's numerical training trajectory requires the exact prepared-data artifacts and their order, tokenizer files, model initialization, and batching. A corpus with the same approximate mixture or token count is not sufficient evidence of the same trajectory.
## Validation
The fixed holdout contains 14633 FineWeb-Edu documents and 15002471 content tokens. The short subset contains 14508 documents and 13162292 tokens; the long subset contains 125 documents and 1840179 tokens, represented by 165 pieces. The combined loss is token-weighted, not the arithmetic mean of short and long losses. Perplexity is `exp(cross_entropy)`.
The released 32-layer checkpoint pair has width 2048, 32 heads, approximately 1.715B parameters, and target 9520000000 supervised lexical tokens. The archived runs reached 9520047061 tokens. Reported final validation values are reference measurements from those runs:
| Model | Combined CE | Short CE | Long CE ||---|---:|---:|---:|| PAT-32 | 2.5801864771 | 2.5948254182 | 2.4754781753 || FA-32 | 2.6116588581 | 2.6243801552 | 2.5206669348 |
These are archived paper-run values, not new continuation-training endpoints. The [verification record](verification.md) supplies checkpoint identities, measured loader/evaluation comparisons, observed archive differences, and the separate 200M-token continuation results.
## Required release verification
The [release verification record](verification.md) identifies executed source snapshots, runtime, GPU, input artifacts, checkpoint hashes, numerical limits, and measured outcomes for the following verification scope:
1. Import the selected PAT-32 and FA-32 checkpoints without missing or unexpected learned tensors.2. Compare logits and lexical loss against their original implementation over multiple chunk boundaries and variable-length document pieces.3. Compare generation before and after checkpoint export/reload, including prompts ending within and exactly at chunk boundaries.4. Verify causal behavior and isolation between packed documents.5. Run training and compare optimizer updates and loss progress using identical seeds, input order, and token accounting.6. Resume saved training and compare its continuation with an uninterrupted run.7. Complete 200M-token local continued-training checks starting from each actual released 32-layer checkpoint, and retain the logs, resulting checkpoints, and exact counts. These checks use a fresh optimizer, a 200M-token horizon, 100M-token warmup, and 30% cooldown. The long checks exercise the released implementation. Separate bounded comparisons check the original and released implementations from identical initial weights and inputs; a smaller model does not qualify the released pair.
A completed 200M-token check establishes continued-training stability over that horizon. It does not establish agreement between two complete 200M-token trajectories or that a fresh multi-billion-token training run reproduces the final paper loss. State separately which checks have completed, which used small fixtures, and which exercised the full released checkpoints.
The measured receipts distinguish completed checks from the strict small-PAT resume-validation criterion that remained unmet. Passing native-evaluation and full-model functional-resume controls do not erase that result or establish deterministic training trajectories. Final archive build and anonymous download identity are attested by the external publication receipt and checksum.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121{ "schema": "pat-release-verification-1", "release_status": "verification_complete_with_documented_limits", "code_revision": null, "runtime": { "python": "3.11", "pytorch": "2.11.0+cu128", "cuda_runtime": "12.8", "triton": "3.6.0", "gpu_model": "NVIDIA H100 80GB HBM3", "liger_kernel": "0.8.1" }, "artifacts": { "PAT-32": { "parameters": 1715105280, "layers": 32, "width": 2048, "heads": 32, "training_target_tokens": 9520000000, "actual_training_tokens": 9520047061, "training_updates": 95473, "weights_sha256": "be0a5fd13fbd6d80f8a488f25446a5db246c01c0090c22656d0eda91a344a5e3", "config_sha256": "7bf4b5edf135137208f17635cd6bf2acf02735025e479ea8000d54da872ec23b", "tokenizer_sha256": "67df57fd93740b7feb7462529fffb9edc0c7c9a30724489472385980b5bdd0b5", "anonymous_repository": "ICLRPAT27/PAT-32", "immutable_revision": "3b88d323731efcac57bf6df2fa6b2aa22a93c792" }, "FA-32": { "parameters": 1715104256, "layers": 32, "width": 2048, "heads": 32, "training_target_tokens": 9520000000, "actual_training_tokens": 9520047061, "training_updates": 95473, "weights_sha256": "994d4b7dcd1ff6a2a612860cf3c9efe096a1739561ac3714f032ffd9a17aa17f", "config_sha256": "a420973d4aeae5a2da9579b0c84d54e9c2e4055eb0e39b4a0cb9c782e92f939c", "tokenizer_sha256": "67df57fd93740b7feb7462529fffb9edc0c7c9a30724489472385980b5bdd0b5", "anonymous_repository": "ICLRPAT27/FA-32", "immutable_revision": "b71320e3a015dc94fc1147fe8891ebd46dfd429f" } }, "verification_data": { "training_lexical_tokens": 220000236, "validation_lexical_tokens": 15002471, "training_manifest_sha256": "06be2e727c9fd5ffcfd66cb0c7de3e1b6ee895283183eb0ec027c9d9b96223f7", "validation_manifest_sha256": "f98606cbb0be9a140555340c82a9dcfcdf4002c3dab7d49ea24e21fa605ea06e", "scope": "Real-text stored-order verification subset; not the full pretraining shuffle trajectory" }, "checks": { "cpu_tests": { "status": "passed", "tests": 29, "seconds": 5.6, "scope": "Tests run against the newly installed wheel outside the source tree" }, "lint": { "status": "passed", "command": "python -m ruff check src tests scripts" }, "batch_planner": { "status": "passed", "all_batch_indices_equal": true, "training_native_comparisons": 85, "validation_native_comparisons": 63 }, "checkpoint_export": { "status": "passed", "all_persisted_tensors_equal": true, "strict_cpu_loading": true, "tied_embedding_retained": true }, "ordinary_tokenization": { "status": "passed", "native_comparisons": 13, "special_spellings_are_ordinary_text": true }, "fresh_initialization": { "status": "passed", "architectures": [ "PAT", "FA" ], "scope": "Small configurations, including 2/8/2 PAT memory allocation", "all_mapped_tensors_equal": true }, "package_installation": { "passed": true, "installed_outside_source_tree": true, "imported_modules": [ "config", "model", "attention", "rotary", "packing", "losses", "inference", "pat_cache", "kernels.attention", "kernels.decoding" ], "cli_help_modules": [ "prepare", "train", "generate", "serve", "checkpoint" ], "all_installed_python_files_equal_source": true, "tokenizer_loads": true, "tokenizer_license_included": true, "wheel_sha256": "9e896cfaaefa8f8450bd8b523e1ebf0f147b7d4c05a0ac7fd2f7c7bded223148", "status": "passed", "scope": "Current core Python implementation installed from a wheel outside the source tree; installed Python bytes match the source" }, "source_archive_builder": { "status": "passed", "scope": "Deterministic builder fixture qualified; final archive construction and unauthenticated download are attested by the external publication receipt", "deterministic_bytes": true, "internal_checksums_verified": true, "private_files_excluded": true }, "pat_small_distributed_resume": { "status": "passed", "scope": "Small PAT configuration; not the released PAT-32 model", "world_size": 2, "updates": 5, "lexical_tokens": 1260, "maximum_absolute_weight_difference": 1.862645149230957e-09, "bitwise_equal": false }, "fa32_inference": { "status": "passed", "boundary_and_batch_cases": 8, "all_inference_logits_bitwise_equal": true, "next_token_logits_bitwise_equal": true, "real_text_long_pieces": [ { "lexical_tokens": 16123, "routed_tokens": 16124, "terminal_eod": true, "logits_bitwise_equal": true }, { "lexical_tokens": 16384, "routed_tokens": 16384, "terminal_eod": false, "logits_bitwise_equal": true } ], "generation_prompts": 3, "greedy_steps": 72, "all_generation_logits_bitwise_equal": true }, "fa32_fresh_process_compiled_training": { "status": "passed", "passed": true, "lexical_tokens": 143, "supervised_tokens": 144, "reference_loss": 3.5339269638061523, "release_loss": 3.5339269638061523, "gradient_tensors": 547, "exact_gradient_tensors": 546, "gradient_maximum_absolute_difference": 1.862645149230957e-09, "gradient_maximum_relative_l2_difference": 7.977480009913052e-09, "native_repeat_gradient_maximum_absolute_difference": 1.862645149230957e-09, "native_repeat_gradient_maximum_relative_l2_difference": 8.086514569072278e-09, "post_step_maximum_absolute_difference": 3.725290298461914e-09, "post_step_maximum_relative_l2_difference": 1.2048054394420138e-11, "gradient_norm": 3.858699083328247, "optimizer": "One fresh fused AdamW step, selective matrix weight decay, gradient clipping at 1.0", "compile_graph_breaks": 0, "compile_recompile_limit": 8, "scope": "Checkpoint import, compiled forward, original production cross entropy, backward, and one optimizer step; this does not establish a full training trajectory." }, "fa32_full_holdout_validation": { "passed": true, "complete": true, "total_lexical_tokens": 15002471, "dataset_manifest_sha256": "f98606cbb0be9a140555340c82a9dcfcdf4002c3dab7d49ea24e21fa605ea06e", "batch_budget": 25000, "ce_chunk_size": 4096, "long": { "pieces": 165, "batches": 85, "completed_batches": 85, "maximum_batch_mean_difference": 0.00033763724497741786, "archived_lexical_cross_entropy": 2.520666934779171, "archived_cross_entropy": 2.520749605516942, "native_plan_sha256": "13487683beea20fd17cdddf9b8ccf95f8d77e512f5df7f65f0860f9090b7d246", "native": { "cross_entropy": 2.520743082732527, "lexical_cross_entropy": 2.520660349991767, "targets": 1840304, "lexical_targets": 1840179 }, "release": { "cross_entropy": 2.520749605516942, "lexical_cross_entropy": 2.5206669517612146, "targets": 1840304, "lexical_targets": 1840179 }, "native_release_lexical_difference": 6.601769447556194e-06, "native_archived_lexical_difference": 6.584787403784986e-06, "release_archived_lexical_difference": 1.69820437712076e-08 }, "short": { "pieces": 14508, "batches": 527, "completed_batches": 527, "maximum_batch_mean_difference": 0.00035492901419716057, "archived_lexical_cross_entropy": 2.6243801552096704, "archived_cross_entropy": 2.6242535818754362, "native_plan_sha256": "609023b60fa4e577c171a0116694034e116f60e47c3057078b21428984703b46", "native": { "cross_entropy": 2.62425309718122, "lexical_cross_entropy": 2.6243796138905746, "targets": 13176800, "lexical_targets": 13162292 }, "release": { "cross_entropy": 2.6242535818754362, "lexical_cross_entropy": 2.6243801516483605, "targets": 13176800, "lexical_targets": 13162292 }, "native_release_lexical_difference": 5.377577858567406e-07, "native_archived_lexical_difference": 5.413190957703762e-07, "release_archived_lexical_difference": 3.5613099136355686e-09 } }, "fa_small_distributed_resume": { "status": "passed", "scope": "Small FA configuration; two accumulation microsteps per update, not released FA-32", "world_size": 2, "updates": 3, "lexical_tokens": 1512, "maximum_absolute_weight_difference": 1.0058283805847168e-07, "bitwise_equal": false }, "fa32_200m_continued_training": { "status": "passed", "complete": true, "target_lexical_tokens": 200000000, "realized_lexical_tokens": 200087827, "updates": 2006, "world_size": 2, "accumulation_steps": 2, "source_snapshot_sha256": "dc7e68f6dd6e63bfdc56b2fb8d4e230f9cf17f44530489027040ac1d24af9216", "training_data_manifest_sha256": "06be2e727c9fd5ffcfd66cb0c7de3e1b6ee895283183eb0ec027c9d9b96223f7", "validation_data_manifest_sha256": "f98606cbb0be9a140555340c82a9dcfcdf4002c3dab7d49ea24e21fa605ea06e", "initial_weights_sha256": "994d4b7dcd1ff6a2a612860cf3c9efe096a1739561ac3714f032ffd9a17aa17f", "final_weights_sha256": "1a4cc3df2d0cc680860918458c750e4cc32048c488544da0313bb53c05329a14", "final_training_state_sha256": "c6fc403b037ea871b9271e8f29bc8a047d67c5ffe98775e2d5a04781ef46ef4b", "final_checkpoint_manifest_sha256": "68f9a21aeb474c4c3e9c9729680211bb6d4b0093da4486681457e735f19530f7", "metrics_sha256": "1ab83bc457b68ba00000c21c679187bd073f75caed19e5ea2ba61c9ecd3485f7", "final_training_metrics": { "step": 2006, "tokens": 200087827, "lr": 2.5000021783021975e-05, "loss": 2.6272884369393523, "lexical_loss": 2.6270604653903242, "grad_norm": 0.1104343980550766 }, "final_validation": { "loss": 2.6396353375936368, "lexical_loss": 2.6396932363050394, "targets": 15017104, "lexical_targets": 15002471 }, "optimizer_parameter_states": 547, "all_recorded_losses_and_grad_norms_finite": true, "every_token_schedule_step_exact": true, "final_resume_manifest_verified": true, "completed_pacific": "2026-09-26 01:56:24 PDT", "final_checkpoint_is_published_original": false, "scope": "Continued training from the exact published original checkpoint with a new optimizer and 200M-token schedule. The run exercises the released implementation only; it does not compare two complete training trajectories or replace the published original checkpoint." }, "fa32_cached_inference": { "status": "passed", "scope": "Exact released FA-32 checkpoint; native production cache and release cache", "fixed_inference_arithmetic": "Eager projections with CUDA BF16 autocast and required FlashAttention", "prompt_length_cases": [ 1, 15, 16, 17, 31, 32, 33, 64 ], "all_prefill_logits_bitwise_equal": true, "append_steps": 32, "all_append_logits_bitwise_equal": true, "overflow_rejected_in_all_cases": true, "full_context_prefill": { "prompt_tokens": 16383, "exact": true, "max_abs": 0.0, "relative_l2": 0.0 }, "greedy_prompts": 3, "greedy_steps": 72, "all_greedy_logits_and_tokens_equal": true, "model_training_wrappers_already_compiled": true }, "pat32_full_holdout_validation": { "passed": true, "complete": true, "total_lexical_tokens": 15002471, "dataset_manifest_sha256": "f98606cbb0be9a140555340c82a9dcfcdf4002c3dab7d49ea24e21fa605ea06e", "batch_budget": 25000, "ce_chunk_size": 16384, "scope": "All 612 current source/public inclusive cross-entropy batch means are bitwise equal. Lexical totals differ by at most 1.07e-8 due to masked reduction association. Both current source and public lexical cross entropies are 7.87e-6 to 9.61e-6 below archived producer metrics; archive comparison passes the fixed 1e-4 absolute tolerance and is not bitwise reproduction. This evaluation covers checkpoint inference, not a training trajectory.", "compile_graph_breaks": 0, "long": { "pieces": 165, "batches": 85, "completed_batches": 85, "maximum_batch_mean_difference": 0.0, "archived_lexical_cross_entropy": 2.475478175288926, "archived_cross_entropy": 2.4755695084888147, "native_plan_sha256": "13487683beea20fd17cdddf9b8ccf95f8d77e512f5df7f65f0860f9090b7d246", "native": { "cross_entropy": 2.4755598888145656, "lexical_cross_entropy": 2.4754685846798057, "targets": 1840304, "lexical_targets": 1840179 }, "release": { "cross_entropy": 2.4755598888145656, "lexical_cross_entropy": 2.4754685740660283, "targets": 1840304, "lexical_targets": 1840179 }, "native_release_lexical_difference": 1.0613777412515901e-08, "native_archived_lexical_difference": 9.590609120202487e-06, "release_archived_lexical_difference": 9.601222897615003e-06 }, "short": { "pieces": 14508, "batches": 527, "completed_batches": 527, "maximum_batch_mean_difference": 0.0, "archived_lexical_cross_entropy": 2.5948254182288313, "archived_cross_entropy": 2.5947842891364936, "native_plan_sha256": "609023b60fa4e577c171a0116694034e116f60e47c3057078b21428984703b46", "native": { "cross_entropy": 2.5947758103968717, "lexical_cross_entropy": 2.594817545656657, "targets": 13176800, "lexical_targets": 13162292 }, "release": { "cross_entropy": 2.5947758103968717, "lexical_cross_entropy": 2.594817545359881, "targets": 13176800, "lexical_targets": 13162292 }, "native_release_lexical_difference": 2.9677593715859985e-10, "native_archived_lexical_difference": 7.872572174161263e-06, "release_archived_lexical_difference": 7.872868950098422e-06 } }, "fa_current_runtime_small_resume": { "passed": true, "architecture": "FA", "scope": "Tiny current-runtime save/resume, not full-model resume", "source_tree_sha256": "c985d4ea2158d9f32d67654a20a775166db5b5d09a72716001333bb100898e79", "world_size": 1, "accumulation_steps": 2, "layers": 2, "width": 128, "memory_slots": [ 0, 0 ], "updates": 7, "lexical_tokens": 1764, "resume_update": 2, "final_epoch": 1, "weights": { "tensor_count": 37, "bitwise_equal_tensors": 7, "maximum_absolute_difference": 7.450580596923828e-09, "worst_tensors": [ [ "layers.1.v_proj.weight", 7.450580596923828e-09 ], [ "token_embed.weight", 7.450580596923828e-09 ], [ "layers.0.k_proj.weight", 3.725290298461914e-09 ], [ "layers.0.mlp.0.weight", 3.725290298461914e-09 ], [ "layers.0.q_proj.weight", 3.725290298461914e-09 ] ] }, "optimizer_state": { "tensor_count": 111, "bitwise_equal_tensors": 39, "maximum_absolute_difference": 3.725290298461914e-09, "worst_tensors": [ [ "24.exp_avg", 3.725290298461914e-09 ], [ "20.exp_avg", 1.862645149230957e-09 ], [ "30.exp_avg", 1.862645149230957e-09 ], [ "34.exp_avg", 1.862645149230957e-09 ], [ "0.exp_avg", 9.313225746154785e-10 ] ] }, "rng_bitwise_equal": true, "counters_and_plan_equal": true, "checkpoint_manifests_verified": true, "current_tokenizer_license_in_manifest": true, "learning_rate_and_token_history_equal": true, "maximum_loss_difference": 0.0, "maximum_validation_loss_difference": 0.0, "maximum_gradient_norm_difference": 2.384185791015625e-07, "data_manifest_sha256": "2b9c910d00bbd94eed9260d74e0755a24e2f8fdb2634a24707a3e98825fed4e7", "validation_manifest_sha256": "2b9c910d00bbd94eed9260d74e0755a24e2f8fdb2634a24707a3e98825fed4e7", "runtime": { "torch": "2.11.0+cu128", "cuda": "12.8", "gpu": "NVIDIA H100 80GB HBM3" }, "status": "passed", "training_state_passed": true, "endpoint_validation_loss_difference": 0.0, "declared_tolerances": { "weights_absolute": 1e-06, "optimizer_state_absolute": 1e-06, "loss_absolute": 2e-05 } }, "pat_current_runtime_small_resume": { "passed": false, "architecture": "PAT", "scope": "Tiny current-runtime save/resume, not full-model resume", "source_tree_sha256": "c985d4ea2158d9f32d67654a20a775166db5b5d09a72716001333bb100898e79", "world_size": 1, "accumulation_steps": 2, "layers": 3, "width": 128, "memory_slots": [ 2, 8, 2 ], "updates": 7, "lexical_tokens": 1764, "resume_update": 2, "final_epoch": 1, "weights": { "tensor_count": 44, "bitwise_equal_tensors": 40, "maximum_absolute_difference": 3.725290298461914e-09, "worst_tensors": [ [ "token_embed.weight", 3.725290298461914e-09 ], [ "layers.1.mlp.2.bias", 1.1641532182693481e-10 ], [ "layers.0.mlp.2.bias", 5.820766091346741e-11 ], [ "layers.2.mlp.2.bias", 2.9103830456733704e-11 ], [ "final_norm.bias", 0.0 ] ] }, "optimizer_state": { "tensor_count": 132, "bitwise_equal_tensors": 112, "maximum_absolute_difference": 9.313225746154785e-10, "worst_tensors": [ [ "0.exp_avg", 9.313225746154785e-10 ], [ "24.exp_avg", 9.313225746154785e-10 ], [ "32.exp_avg", 9.313225746154785e-10 ], [ "40.exp_avg", 4.656612873077393e-10 ], [ "17.exp_avg", 7.275957614183426e-12 ] ] }, "rng_bitwise_equal": true, "counters_and_plan_equal": true, "checkpoint_manifests_verified": true, "current_tokenizer_license_in_manifest": true, "learning_rate_and_token_history_equal": true, "maximum_loss_difference": 0.0, "maximum_validation_loss_difference": 6.200396825306598e-05, "maximum_gradient_norm_difference": 0.0, "data_manifest_sha256": "2b9c910d00bbd94eed9260d74e0755a24e2f8fdb2634a24707a3e98825fed4e7", "validation_manifest_sha256": "2b9c910d00bbd94eed9260d74e0755a24e2f8fdb2634a24707a3e98825fed4e7", "runtime": { "torch": "2.11.0+cu128", "cuda": "12.8", "gpu": "NVIDIA H100 80GB HBM3" }, "status": "training_state_passed_validation_tolerance_exceeded", "training_state_passed": true, "endpoint_validation_loss_difference": 0.0, "declared_tolerances": { "weights_absolute": 1e-06, "optimizer_state_absolute": 1e-06, "loss_absolute": 2e-05 }, "qualification": "All training loss records and final validation agree exactly. One intermediate validation differs by 6.2004e-5, exceeding the preset 2e-5 tolerance; the aggregate test is not marked passed.", "validation_diagnostic": { "continuous": { "loss": 10.465711805555555, "lexical_loss": 10.465711805555555, "targets": 1008, "lexical_targets": 1008 }, "resumed": { "loss": 10.465649801587302, "lexical_loss": 10.465649801587302, "targets": 1008, "lexical_targets": 1008 }, "continuous_repeat": { "loss": 10.465711805555555, "lexical_loss": 10.465711805555555, "targets": 1008, "lexical_targets": 1008 }, "resumed_instance_with_continuous_weights": { "loss": 10.465711805555555, "lexical_loss": 10.465711805555555, "targets": 1008, "lexical_targets": 1008 }, "scope": "Fresh-process same-runtime evaluation of saved update6 weights; optimizer trajectory is unchanged", "interpretation": "The validation difference is reproducible from the saved weights in a fresh shared process. Repeating the continuous model is exact, and replacing the resumed instance weights with continuous weights restores exact agreement. The preset validation tolerance remains exceeded." } }, "pat32_cached_inference": { "status": "passed", "scope": "Exact released PAT-32 checkpoint; comparison against original cached decoding core", "greedy_prompts": 9, "greedy_steps": 216, "all_greedy_tokens_equal": true, "full_model_trace_steps": 35, "all_traced_logits_and_cache_tensors_bitwise_equal": true, "completed_chunk_commits_in_trace": 2, "small_geometry_boundary_comparisons": [ { "chunk_size": 16, "memory_slots": [ 2, 8, 2 ], "capacity": 64, "exact_steps": 63, "total_steps": 63, "native_exact": true, "max_context_prefill": true, "capacity_overflow_rejected": true, "compiled_model_reuse_exact": true }, { "chunk_size": 32, "memory_slots": [ 2, 8, 2 ], "capacity": 128, "exact_steps": 127, "total_steps": 127, "native_exact": true, "max_context_prefill": true, "capacity_overflow_rejected": true, "compiled_model_reuse_exact": true }, { "chunk_size": 16, "memory_slots": [ 1, 4, 1 ], "capacity": 64, "exact_steps": 63, "total_steps": 63, "native_exact": true, "max_context_prefill": true, "capacity_overflow_rejected": true, "compiled_model_reuse_exact": true }, { "chunk_size": 16, "memory_slots": [ 2, 20, 2 ], "capacity": 64, "exact_steps": 63, "total_steps": 63, "native_exact": true, "max_context_prefill": true, "capacity_overflow_rejected": true, "compiled_model_reuse_exact": true } ], "prefill": "Sequential token ingestion through the same cached append arithmetic; no optimized prefill throughput claim" }, "pat32_causality_and_document_isolation": { "mode": "eval; no_grad; BF16 autocast; fixed compiled components", "contract": "Inputs in every perturbation pair have identical lengths, document boundaries, packing geometry, and logit projection shapes.", "causality": [ { "routed_length": 33, "first_changed_target": 0, "compared_target_count": 1, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 50304 }, { "routed_length": 33, "first_changed_target": 15, "compared_target_count": 16, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 804864 }, { "routed_length": 33, "first_changed_target": 16, "compared_target_count": 17, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 855168 }, { "routed_length": 33, "first_changed_target": 17, "compared_target_count": 18, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 905472 }, { "routed_length": 65, "first_changed_target": 31, "compared_target_count": 32, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1609728 }, { "routed_length": 65, "first_changed_target": 32, "compared_target_count": 33, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1660032 }, { "routed_length": 65, "first_changed_target": 33, "compared_target_count": 34, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1710336 }, { "routed_length": 145, "first_changed_target": 63, "compared_target_count": 64, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3219456 }, { "routed_length": 145, "first_changed_target": 64, "compared_target_count": 65, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3269760 }, { "routed_length": 145, "first_changed_target": 65, "compared_target_count": 66, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3320064 }, { "routed_length": 513, "first_changed_target": 255, "compared_target_count": 256, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 12877824 }, { "routed_length": 4096, "first_changed_target": 1023, "compared_target_count": 1024, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 51511296 }, { "routed_length": 16384, "first_changed_target": 8191, "compared_target_count": 8192, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 412090368 }, { "routed_length": 16124, "first_changed_target": 8191, "compared_target_count": 8192, "terminal_eod": true, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 412090368 } ], "document_isolation": [ { "target_length": 15, "other_length": 17, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 754560 }, { "target_length": 15, "other_length": 17, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 754560 }, { "target_length": 32, "other_length": 33, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1609728 }, { "target_length": 32, "other_length": 33, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1609728 }, { "target_length": 65, "other_length": 79, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3269760 }, { "target_length": 65, "other_length": 79, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3269760 }, { "target_length": 512, "other_length": 1025, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 25755648 }, { "target_length": 512, "other_length": 1025, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 25755648 }, { "target_length": 2048, "other_length": 4096, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 103022592 }, { "target_length": 2048, "other_length": 4096, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 103022592 } ], "complete": true, "elapsed_seconds": 23.076029752992326, "passed": true, "scope": "Controlled perturbations of real heldout text; evaluated the exact exported 32-layer checkpoint with fixed shapes, boundaries, evaluation mode, and BF16 arithmetic. All compared logits are bitwise unchanged. This checks teacher-forced inference; cache equivalence is validated separately." }, "fa32_causality_and_document_isolation": { "mode": "eval; no_grad; BF16 autocast; fixed compiled components", "contract": "Inputs in every perturbation pair have identical lengths, document boundaries, packing geometry, and logit projection shapes.", "causality": [ { "routed_length": 33, "first_changed_target": 0, "compared_target_count": 1, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 50304 }, { "routed_length": 33, "first_changed_target": 15, "compared_target_count": 16, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 804864 }, { "routed_length": 33, "first_changed_target": 16, "compared_target_count": 17, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 855168 }, { "routed_length": 33, "first_changed_target": 17, "compared_target_count": 18, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 905472 }, { "routed_length": 65, "first_changed_target": 31, "compared_target_count": 32, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1609728 }, { "routed_length": 65, "first_changed_target": 32, "compared_target_count": 33, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1660032 }, { "routed_length": 65, "first_changed_target": 33, "compared_target_count": 34, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1710336 }, { "routed_length": 145, "first_changed_target": 63, "compared_target_count": 64, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3219456 }, { "routed_length": 145, "first_changed_target": 64, "compared_target_count": 65, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3269760 }, { "routed_length": 145, "first_changed_target": 65, "compared_target_count": 66, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3320064 }, { "routed_length": 513, "first_changed_target": 255, "compared_target_count": 256, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 12877824 }, { "routed_length": 4096, "first_changed_target": 1023, "compared_target_count": 1024, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 51511296 }, { "routed_length": 16384, "first_changed_target": 8191, "compared_target_count": 8192, "terminal_eod": false, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 412090368 }, { "routed_length": 16124, "first_changed_target": 8191, "compared_target_count": 8192, "terminal_eod": true, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 412090368 } ], "document_isolation": [ { "target_length": 15, "other_length": 17, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 754560 }, { "target_length": 15, "other_length": 17, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 754560 }, { "target_length": 32, "other_length": 33, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1609728 }, { "target_length": 32, "other_length": 33, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 1609728 }, { "target_length": 65, "other_length": 79, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3269760 }, { "target_length": 65, "other_length": 79, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 3269760 }, { "target_length": 512, "other_length": 1025, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 25755648 }, { "target_length": 512, "other_length": 1025, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 25755648 }, { "target_length": 2048, "other_length": 4096, "target_document_index": 0, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 103022592 }, { "target_length": 2048, "other_length": 4096, "target_document_index": 1, "exact": true, "max_abs": 0.0, "relative_l2": 0.0, "logit_values": 103022592 } ], "complete": true, "elapsed_seconds": 19.475248193994048, "passed": true, "scope": "Controlled perturbations of real heldout text; evaluated the exact exported 32-layer checkpoint with fixed shapes, boundaries, evaluation mode, and BF16 arithmetic. All compared logits are bitwise unchanged. This checks teacher-forced inference; cache equivalence is validated separately." }, "anonymous_downloads": { "status": "passed", "architectures": [ "PAT-32", "FA-32" ], "authentication": "token=False", "full_bundle_bytes_verified": true, "generation_from_downloaded_weights": true }, "cached_http_interface": { "status": "passed", "architectures": [ "PAT", "FA" ], "checks": { "PAT": { "passed": true, "health": { "status": "ready", "architecture": "PAT" }, "generated_tokens": 64, "stop_reason": "length", "invalid_request_status": 400, "empty_prompt_status": 400 }, "FA": { "passed": true, "health": { "status": "ready", "architecture": "FA" }, "generated_tokens": 64, "stop_reason": "length", "invalid_request_status": 400, "empty_prompt_status": 400 } }, "scope": "Local exported bundles with weight hashes equal to the publicly downloaded bundles; local HTTP readiness, 64-token cached greedy continuation, and rejected malformed or empty prompts", "quality_observations": "PAT repeated the Paris statement; FA repeated itself and incorrectly located Paris in southern France. Matching the original cached computations establishes behavior preservation, not answer quality." }, "pat32_repeated_compiled_training_and_optimizer": { "complete": true, "losses": [ { "kind": "native", "repeat": 0, "loss": 3.467360734939575 }, { "kind": "public", "repeat": 0, "loss": 3.467360734939575 }, { "kind": "native", "repeat": 1, "loss": 3.467360734939575 }, { "kind": "public", "repeat": 1, "loss": 3.467360734939575 }, { "kind": "native", "repeat": 2, "loss": 3.467360734939575 }, { "kind": "public", "repeat": 2, "loss": 3.467360734939575 } ], "summaries": { "comparisons": { "native-native": { "pairs": 3, "maximum_absolute_difference": 0.0003722831606864929, "maximum_relative_l2_difference": 0.015777727589011192 }, "native-public": { "pairs": 9, "maximum_absolute_difference": 0.0003722831606864929, "maximum_relative_l2_difference": 0.015777727589011192 }, "public-public": { "pairs": 3, "maximum_absolute_difference": 0.000244140625, "maximum_relative_l2_difference": 0.009892137721180916 } }, "optimizer_comparisons": { "native-native": { "pairs": 3, "maximum_absolute_difference": 0.000498548150062561, "maximum_relative_l2_difference": 0.000719903560820967 }, "native-public": { "pairs": 9, "maximum_absolute_difference": 0.000498548150062561, "maximum_relative_l2_difference": 0.000719903560820967 }, "public-public": { "pairs": 3, "maximum_absolute_difference": 0.0004982585087418556, "maximum_relative_l2_difference": 0.0005761353531852365 } } }, "matching_variants": [ { "left": [ "public", 0 ], "right": [ "native", 2 ], "gradient_max_abs": 1.4901161193847656e-08, "gradient_max_relative": 8.276615659497111e-08, "gradient_nonexact": [ { "name": "token_embed.weight", "max_abs": 1.862645149230957e-09, "rms": 2.420710550413152e-12, "relative_l2": 1.0239719294702354e-08, "exact": false, "relative_l2_reverse": 1.0239719294702354e-08 }, { "name": "final_norm.weight", "max_abs": 1.4901161193847656e-08, "rms": 3.7714895095852796e-10, "relative_l2": 7.379185262834653e-08, "exact": false, "relative_l2_reverse": 7.379185262834653e-08 }, { "name": "final_norm.bias", "max_abs": 1.862645149230957e-09, "rms": 4.4500195195418257e-10, "relative_l2": 8.276615659497111e-08, "exact": false, "relative_l2_reverse": 8.276615659497111e-08 } ], "optimizer_max_abs": 3.725290298461914e-08, "optimizer_max_relative": 3.6184089058366453e-09, "optimizer_nonexact": [ { "name": "token_embed.weight", "max_abs": 3.725290298461914e-08, "rms": 4.3118512232931394e-12, "relative_l2": 7.09697023371092e-11, "exact": false, "relative_l2_reverse": 7.09697023371092e-11 }, { "name": "final_norm.bias", "max_abs": 3.725290298461914e-09, "rms": 1.4098047729227403e-10, "relative_l2": 3.6184089058366453e-09, "exact": false, "relative_l2_reverse": 3.6184089058366453e-09 } ] }, { "left": [ "native", 0 ], "right": [ "public", 1 ], "gradient_max_abs": 1.4901161193847656e-08, "gradient_max_relative": 8.276615659497111e-08, "gradient_nonexact": [ { "name": "token_embed.weight", "max_abs": 1.862645149230957e-09, "rms": 2.319067464104374e-12, "relative_l2": 9.809637546709382e-09, "exact": false, "relative_l2_reverse": 9.809637546709382e-09 }, { "name": "final_norm.weight", "max_abs": 1.4901161193847656e-08, "rms": 3.7714895095852796e-10, "relative_l2": 7.379185262834653e-08, "exact": false, "relative_l2_reverse": 7.379185262834653e-08 }, { "name": "final_norm.bias", "max_abs": 1.862645149230957e-09, "rms": 4.4500195195418257e-10, "relative_l2": 8.276615659497111e-08, "exact": false, "relative_l2_reverse": 8.276615659497111e-08 } ], "optimizer_max_abs": 1.4901161193847656e-08, "optimizer_max_relative": 2.6642872352766744e-09, "optimizer_nonexact": [ { "name": "token_embed.weight", "max_abs": 1.4901161193847656e-08, "rms": 1.9599987865354107e-12, "relative_l2": 3.226004879897104e-11, "exact": false, "relative_l2_reverse": 3.226004879897104e-11 }, { "name": "final_norm.bias", "max_abs": 1.862645149230957e-09, "rms": 1.0380598464143631e-10, "relative_l2": 2.6642872352766744e-09, "exact": false, "relative_l2_reverse": 2.6642872352766744e-09 } ] }, { "left": [ "native", 0 ], "right": [ "public", 2 ], "gradient_max_abs": 1.4901161193847656e-08, "gradient_max_relative": 8.276615659497111e-08, "gradient_nonexact": [ { "name": "token_embed.weight", "max_abs": 7.450580596923828e-09, "rms": 2.4919751592106243e-12, "relative_l2": 1.054103648812088e-08, "exact": false, "relative_l2_reverse": 1.054103648812088e-08 }, { "name": "final_norm.weight", "max_abs": 1.4901161193847656e-08, "rms": 3.7714895095852796e-10, "relative_l2": 7.379185262834653e-08, "exact": false, "relative_l2_reverse": 7.379185262834653e-08 }, { "name": "final_norm.bias", "max_abs": 1.862645149230957e-09, "rms": 4.4500195195418257e-10, "relative_l2": 8.276615659497111e-08, "exact": false, "relative_l2_reverse": 8.276615659497111e-08 } ], "optimizer_max_abs": 1.4901161193847656e-08, "optimizer_max_relative": 2.6642872352766744e-09, "optimizer_nonexact": [ { "name": "token_embed.weight", "max_abs": 1.4901161193847656e-08, "rms": 1.9840487759659187e-12, "relative_l2": 3.265589187950724e-11, "exact": false, "relative_l2_reverse": 3.265589187950724e-11 }, { "name": "final_norm.bias", "max_abs": 1.862645149230957e-09, "rms": 1.0380598464143631e-10, "relative_l2": 2.6642872352766744e-09, "exact": false, "relative_l2_reverse": 2.6642872352766744e-09 } ] } ], "status": "qualified_with_empirical_native_variability", "scope": "Exact released PAT-32 weights; three original and three released compiled production-loss draws and corresponding fresh clipped fused-AdamW steps. Each released draw has an observed original decoder-gradient variant match. Equal native/native and native/public maximum spreads are finite empirical evidence, not guaranteed bounds or a deterministic-trajectory claim.", "input_sha256": "934478292f6813a01cbe04077282a162335ef9da5ea1d09a5c12724aa26da76a", "piece_routed_lengths": [ 64, 80 ], "lexical_tokens": 143, "supervised_tokens": 144, "gradient_tensors": 421, "matched_gradient_tensors": 418, "matched_updated_weight_tensors": 419, "optimizer": "Fresh fused AdamW, peak LR2.5e-4, selective matrix decay0.01, betas0.9/0.999, epsilon1e-8, global gradient clipping1.0" }, "pat32_independent_repeated_gradient_control": { "complete": true, "source_draws": 3, "public_draws": 3, "compared_gradient_tensors": 421, "input_sha256": "934478292f6813a01cbe04077282a162335ef9da5ea1d09a5c12724aa26da76a", "piece_routed_lengths": [ 64, 80 ], "lexical_tokens": 143, "supervised_tokens": 144, "identical_loss_all_six_draws": 3.4686646461486816, "native_native": { "pairs": 3, "maximum_absolute_difference": 0.0002324134111404419, "maximum_relative_l2_difference": 0.011112370528280735 }, "public_public": { "pairs": 3, "maximum_absolute_difference": 0.0002324134111404419, "maximum_relative_l2_difference": 0.011112370528280735 }, "native_public": { "pairs": 9, "maximum_absolute_difference": 0.0002324134111404419, "maximum_relative_l2_difference": 0.011112370528280735 }, "near_bitwise_cross_pairs": [ { "left": [ "native", 0 ], "right": [ "public", 2 ], "maximum_absolute_difference": 2.9802322387695312e-08, "maximum_relative_l2_difference": 1.3370944884627534e-07, "exact_tensors": 418, "tensors": 421 }, { "left": [ "public", 0 ], "right": [ "native", 2 ], "maximum_absolute_difference": 1.1920928955078125e-07, "maximum_relative_l2_difference": 5.054168354945432e-07, "exact_tensors": 416, "tensors": 421 }, { "left": [ "native", 1 ], "right": [ "public", 2 ], "maximum_absolute_difference": 2.9802322387695312e-08, "maximum_relative_l2_difference": 1.3370944884627534e-07, "exact_tensors": 418, "tensors": 421 } ], "additional_source_only_draws": 5, "combined_source_empirical_absolute_envelope_exceptions": [ { "name": "final_norm.weight", "maximum_absolute_difference": 2.9802322387695312e-08 }, { "name": "final_norm.bias", "maximum_absolute_difference": 1.862645149230957e-09 } ], "scope": "Repeated uninstrumented production-loss forward/backward with identical weights, inputs, mode and compilation in one process. The source and release exhibit nondeterministic backward accumulation. Maximum cross-model gradient differences match the observed source/source maximum; several cross-model draws agree up to small FP32 differences. This is finite empirical evidence, not a guaranteed bound or deterministic training-trajectory claim. Optimizer and longer training are evaluated separately." }, "pat32_200m_continued_training": { "status": "passed", "complete": true, "target_lexical_tokens": 200000000, "realized_lexical_tokens": 200087827, "updates": 2006, "world_size": 4, "accumulation_steps": 1, "source_snapshot_sha256": "ac87fc0fcc8dae5e6890bca5da11103fd82116544ec25724f15112d75b5b73fe", "training_data_manifest_sha256": "06be2e727c9fd5ffcfd66cb0c7de3e1b6ee895283183eb0ec027c9d9b96223f7", "validation_data_manifest_sha256": "f98606cbb0be9a140555340c82a9dcfcdf4002c3dab7d49ea24e21fa605ea06e", "initial_weights_sha256": "be0a5fd13fbd6d80f8a488f25446a5db246c01c0090c22656d0eda91a344a5e3", "final_weights_sha256": "a9d62e1ff6b811686bc7bc7c0cf2fb96076c37651f4fbd968ce4b3574b63af7b", "final_training_state_sha256": "5091ff0fe85e70719799c416841f06075cf37ba9bd83b43a157aa6210f4f3906", "final_checkpoint_manifest_sha256": "bf1bba940c613174c7edc9d9311e1bcd1cba6829f5a5c75c2196998c06dfb55e", "metrics_sha256": "5226f5756b70300dfcf4fa84dd3c5461048bdcc5a1e3c16ad227eba1900b2399", "final_training_metrics": { "step": 2006, "tokens": 200087827, "lr": 2.5000021783021975e-05, "loss": 2.584868706651599, "lexical_loss": 2.584656310173299, "grad_norm": 0.11044399440288544 }, "final_validation": { "loss": 2.60876559592482, "lexical_loss": 2.608747152906511, "targets": 15017104, "lexical_targets": 15002471 }, "optimizer_parameter_states": 421, "all_recorded_losses_and_grad_norms_finite": true, "every_token_schedule_step_exact": true, "final_resume_manifest_verified": true, "completed_pacific": "2026-09-26 02:47:37 PDT", "final_checkpoint_is_published_original": false, "scope": "Continued training from the exact published original checkpoint with a new optimizer and 200M-token schedule. The run exercises the released implementation only; it does not compare two complete training trajectories or replace the published original checkpoint." }, "pat_small_saved_weight_native_validation_control": { "scope": "Native and clean evaluation of identical saved continuous/resumed update6 weight variants; this does not rerun native resume training", "results": { "continuous": { "native": 10.465711805555555, "public": 10.465711805555555, "targets": 1008, "batches": [ { "native_loss_sum": 1314.625, "public_loss_sum": 1314.625, "targets": 126 }, { "native_loss_sum": 1312.3125, "public_loss_sum": 1312.3125, "targets": 126 }, { "native_loss_sum": 1325.125, "public_loss_sum": 1325.125, "targets": 126 }, { "native_loss_sum": 1312.1875, "public_loss_sum": 1312.1875, "targets": 126 }, { "native_loss_sum": 1327.5, "public_loss_sum": 1327.5, "targets": 126 }, { "native_loss_sum": 1324.125, "public_loss_sum": 1324.125, "targets": 126 }, { "native_loss_sum": 1314.5625, "public_loss_sum": 1314.5625, "targets": 126 }, { "native_loss_sum": 1319.0, "public_loss_sum": 1319.0, "targets": 126 } ], "every_batch_exact": true }, "resumed": { "native": 10.465649801587302, "public": 10.465649801587302, "targets": 1008, "batches": [ { "native_loss_sum": 1314.625, "public_loss_sum": 1314.625, "targets": 126 }, { "native_loss_sum": 1312.3125, "public_loss_sum": 1312.3125, "targets": 126 }, { "native_loss_sum": 1325.0625, "public_loss_sum": 1325.0625, "targets": 126 }, { "native_loss_sum": 1312.1875, "public_loss_sum": 1312.1875, "targets": 126 }, { "native_loss_sum": 1327.5, "public_loss_sum": 1327.5, "targets": 126 }, { "native_loss_sum": 1324.125, "public_loss_sum": 1324.125, "targets": 126 }, { "native_loss_sum": 1314.5625, "public_loss_sum": 1314.5625, "targets": 126 }, { "native_loss_sum": 1319.0, "public_loss_sum": 1319.0, "targets": 126 } ], "every_batch_exact": true }, "continuous_repeat": { "native": 10.465711805555555, "public": 10.465711805555555, "targets": 1008, "batches": [ { "native_loss_sum": 1314.625, "public_loss_sum": 1314.625, "targets": 126 }, { "native_loss_sum": 1312.3125, "public_loss_sum": 1312.3125, "targets": 126 }, { "native_loss_sum": 1325.125, "public_loss_sum": 1325.125, "targets": 126 }, { "native_loss_sum": 1312.1875, "public_loss_sum": 1312.1875, "targets": 126 }, { "native_loss_sum": 1327.5, "public_loss_sum": 1327.5, "targets": 126 }, { "native_loss_sum": 1324.125, "public_loss_sum": 1324.125, "targets": 126 }, { "native_loss_sum": 1314.5625, "public_loss_sum": 1314.5625, "targets": 126 }, { "native_loss_sum": 1319.0, "public_loss_sum": 1319.0, "targets": 126 } ], "every_batch_exact": true } }, "native_variant_delta": -6.200396825306598e-05, "public_variant_delta": -6.200396825306598e-05, "every_batch_exact": true, "status": "passed", "interpretation": "Every original/released batch loss is identical for each saved weight variant. One batch sum changes from 1325.125 to 1325.0625, reproducing the same 6.2003968253e-5 mean-loss shift. This passing evaluation control does not rerun native continuation training or change the failed strict resume-validation gate." }, "fa32_full_resume": { "architecture": "FA", "world_size": 2, "source_snapshot_sha256": "dc7e68f6dd6e63bfdc56b2fb8d4e230f9cf17f44530489027040ac1d24af9216", "original_row": { "step": 1004, "tokens": 100144085, "lr": 0.00025, "loss": 2.536753174964392, "lexical_loss": 2.5366325168232318, "grad_norm": 0.11217649281024933 }, "replayed_row": { "step": 1004, "tokens": 100144085, "lr": 0.00025, "loss": 2.536753174964392, "lexical_loss": 2.5366325168232318, "grad_norm": 0.11217648535966873 }, "absolute_differences": { "loss": 0.0, "lexical_loss": 0.0, "grad_norm": 7.450580596923828e-09 }, "tokens_and_learning_rate_exact": true, "saved_after_one_update": true, "saved_manifest_verified": true, "scope": "Full released FA-32 geometry on two GPUs with two microbatches per rank per update. Restore the actual continuation-run checkpoint at100,044,446 lexical tokens, including optimizer, per-rank RNG, and data cursor; execute exactly one update and save via the public signal path. This verifies resume functionality and next-update numerical behavior, not completion of the200M run.", "saved_state_audit": { "contract_fields_equal": [ "format", "world_size", "training_config", "data_fingerprint", "validation_fingerprint", "plan_sha256" ], "frozen_source_files_verified": 44, "source_and_saved_complete_manifests_verified": true, "expected_world_size": 2, "source_epoch": 0, "saved_epoch": 0, "source_cursor": 4012, "saved_cursor": 4016, "cursor_increment": 4, "source_tokens": 100044446, "saved_tokens": 100144085, "source_step": 1003, "saved_step": 1004, "optimizer_parameter_states": 547, "all_optimizer_steps_incremented_once": true, "all_optimizer_group_learning_rates_exact": true, "rng_state_unchanged_by_replay_update_per_rank": [ { "cpu": true, "cuda": true }, { "cpu": true, "cuda": true } ], "saved_model_strict_load_and_tied_embedding": true, "source_manifest_sha256": "fd267b4bff2231fe65d10ae606d73ab894f49bcf28e80a6548627021da24812f", "saved_manifest_sha256": "23f42bed77e841a617eba2eae41440181d15e4e284c90bc9108f562be261b11b", "source_weights_sha256": "3696823a957fda6e70b05b601d8feaf9103b516066171beb33b30c69b5b03aac", "saved_weights_sha256": "97e5379f5e08e919826a6c5669e2f3b105ffa917f09cc9bd3024e54ccf44ecd6" }, "functional_state_audit_passed": true, "status": "functional_state_passed_numerical_differences_reported" }, "pat32_long_cached_inference": { "status": "passed", "passed": true, "scope": "Exact PAT-32 checkpoint, authentic long validation document, original single-document cache oracle", "prompt_tokens": 16319, "capacity_including_bos": 16384, "prefill_logit_comparisons": [ { "prefix_tokens": 1, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 15, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 16, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 17, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 511, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 1023, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 2047, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 4095, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 8191, "exact": true, "maximum_absolute_difference": 0.0 }, { "prefix_tokens": 16319, "exact": true, "maximum_absolute_difference": 0.0 } ], "greedy_steps": 64, "all_greedy_logits_and_tokens_equal": true, "endpoint_cache_comparisons": 95, "all_endpoint_cache_tensors_bitwise_equal": true, "elapsed_seconds": 907.1081237280014 }, "pat32_full_resume": { "architecture": "PAT", "world_size": 4, "source_snapshot_sha256": "ac87fc0fcc8dae5e6890bca5da11103fd82116544ec25724f15112d75b5b73fe", "original_row": { "step": 1004, "tokens": 100144085, "lr": 0.00025, "loss": 2.5029088428823623, "lexical_loss": 2.5029162307178914, "grad_norm": 0.1155344769358635 }, "replayed_row": { "step": 1004, "tokens": 100144085, "lr": 0.00025, "loss": 2.5029318424886657, "lexical_loss": 2.5029397139297864, "grad_norm": 0.11557839065790176 }, "absolute_differences": { "loss": 2.2999606303475417e-05, "lexical_loss": 2.3483211895047873e-05, "grad_norm": 4.391372203826904e-05 }, "tokens_and_learning_rate_exact": true, "saved_after_one_update": true, "saved_manifest_verified": true, "scope": "Full PAT-32 geometry on four GPUs with one microbatch per rank. Restore the actual continuation checkpoint at 100,044,446 lexical tokens, run one optimizer update, and save via the public signal path. Functional restoration and state integrity passed; numerical differences from uninterrupted training remain explicitly reported.", "saved_state_audit": { "contract_fields_equal": [ "format", "world_size", "training_config", "data_fingerprint", "validation_fingerprint", "plan_sha256" ], "frozen_source_files_verified": 48, "source_and_saved_complete_manifests_verified": true, "expected_world_size": 4, "source_epoch": 0, "saved_epoch": 0, "source_cursor": 4012, "saved_cursor": 4016, "cursor_increment": 4, "source_tokens": 100044446, "saved_tokens": 100144085, "source_step": 1003, "saved_step": 1004, "optimizer_parameter_states": 421, "all_optimizer_steps_incremented_once": true, "all_optimizer_group_learning_rates_exact": true, "rng_state_unchanged_by_replay_update_per_rank": [ { "cpu": true, "cuda": true }, { "cpu": true, "cuda": true }, { "cpu": true, "cuda": true }, { "cpu": true, "cuda": true } ], "saved_model_strict_load_and_tied_embedding": true, "source_manifest_sha256": "02010249f94a4720d01cb06a88041b712c0b349af4b50d3c16b0e6c2a713a251", "saved_manifest_sha256": "2b6b613b83765de82ae64ac3ff56c3f5ecf2667386472ef2c9998b5aed9f42c0", "source_weights_sha256": "7521817cf8db58ed2e3a3980e5fd22de8b9fc8ec7a4f447e25d2deaf3d673545", "saved_weights_sha256": "a1d57a24359613a71c9ed25d1acdc9412844c3735ee2f345a1a9969f629b0a14", "source_and_saved_model_configs_match_frozen_recipe": true, "source_data_fingerprints_match_frozen_run_identity": true, "full_native_batch_plan_hash_verified": true }, "functional_state_audit_passed": true, "launcher_exit_codes": [ 0, 0 ], "status": "functional_state_passed_numerical_differences_reported", "numerical_scope": "The token clock, learning rate, optimizer state structure, and resume cursor were restored successfully. Measured loss, lexical-loss, and gradient-norm differences from uninterrupted training are reported explicitly; no numerical tolerance was declared or passed." }, "pat32_continuation_endpoint": { "architecture": "PAT", "model": "PAT-32", "complete": true, "passed": true, "training_target_lexical_tokens": 200000000, "training_realized_lexical_tokens": 200087827, "training_updates": 2006, "training_source_tree_sha256": "ac87fc0fcc8dae5e6890bca5da11103fd82116544ec25724f15112d75b5b73fe", "checkpoint_manifest_sha256": "bf1bba940c613174c7edc9d9311e1bcd1cba6829f5a5c75c2196998c06dfb55e", "model_weights_sha256": "a9d62e1ff6b811686bc7bc7c0cf2fb96076c37651f4fbd968ce4b3574b63af7b", "strict_loads": 2, "tied_embedding_verified": true, "greedy_generation_identical_after_reload": true, "generation_uses_current_public_cached_api": true, "generation": [ { "prompt_tokens": 5, "generated_tokens": 24, "stop_reason": "length", "token_ids_sha256": "8700b2470aab29e3898888fb1a0d40fecccc480aac1195c7fdadd6bbda66541d" }, { "prompt_tokens": 12, "generated_tokens": 24, "stop_reason": "length", "token_ids_sha256": "d772f387f5bcd91e597002b93cdd7d7415784a7dd08091e87226f6c67c31b025" }, { "prompt_tokens": 8, "generated_tokens": 24, "stop_reason": "length", "token_ids_sha256": "74bafc592e03ee3edf0b5cbce99a2e11588fe4405863fb266caed5087c10ae03" } ], "runtime": { "gpu": "NVIDIA H100 80GB HBM3", "torch": "2.11.0+cu128", "cuda": "12.8", "triton": "3.6.0" }, "public_inference_source_files": { "src/pat/__init__.py": "2bde6c86f162f864c978e703a78fe7b85257604d4f3e04b6bc1a0e0c73333c35", "src/pat/attention.py": "a0d61863a1c65beda70a1253878ec799099856379b341ea8f826cc7b9cd24e4e", "src/pat/checkpoint.py": "dfc3fe41c51ad42d66429e8f8d382ef4c95c8cebe61dffb3b940c2cfad36d925", "src/pat/config.py": "58cec92f71b229d4b5bdc460a9a5e1f5af61d2eeb0d22b8228a3af57a9c06350", "src/pat/data.py": "649e9f25c911feb0af4be5d9746c6e9dedec6e2677804245869093ab750235f4", "src/pat/generate.py": "24d2c3daa4d81baab025cdbb2524caa2f7c0fa81a3dbc445219753aed52dbce5", "src/pat/inference.py": "271c3eb7b426d19baead1ccb3067eff923d6cad8cf6ecfd4ceddebb4bff85493", "src/pat/kernels/__init__.py": "e7c17f234aecd5cf9d039adf65230c584e65fd10c7fd14a0f545f77f763862b5", "src/pat/kernels/attention.py": "ec980919ccd30659b9745fa15c792c4cf7e2398596aad1b5e11f5ac0f05f5682", "src/pat/kernels/decoding.py": "9eac6a9efbeada39937b4f7d4816d365ca915bee08dc0ddb0765665c87d1eb89", "src/pat/kernels/layout.py": "dd3413746f4b56ab3af4b593777d76768a9ff7127a6590e89fe47d30b9bc9cc2", "src/pat/losses.py": "10e42db2ee3e22a3b548fd9acc5a8a567e70afa27024f54ebda2ba35fe5d4018", "src/pat/model.py": "dd3c720308ce7a5f8502fb4eb4127982c98b64c9a21e1718f79d71e80b491225", "src/pat/packing.py": "6ba16848ec282771f17b9e447eb44ecd7060157e34b855cb32a67cca4a36261d", "src/pat/pat_cache.py": "eb64e3810b726ab1e57d303424a88adf0041fe5df516e22940421252098d9ee5", "src/pat/prepare.py": "d659d25646311ed8e5ee468442d80462e3b889745cd0e1438d2a8d0e7e6d9293", "src/pat/rotary.py": "e0d1249b6c5a0d55745f4028d512f85e4048ae5c5115d8dcca292b47434cb74a", "src/pat/serve.py": "485196a41c4cfd9ef9f89d579fe3e4078ead63669efda871b41387bbbf131c74", "src/pat/tokenizer.py": "77ce5ef143013252fbe21b8d76a3d79b3727eab304a708966f8a62bf926c9146", "src/pat/train.py": "644577c69eee6ef26f5ea8946d6a6c1aef6482b3cf5390e5d436fff4f9faab75", "src/pat/training.py": "3330afcc9183bb31816f141b74436ee8c4ff740b46273c5afa151048eacece07" }, "elapsed_seconds": 38.639570731000276, "completed_pacific": "2026-09-26 02:53:27 PDT", "scope": "Reload the exact completed continuation-training checkpoint through the current public API, run three ordinary-text prompts with greedy cached decoding, then independently reload and reproduce the first output. This is a functional endpoint check, not a text-quality benchmark.", "quality_observation": "The samples include repetition and an incorrect prime-number definition. Successful strict loading, finite valid-token cached decoding, and repeatability do not establish factual, mathematical, or programming accuracy.", "status": "passed" }, "fa32_continuation_endpoint": { "architecture": "FA", "model": "FA-32", "complete": true, "passed": true, "training_target_lexical_tokens": 200000000, "training_realized_lexical_tokens": 200087827, "training_updates": 2006, "training_source_tree_sha256": "dc7e68f6dd6e63bfdc56b2fb8d4e230f9cf17f44530489027040ac1d24af9216", "checkpoint_manifest_sha256": "68f9a21aeb474c4c3e9c9729680211bb6d4b0093da4486681457e735f19530f7", "model_weights_sha256": "1a4cc3df2d0cc680860918458c750e4cc32048c488544da0313bb53c05329a14", "strict_loads": 2, "tied_embedding_verified": true, "greedy_generation_identical_after_reload": true, "generation_uses_current_public_cached_api": true, "generation": [ { "prompt_tokens": 5, "generated_tokens": 24, "stop_reason": "length", "token_ids_sha256": "ee3387ec7fe2ffa23226dae5b72f1dc1a9811126f82f2da226b856dd3f7b7a6b" }, { "prompt_tokens": 12, "generated_tokens": 24, "stop_reason": "length", "token_ids_sha256": "a9e1ca1a5d307578512f326d21d21ff45800ed5f8432b5a6ac58ad1de53ddf72" }, { "prompt_tokens": 8, "generated_tokens": 24, "stop_reason": "length", "token_ids_sha256": "622c6af8f7354020cb87ff73aebd58d5aff229c4a0fcf72a9075a7c048ef8095" } ], "runtime": { "gpu": "NVIDIA H100 80GB HBM3", "torch": "2.11.0+cu128", "cuda": "12.8", "triton": "3.6.0" }, "public_inference_source_files": { "src/pat/__init__.py": "2bde6c86f162f864c978e703a78fe7b85257604d4f3e04b6bc1a0e0c73333c35", "src/pat/attention.py": "a0d61863a1c65beda70a1253878ec799099856379b341ea8f826cc7b9cd24e4e", "src/pat/checkpoint.py": "dfc3fe41c51ad42d66429e8f8d382ef4c95c8cebe61dffb3b940c2cfad36d925", "src/pat/config.py": "58cec92f71b229d4b5bdc460a9a5e1f5af61d2eeb0d22b8228a3af57a9c06350", "src/pat/data.py": "649e9f25c911feb0af4be5d9746c6e9dedec6e2677804245869093ab750235f4", "src/pat/generate.py": "24d2c3daa4d81baab025cdbb2524caa2f7c0fa81a3dbc445219753aed52dbce5", "src/pat/inference.py": "271c3eb7b426d19baead1ccb3067eff923d6cad8cf6ecfd4ceddebb4bff85493", "src/pat/kernels/__init__.py": "e7c17f234aecd5cf9d039adf65230c584e65fd10c7fd14a0f545f77f763862b5", "src/pat/kernels/attention.py": "ec980919ccd30659b9745fa15c792c4cf7e2398596aad1b5e11f5ac0f05f5682", "src/pat/kernels/decoding.py": "9eac6a9efbeada39937b4f7d4816d365ca915bee08dc0ddb0765665c87d1eb89", "src/pat/kernels/layout.py": "dd3413746f4b56ab3af4b593777d76768a9ff7127a6590e89fe47d30b9bc9cc2", "src/pat/losses.py": "10e42db2ee3e22a3b548fd9acc5a8a567e70afa27024f54ebda2ba35fe5d4018", "src/pat/model.py": "dd3c720308ce7a5f8502fb4eb4127982c98b64c9a21e1718f79d71e80b491225", "src/pat/packing.py": "6ba16848ec282771f17b9e447eb44ecd7060157e34b855cb32a67cca4a36261d", "src/pat/pat_cache.py": "eb64e3810b726ab1e57d303424a88adf0041fe5df516e22940421252098d9ee5", "src/pat/prepare.py": "d659d25646311ed8e5ee468442d80462e3b889745cd0e1438d2a8d0e7e6d9293", "src/pat/rotary.py": "e0d1249b6c5a0d55745f4028d512f85e4048ae5c5115d8dcca292b47434cb74a", "src/pat/serve.py": "485196a41c4cfd9ef9f89d579fe3e4078ead63669efda871b41387bbbf131c74", "src/pat/tokenizer.py": "77ce5ef143013252fbe21b8d76a3d79b3727eab304a708966f8a62bf926c9146", "src/pat/train.py": "644577c69eee6ef26f5ea8946d6a6c1aef6482b3cf5390e5d436fff4f9faab75", "src/pat/training.py": "3330afcc9183bb31816f141b74436ee8c4ff740b46273c5afa151048eacece07" }, "elapsed_seconds": 38.475261863990454, "completed_pacific": "2026-09-26 01:58:24 PDT", "scope": "Reload the exact completed continuation-training checkpoint through the current public API, run three ordinary-text prompts with greedy cached decoding, then independently reload and reproduce the first output. This is a functional endpoint check, not a text-quality benchmark.", "quality_observation": "The samples contain repetition and an incorrect prime-number statement. Successful loading, finite valid-token decoding, and repeatability do not establish factual, mathematical, or programming accuracy.", "status": "passed" } }, "pending": [], "generation_scope": "PAT and FA caches match their original cached decoding computations within the documented checks. CLI generation from complete unauthenticated checkpoint downloads and local HTTP behavior passed. No throughput or response-quality claim.", "code_identity_policy": { "embedded_code_revision": "intentionally null to avoid self-reference", "release_identity": "External source ZIP SHA256 and immutable hosted code revision, supplied in the final handoff", "included_file_identity": "SHA256SUMS inside the source ZIP", "experiment_identity": "Per-check source_snapshot_sha256 identifies the executed snapshot independently of the final archive" }, "execution_source_compatibility": { "status": "passed", "PAT": { "source_snapshot_sha256": "ac87fc0fcc8dae5e6890bca5da11103fd82116544ec25724f15112d75b5b73fe", "all_current_python_files_equal_execution_snapshot": true }, "FA": { "source_snapshot_sha256": "dc7e68f6dd6e63bfdc56b2fb8d4e230f9cf17f44530489027040ac1d24af9216", "changed_or_added_python_files": [ "src/pat/checkpoint.py", "src/pat/generate.py", "src/pat/inference.py", "src/pat/kernels/decoding.py", "src/pat/model.py", "src/pat/pat_cache.py", "src/pat/serve.py" ], "training_path_unchanged_under_reviewed_source_comparison": true, "scope": "The FA snapshot predates cached-inference modules, explicit anonymous download, and PAT-only fullgraph compilation changes. Other training files are byte-identical; model/checkpoint AST comparison removes only documentation, the download function not called by training, and fullgraph on PAT memory/transition compilation. The FA training computation is unchanged." } }, "publication_attestation": { "location": "External publication receipt and source ZIP checksum sidecar", "scope": "Final archive construction, immutable code revision, and unauthenticated ZIP download are attested externally. This record does not embed the enclosing archive hash or commit." }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# Release verification record
This record reports completed artifact and execution checks for the released32-layer models, together with their measured limits. The corresponding[structured record](verification.json) identifies hashes, counts, scopes, andthe strict small-resume criterion that remained unmet.
## Completed checks
| Check | Evidence and scope ||---|---|| Checkpoint selection | PAT-32 and FA-32 are the exact completed 9.52B-token pair; both reached 9520047061 lexical tokens at update 95473 || Tensor export | Every persisted tensor equals the selected source tensor exactly; model loading is strict and retains tied embeddings || Parameter counts | PAT-32: 1715105280; FA-32: 1715104256; tied embedding counted once || Tokenizer | Ordinary-text encoding checked against the source tokenizer, including literal control spellings; the original tokenizer artifact is unchanged || Data boundaries | Preparation preserves lexical content, final EOD placement, and independent pieces; altered token files fail hash verification || Batch planner | Exact agreement with the source planner in 85 training and 63 validation comparisons, including the real verification datasets || Objective accounting | CPU gradient checks cover unequal rank and accumulation counts for both PAT and FA || Learning-rate schedule | Warmup, stable, cooldown, endpoint, and exact token rounding checked || Resume admission | Changed data, validation data, horizon, world size, invalid counters, and partial optimizer windows are rejected || Generation sampling | Internal IDs cannot be emitted; greedy and nucleus selection and invalid inputs are checked || CPU test suite | 29 tests passed against the newly installed wheel, covering data, training accounting, generation sampling, and checkpoints || Floating-point objective order | PAT and FA regression fixtures detect the one-ULP gradient difference caused by collapsing normalization factors || Fresh initialization | All mapped parameters match the original implementation for small PAT and FA configurations, including PAT allocation transitions || Package installation | Current implementation built and installed outside the source tree; all installed Python files equal the source bytes, including loss/cache/kernel modules, and bundled tokenizer/notices are present || Command interfaces | All five installed command modules accept `--help`: prepare, train, generate, serve, checkpoint || Static checks | Ruff passes for source, tests, and scripts |
Portable weight-file SHA256 values:
```textPAT-32 be0a5fd13fbd6d80f8a488f25446a5db246c01c0090c22656d0eda91a344a5e3FA-32 994d4b7dcd1ff6a2a612860cf3c9efe096a1739561ac3714f032ffd9a17aa17f```
## Measured GPU checks
The GPU comparisons use NVIDIA H100 80GB HBM3, PyTorch 2.11.0+cu128,CUDA runtime 12.8, and Triton 3.6.0.
| Check | Measured result and scope ||---|---|| FA-32 forward comparison | Bitwise-equal logits in eight boundary and packed-batch cases, next-token prediction, and real text pieces of 16123 and 16384 lexical tokens || FA-32 greedy generation | Three prompts and 72 generated tokens; all compared next-token logits and selected tokens equal the original implementation || FA-32 cached generation | Bitwise-equal native/release prefill at eight prompt lengths, 32 append steps, full-context prefill with 16383 content tokens plus BOS, and all 72 greedy step logits/tokens. Cache-capacity overflow is rejected || PAT-32 cached generation | All 216 greedy tokens across nine prompts equal the original cached decoding core. A separate 35-step trace has bitwise-equal logits and cache tensors at every layer across two complete chunk commits. Small-geometry checks cover 316 steps, chunk sizes 16/32, allocation transitions, context capacity, overflow, and reuse after compilation || FA-32 fresh-process compiled training | Loss is exactly 3.5339269638061523 on 143 lexical tokens and 144 valid targets. 546 of 547 gradient tensors are bitwise equal; the tied embedding differs by at most 1.862645149230957e-9, matching the maximum difference between repeated native runs. Post-AdamW maximum difference is 3.725290298461914e-9 || PAT-32 repeated compiled training and AdamW | Three original and three released draws have identical loss within the control. Each released draw matches an observed original decoder-gradient variant: 418 of 421 gradients bitwise equal, remaining maximum difference 1.49e-8. Matched updated weights are exact for 419 of 421 tensors, with maximum difference 3.73e-8. Native/native and native/released maximum gradient and optimizer spreads are equal || Small PAT distributed save/resume | Two GPUs, five updates, 1260 lexical tokens; maximum absolute resumed/uninterrupted weight difference 1.862645149230957e-9 || Small FA distributed save/resume | Two GPUs, two accumulation microsteps, three updates, 1512 lexical tokens; maximum absolute resumed/uninterrupted weight difference 1.0058283805847168e-7 || Current FA save/resume | One GPU, two accumulation microsteps, seven updates and 1764 lexical tokens, crossing an epoch boundary. Training/validation losses, RNG, token clock, and data cursor match; maximum weight difference 7.45e-9 and optimizer-state difference 3.73e-9 || Current PAT save/resume | Three layers with 2/8/2 memory slots; one GPU, two accumulation microsteps, seven updates and 1764 lexical tokens. Training losses and final validation match exactly; maximum weight difference 3.73e-9 and optimizer-state difference 9.31e-10. One intermediate validation differs by 6.20e-5, exceeding the preset 2e-5 tolerance; the aggregate test is not marked passed || FA-32 full holdout | All 15002471 lexical tokens evaluated. Long and short lexical CE differ from their archived results by 1.70e-8 and 3.56e-9; inclusive CE matches both archived splits exactly. The structured record also retains fresh native-run comparisons || PAT-32 full holdout | All 15002471 lexical tokens evaluated. All 612 original/released inclusive CE batch means are bitwise equal; lexical totals differ by at most 1.07e-8. Both current implementations differ from archived lexical CE by approximately 8–10e-6, within the declared 1e-4 archive tolerance || Causality and document isolation | Both released 32-layer checkpoints pass 14 future-text mutations and 10 other-document mutations with bitwise-unchanged protected logits. Pairs retain identical shapes and document boundaries; lengths reach 16384 tokens for causality and 2048/4096 tokens for packed-document isolation || Anonymous downloads | Both immutable public bundles freshly downloaded with authentication disabled, complete bytes/hash verification, and successful generation from the downloaded weights || Cached HTTP integration | Both local exported bundles, whose hashes equal the public downloads, passed readiness, 64-token cached continuation, invalid-request rejection, and empty-prompt rejection |
The small distributed resume tests do not qualify full-model resume behavior.The current one-GPU checks include the final loss and compiler settings and verifyoptimizer moments, RNG states, counters, batch-plan identity, and checkpointmanifests including tokenizer notices. The PAT intermediate-validation discrepancyis retained explicitly; it does not appear in its training-loss records or finalvalidation. Validation and save intervals restart from the restored token count.Fresh evaluation of the two saved intermediate checkpoints reproduces thevalidation difference in one process. Replacing the resumed model's weightswith the continuous run's weights restores exact agreement, while repeatingthe continuous model is also exact. The difference therefore follows the savedweights; the declared validation tolerance remains exceeded.An additional original-implementation evaluation control agrees exactly withthe released evaluator for every batch of both saved weight variants and arepeat. The differing batch sum is 1325.125 versus 1325.0625, producing thesame 6.2003968253e-5 mean-loss shift in both implementations. This separatecontrol passes and identifies shared evaluation sensitivity to those weightvariants. It does not rerun original-implementation resume training or changethe failed strict resume-validation result.The FA training comparison uses a fresh process, the production loss path,the default compiler limits, and zero graph breaks. Full-model 200M-tokenchecks remain separate from these bounded comparisons.
PAT backward accumulation is nondeterministic in both implementations. In thepaired optimizer control, native/native and native/released maximum gradientdifferences are both 3.7228e-4 (maximum relative L2 difference 1.5778%); theirmaximum updated-weight differences are both 4.9855e-4. An independent gradientcontrol also has equal observed native/native and native/released spreads.The controls' absolute losses differ from each other, although original/releasedlosses agree within each control. These finite observations support numericalcompatibility under the measured native variability; they do not establishbitwise backward execution, a universal error bound, or identical trainingtrajectories. The structured record preserves every control separately.
Generation comparisons validate that inference preserves checkpoint behavior.For the tested France prompt, PAT repeatedly generated the Paris statement;FA repeated itself and incorrectly located Paris in southern France. Theseare pretrained continuation models. Matching original output does not establishresponse quality.
The full FA-32 continuation checkpoint at 100,044,446 lexical tokens was restored on two GPUs with two accumulation microsteps. Its next update reached 100,144,085 tokens with exactly equal loss, lexical loss, token count, and learning rate; gradient norm differed by 7.45e-9. All 547 optimizer counters advanced once, data cursor and per-rank RNG checks passed, and the newly saved bundle passed complete hash verification and strict reload. This resume check is separate from completion of the 200M-token run.
The full PAT-32 cached decoder also passed an authentic 16,319-token prefix followed by 64 greedy predictions. Ten prefill checkpoints, every compared prediction, and all 95 endpoint key/value cache comparisons were bitwise equal to the original cache. The joint native/release check took 907 seconds; this sequential-prefix qualification is not a throughput benchmark.
<!-- completed-continuation-checks:start -->## Completed 200M-token continued-training checks
| Model | Target | Realized lexical tokens | Updates | Final training lexical CE | Final holdout lexical CE ||---|---:|---:|---:|---:|---:|| PAT-32 | 200000000 | 200087827 | 2006 | 2.5846563102 | 2.6087471529 || FA-32 | 200000000 | 200087827 | 2006 | 2.6270604654 | 2.6396932363 |
Both runs completed successfully with finite recorded losses and gradient norms, exact token-clock learning-rate schedules, complete holdout evaluation, and verified final model/optimizer manifests. The published downloads remain the original 9.52B checkpoints; continuation endpoints are separate verification artifacts.
Each final continuation checkpoint was strictly loaded twice through the current public cached-inference API. Three ordinary-text prompts were generated, and the first output was reproduced after independent reload. These are functional endpoint checks, not response-quality measurements.
The FA execution snapshot predates cached-inference additions and PAT-only compilation fixes. A scoped source comparison confirms that its training computation is unchanged in the final package. All final public Python files match the PAT execution snapshot. The structured record retains both executed snapshot identities and the comparison scope.
Full-model resume checks restore an actual intermediate checkpoint and execute one complete optimizer update. Their measured differences are:
| Model | Restored lexical tokens | Tokens after replay | Loss difference | Lexical-loss difference | Gradient-norm difference ||---|---:|---:|---:|---:|---:|| PAT-32 | 100044446 | 100144085 | 2.29996063e-05 | 2.34832119e-05 | 4.391372204e-05 || FA-32 | 100044446 | 100144085 | 0 | 0 | 7.450580597e-09 |
Both functional state audits verify optimizer-step advancement, token/LR clocks, data cursor and plan, per-rank random state, and saved-manifest integrity. Numerical deltas are reported separately; these one-update checks do not establish identical complete trajectories. The earlier strict small-PAT validation failure and its separate passing native-evaluation control remain unchanged.<!-- completed-continuation-checks:end -->
The training verification corpus contains 220000236 lexical tokens fromcomplete documents in stored corpus order, and the full paper validation setcontains 15002471 lexical tokens. The subset's stored order and fingerprintsare retained in the private experiment record. It is a real-text verificationsubset and does not recreate the full pretraining corpus's shuffled trajectory.
PAT and FA cached decoding are qualified against their original cached computations.The generation command and local HTTP interfaces passed their bounded checks.PAT prompt ingestion uses sequential cached appends. Optimized prefill andcached-decoding throughput are outside these measured checks.
## Identifying the released code
Use the final source ZIP's external SHA256 file and its immutable hostedrevision to identify a release. Inside the ZIP, `SHA256SUMS` identifies everyincluded source, configuration, documentation, and tokenizer file. The`code_revision` field in the structured record is intentionally null: embeddingthe enclosing archive's own digest or commit would change the object beingidentified. The final handoff supplies the external archive hash and pinnedcode URL. Per-experiment source-snapshot hashes identify the code executed bythose experiments and are distinct from the final archive and hosting revision.12345678910111213141516171819202122232425262728293031323334353637[build-system]requires = ["setuptools>=77"]build-backend = "setuptools.build_meta"
[project]name = "pat-release"version = "0.1.0"description = "Predictive Abstraction Transformer: training and text generation"readme = "README.md"requires-python = ">=3.11"license-files = ["THIRD_PARTY_NOTICES/tokenizer/LICENSE", "THIRD_PARTY_NOTICES.md"]dependencies = [ "torch==2.11.0", "triton==3.6.0", "liger-kernel==0.8.1", "numpy>=1.26,<3", "safetensors==0.5.3", "tokenizers==0.22.1", "huggingface-hub==0.36.0",]
[project.optional-dependencies]test = ["pytest>=8,<10", "ruff>=0.11"]
[tool.setuptools.packages.find]where = ["src"]
[tool.setuptools.package-data]pat = ["assets/*"]
[tool.pytest.ini_options]testpaths = ["tests"]pythonpath = ["src"]
[tool.ruff]line-length = 100target-version = "py311"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990#!/usr/bin/env python3"""Build a reproducible source ZIP from an explicit publication allowlist.
The archive contains code, documentation, configurations, tests, and thetokenizer. Model weights are distributed as separate verified checkpoints."""
from __future__ import annotations
import argparseimport hashlibimport zipfilefrom pathlib import Path
ROOT_FILES = ("README.md", "pyproject.toml", ".gitignore", "THIRD_PARTY_NOTICES.md")PATTERNS = ( "src/pat/*.py", "src/pat/kernels/*.py", "src/pat/assets/tokenizer.json", "src/pat/assets/tokenizer_contract.json", "src/pat/assets/tokenizer_license.txt", "CHECKPOINTS.json", "configs/*.json", "docs/*.md", "docs/verification.json", "scripts/train_*.sh", "scripts/build_supplement.py", "tests/test_*.py", "THIRD_PARTY_NOTICES/tokenizer/LICENSE",)
def source_files(root: Path) -> list[Path]: paths = set() for name in ROOT_FILES: path = root / name if not path.is_file(): raise FileNotFoundError(f"Required supplement file is missing: {name}") paths.add(path) for pattern in PATTERNS: paths.update(root.glob(pattern)) for path in paths: if path.is_symlink() or not path.is_file(): raise ValueError(f"Supplement sources must be regular files: {path.relative_to(root)}") if not path.resolve().is_relative_to(root.resolve()): raise ValueError("Supplement source resolves outside the repository") return sorted(paths, key=lambda path: path.relative_to(root).as_posix())
def build(root: Path, output: Path) -> dict: paths = source_files(root) if output.exists(): raise FileExistsError(output) output.parent.mkdir(parents=True, exist_ok=True) sums = [] with zipfile.ZipFile(output, "x", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for path in paths: relative = path.relative_to(root).as_posix() data = path.read_bytes() sums.append(f"{hashlib.sha256(data).hexdigest()} {relative}\n") info = zipfile.ZipInfo(f"PAT/{relative}", date_time=(1980, 1, 1, 0, 0, 0)) info.compress_type = zipfile.ZIP_DEFLATED info.create_system = 3 executable = path.suffix == ".sh" or relative == "scripts/build_supplement.py" info.external_attr = (0o100755 if executable else 0o100644) << 16 archive.writestr(info, data) info = zipfile.ZipInfo("PAT/SHA256SUMS", date_time=(1980, 1, 1, 0, 0, 0)) info.compress_type = zipfile.ZIP_DEFLATED info.create_system = 3 info.external_attr = 0o100644 << 16 archive.writestr(info, "".join(sums)) with zipfile.ZipFile(output) as archive: if archive.testzip() is not None: raise RuntimeError("ZIP integrity check failed") digest = hashlib.sha256(output.read_bytes()).hexdigest() output.with_suffix(output.suffix + ".sha256").write_text(f"{digest} {output.name}\n") return {"archive": str(output), "sha256": digest, "source_files": len(paths)}
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, help="New ZIP path; existing archives are never overwritten") parser.add_argument("--list", action="store_true", help="Inspect the allowlist without writing an archive") args = parser.parse_args() root = Path(__file__).resolve().parents[1] if args.list: for path in source_files(root): print(path.relative_to(root).as_posix()) elif args.output: import json print(json.dumps(build(root, args.output), indent=2)) else: parser.error("provide --output or --list")
if __name__ == "__main__": main()12345678910111213141516#!/usr/bin/env bash# FA-32: two ranks, two 25K-token microbatches per rank, about 100K tokens/update.# Required: DATA, VALIDATION. OUTPUT defaults to runs/fa32.# Additional arguments are passed to the trainer, e.g. --resume runs/fa32/step-....set -euo pipefail
: "${DATA:?Set DATA to the prepared training directory}": "${VALIDATION:?Set VALIDATION to the prepared validation directory}"PAT_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
exec torchrun --standalone --nproc_per_node=2 -m pat.train \ --config "$PAT_ROOT/configs/fa32.json" \ --data "$DATA" \ --validation "$VALIDATION" \ --output "${OUTPUT:-runs/fa32}" \ "$@"1234567891011121314151617#!/usr/bin/env bash# Start a 200M-token training check from the released FA-32 weights.# This starts a new optimizer and schedule; it does not resume the paper run.set -euo pipefail
: "${DATA:?Set DATA to the prepared training directory}": "${VALIDATION:?Set VALIDATION to the prepared validation directory}": "${CHECKPOINT:?Set CHECKPOINT to the verified FA-32 model bundle}"PAT_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
exec torchrun --standalone --nproc_per_node=2 -m pat.train \ --config "$PAT_ROOT/configs/fa32_200m.json" \ --data "$DATA" \ --validation "$VALIDATION" \ --output "${OUTPUT:-runs/fa32-200m}" \ --init-checkpoint "$CHECKPOINT" \ "$@"12345678910111213141516#!/usr/bin/env bash# PAT-32: four ranks, one 25K-token microbatch per rank, about 100K tokens/update.# Required: DATA, VALIDATION. OUTPUT defaults to runs/pat32.# Additional arguments are passed to the trainer, e.g. --resume runs/pat32/step-....set -euo pipefail
: "${DATA:?Set DATA to the prepared training directory}": "${VALIDATION:?Set VALIDATION to the prepared validation directory}"PAT_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
exec torchrun --standalone --nproc_per_node=4 -m pat.train \ --config "$PAT_ROOT/configs/pat32.json" \ --data "$DATA" \ --validation "$VALIDATION" \ --output "${OUTPUT:-runs/pat32}" \ "$@"1234567891011121314151617#!/usr/bin/env bash# Start a 200M-token training check from the released PAT-32 weights.# This starts a new optimizer and schedule; it does not resume the paper run.set -euo pipefail
: "${DATA:?Set DATA to the prepared training directory}": "${VALIDATION:?Set VALIDATION to the prepared validation directory}": "${CHECKPOINT:?Set CHECKPOINT to the verified PAT-32 model bundle}"PAT_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
exec torchrun --standalone --nproc_per_node=4 -m pat.train \ --config "$PAT_ROOT/configs/pat32_200m.json" \ --data "$DATA" \ --validation "$VALIDATION" \ --output "${OUTPUT:-runs/pat32-200m}" \ --init-checkpoint "$CHECKPOINT" \ "$@"123456"""Publication training and inference for PAT and FA."""
from .config import PATConfigfrom .model import PATModel
__all__ = ["PATConfig", "PATModel"]123456789101112131415161718192021{ "vocab_size": 50304, "lexical_ids": [ 0, 50255 ], "eod_id": 50256, "pad_id": 50257, "bos_id": 50258, "eoc_id": 50259, "vocabulary_padding_ids": [ 50260, 50303 ], "tokenizer_sha256": "67df57fd93740b7feb7462529fffb9edc0c7c9a30724489472385980b5bdd0b5", "automatic_special_tokens": false, "generation_valid_ids": [ 0, 50256 ]}123456789101112131415161718192021222324Modified MIT License
Software Copyright (c) 2019 OpenAI
We don’t claim ownership of the content you create with GPT-2, so it is yours to do with as you please.We only ask that you use GPT-2 responsibly and clearly indicate your content was created using GPT-2.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software andassociated documentation files (the "Software"), to deal in the Software without restriction,including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,subject to the following conditions:
The above copyright notice and this permission notice shall be includedin all copies or substantial portions of the Software.The above copyright notice and this permission notice need not be includedwith content created by the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERSBE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USEOR OTHER DEALINGS IN THE SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""Shared decoder layers and the two fixed attention implementations."""
from __future__ import annotations
import math
import torchfrom torch import nnfrom torch.nn import functional as Ffrom torch.nn.attention import SDPBackend, sdpa_kernel
from .config import PATConfigfrom .rotary import RotaryEmbedding, normalize_key, normalize_query
class SwiGLU(nn.Module): def forward(self, values: torch.Tensor) -> torch.Tensor: gate, value = values.chunk(2, dim=-1) return F.silu(gate) * value
class DecoderLayer(nn.Module): """Pre-LayerNorm attention and SwiGLU.
The packed projection stores Q, K, V in that order. Later PAT layers compute Q only for current rows, and K/V for current and summary sources. Summary rows skip the feed-forward sublayer. FA keeps its producer's separate Q/K/V projections, so importing a checkpoint preserves GEMMs. """
def __init__(self, config: PATConfig, index: int) -> None: super().__init__() width = config.d_model self.n_heads, self.head_dim = config.n_heads, config.head_dim self.qk_norm_eps = 1e-6 self.norm1 = nn.LayerNorm(width, eps=1e-6) self.is_pat = config.architecture == "PAT" if self.is_pat: self.qkv_proj = nn.Linear(width, 3 * width) else: self.q_proj = nn.Linear(width, width) self.k_proj = nn.Linear(width, width) self.v_proj = nn.Linear(width, width) self.out_proj = nn.Linear(width, width) self.qk_log_scale = nn.Parameter( torch.full((config.n_heads,), math.log(config.qk_scale(index)), dtype=torch.float32) ) self.norm2 = nn.LayerNorm(width, eps=1e-6) base = round(width * config.ffw_mult_by_layer[index]) inner = max(8, round((2.0 / 3.0) * base / 8) * 8) self.mlp = nn.Sequential(nn.Linear(width, 2 * inner), SwiGLU(), nn.Linear(inner, width)) self.rope = RotaryEmbedding(config.head_dim)
def prepare(self, hidden, positions, key_positions): normalized = self.norm1(hidden) token_count = int(hidden.size(0)) if self.is_pat: q_projected, k_projected, v_projected = self.qkv_proj(normalized).split( self.n_heads * self.head_dim, dim=-1 ) q = q_projected.view(token_count, self.n_heads, self.head_dim) k = k_projected.view(token_count, self.n_heads, self.head_dim) v = v_projected.view(token_count, self.n_heads, self.head_dim) else: q = self.q_proj(normalized).view(token_count, self.n_heads, self.head_dim) k = self.k_proj(normalized).view(token_count, self.n_heads, self.head_dim) v = self.v_proj(normalized).view(token_count, self.n_heads, self.head_dim) raw_key = k if self.is_pat: q = self.rope(q, positions) k = self.rope(k, key_positions) else: q, k = self.rope.apply_pair(q, k, positions) q = normalize_query(q, self.qk_log_scale, self.head_dim, self.qk_norm_eps) k = normalize_key(k, self.qk_norm_eps) # Preserve the producer's compile outputs, including the raw key view. # Removing that view changes saved-intermediate rounding in backward. return q.contiguous(), k.contiguous(), v.contiguous(), raw_key
def prepare_with_memory( self, combined, positions, current_marker, memory_marker, memory_positions, key_positions ): current_tokens = int(current_marker.size(0)) memory_start = int(memory_marker.size(0)) total_tokens = int(combined.size(0)) normalized = self.norm1(combined) width = self.n_heads * self.head_dim q_projected = F.linear( normalized[:current_tokens], self.qkv_proj.weight[:width], self.qkv_proj.bias[:width] ) kv = F.linear(normalized, self.qkv_proj.weight[width:], self.qkv_proj.bias[width:]) k_projected, v_projected = kv.split(width, dim=-1) q_raw = q_projected.view(current_tokens, self.n_heads, self.head_dim) k_raw_all = k_projected.view(total_tokens, self.n_heads, self.head_dim) value_all = v_projected.view(total_tokens, self.n_heads, self.head_dim) k_raw = k_raw_all[:current_tokens] value = value_all[:current_tokens] query = self.rope(q_raw, positions) key = self.rope(k_raw, key_positions) query = normalize_query(query, self.qk_log_scale, self.head_dim, self.qk_norm_eps) key = normalize_key(key, self.qk_norm_eps) memory_positions = memory_positions.to(device=k_raw_all.device) memory_key = self.rope(k_raw_all[memory_start:], memory_positions) memory_key = normalize_key(memory_key, self.qk_norm_eps) return ( query.contiguous(), key.contiguous(), value.contiguous(), k_raw, memory_key.contiguous(), value_all[memory_start:].contiguous(), )
def finish(self, residual, context, lexical_tokens): hidden = residual + self.out_proj(context.reshape(context.size(0), -1)).to(residual.dtype) if not self.is_pat: return hidden + self.mlp(self.norm2(hidden)) lexical = hidden[:lexical_tokens] lexical = lexical + self.mlp(self.norm2(lexical)).to(hidden.dtype) return torch.cat((lexical, hidden[lexical_tokens:]), dim=0)
class MemoryTransition(nn.Module): """Learned interval-overlap map, independent for each attention head."""
def __init__(self, config: PATConfig, boundary: int) -> None: super().__init__() fan_in, fan_out = config.memory_slots[boundary : boundary + 2] source = torch.arange(fan_in, dtype=torch.float64, device="cpu") target = torch.arange(fan_out, dtype=torch.float64, device="cpu") overlap = ( torch.minimum((target[:, None] + 1) / fan_out, (source[None, :] + 1) / fan_in) - torch.maximum(target[:, None] / fan_out, source[None, :] / fan_in) ).clamp_min(0) matrix = overlap * fan_out if fan_in > 1: generator = torch.Generator(device="cpu").manual_seed( (config.seed + 1_000_003 * (boundary + 1)) % ((1 << 63) - 1) ) noise = torch.randn( matrix.shape, generator=generator, dtype=torch.float64, device="cpu" ) centered = noise - noise.mean(dim=1, keepdim=True) noise = centered * ( torch.linalg.vector_norm(matrix, dim=1, keepdim=True) / torch.linalg.vector_norm(centered, dim=1, keepdim=True) ) matrix = matrix + 0.01 * noise self.matrix = nn.Parameter(matrix.float().unsqueeze(0).repeat(config.n_heads, 1, 1))
def forward(self, summaries: torch.Tensor) -> torch.Tensor: rows, width, features = summaries.shape groups = self.matrix.size(0) grouped = summaries.reshape(rows, width, groups, features // groups) matrix = self.matrix.to(device=summaries.device, dtype=summaries.dtype) return ( torch.einsum("goi,rigd->rogd", matrix, grouped) .reshape(rows, self.matrix.size(1), features) .contiguous() )
def full_attention(q, k, v, piece_lengths: tuple[int, ...], context_length: int): """Piece-local causal FlashAttention, with a fixed sliding window.""" if q.device.type != "cuda": raise RuntimeError("FA requires CUDA FlashAttention") if q.dtype not in {torch.float16, torch.bfloat16}: raise RuntimeError("FA requires BF16 or FP16 autocast") maximum = max(piece_lengths) equal = len(set(piece_lengths)) == 1 if equal and maximum <= context_length: shape = (len(piece_lengths), maximum, q.size(1), q.size(2)) query, key, value = (x.reshape(shape).permute(0, 2, 1, 3) for x in (q, k, v)) with sdpa_kernel(SDPBackend.FLASH_ATTENTION): result = F.scaled_dot_product_attention( query, key, value, dropout_p=0.0, is_causal=True ) return result.permute(0, 2, 1, 3).reshape_as(q).contiguous() from torch.nn.attention.varlen import varlen_attn
offsets = [0] for length in piece_lengths: offsets.append(offsets[-1] + length) offsets = torch.tensor(offsets, device=q.device, dtype=torch.int32) window = (context_length - 1, 0) if maximum > context_length else (-1, 0) return varlen_attn( q.contiguous(), k.contiguous(), v.contiguous(), offsets, offsets, max_q=maximum, max_k=maximum, window_size=window, ).contiguous()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171"""Portable, hash-verified model checkpoints with tensor-only serialization."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport reimport shutilimport tempfilefrom pathlib import Path
import torchfrom safetensors.torch import load_file, save_file
from .config import PATConfigfrom .tokenizer import Tokenizer
FORMAT = "pat-checkpoint-v1"WEIGHTS = "model.safetensors"REQUIRED_FILES = ("config.json", WEIGHTS, "tokenizer.json", "TOKENIZER_LICENSE.txt", "metadata.json")
def sha256(path: str | Path) -> str: digest = hashlib.sha256() with Path(path).open("rb") as stream: for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): digest.update(block) return digest.hexdigest()
def verify_checkpoint(directory: str | Path) -> dict: """Verify the entire inference bundle before loading its weights.""" directory = Path(directory) manifest = json.loads((directory / "manifest.json").read_text()) if manifest.get("format") != FORMAT: raise ValueError("Unsupported checkpoint format.") files = manifest.get("files", {}) if not set(REQUIRED_FILES).issubset(files): raise ValueError("Incomplete checkpoint manifest.") for name, expected in files.items(): if Path(name).name != name or name in (".", ".."): raise ValueError("Checkpoint filenames must be simple basenames.") path = directory / name if not path.is_file() or path.stat().st_size != expected["size_bytes"]: raise ValueError(f"Missing or incomplete checkpoint file: {name}") if sha256(path) != expected["sha256"]: raise ValueError(f"Checkpoint SHA-256 mismatch: {name}") Tokenizer(directory / "tokenizer.json") return manifest
def load_checkpoint( directory: str | Path, device: str | torch.device = "cpu", dtype: torch.dtype | None = None,): """Load a released model in evaluation mode, preserving tied embeddings.
The default retains the stored precision. Passing ``dtype=torch.bfloat16`` casts weights for inference; autocast can instead preserve FP32 weights. """ from .model import PATModel
directory = Path(directory) verify_checkpoint(directory) config = PATConfig.from_dict(json.loads((directory / "config.json").read_text())) weights = load_file(str(directory / WEIGHTS), device="cpu") if "lm_head.weight" in weights: raise ValueError("The tied output embedding must be stored only once.") weights["lm_head.weight"] = weights["token_embed.weight"] with torch.device("meta"): model = PATModel(config) model.load_state_dict(weights, strict=True, assign=True) model.lm_head.weight = model.token_embed.weight model = model.to(device=device, dtype=dtype) return model.eval()
def save_weights( config: PATConfig, state: dict[str, torch.Tensor], directory: str | Path, metadata: dict | None = None,) -> Path: """Write a new inference bundle atomically; never overwrite an existing one.
The metadata is application supplied JSON. Optimizer and data cursor state belong to the separate training resume file written by the trainer. """ directory = Path(directory) if directory.exists(): raise FileExistsError(directory) directory.parent.mkdir(parents=True, exist_ok=True) if "token_embed.weight" not in state: raise ValueError("Missing token embedding.") if "lm_head.weight" in state and not torch.equal(state["token_embed.weight"], state["lm_head.weight"]): raise ValueError("Checkpoint requires tied input and output embeddings.") stage = Path(tempfile.mkdtemp(prefix=f".{directory.name}.", dir=directory.parent)) try: clean_state = { name: tensor.detach().cpu().contiguous() for name, tensor in state.items() if name != "lm_head.weight" } save_file(clean_state, str(stage / WEIGHTS), metadata={"format": FORMAT}) (stage / "config.json").write_text(json.dumps(config.to_dict(), indent=2) + "\n") (stage / "metadata.json").write_text(json.dumps(metadata or {}, indent=2) + "\n") shutil.copyfile(Path(__file__).parent / "assets" / "tokenizer.json", stage / "tokenizer.json") shutil.copyfile( Path(__file__).parent / "assets" / "tokenizer_license.txt", stage / "TOKENIZER_LICENSE.txt", ) manifest = {"format": FORMAT, "files": { name: {"sha256": sha256(stage / name), "size_bytes": (stage / name).stat().st_size} for name in REQUIRED_FILES }} (stage / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") stage.rename(directory) except BaseException: shutil.rmtree(stage, ignore_errors=True) raise return directory
def save_checkpoint(model, directory: str | Path, metadata: dict | None = None) -> Path: """Save model weights, architecture, tokenizer, and caller supplied metadata.""" return save_weights(model.config, model.state_dict(), directory, metadata)
def download_checkpoint(repo_id: str, revision: str, directory: str | Path) -> Path: """Download an explicitly selected immutable Hub model revision and verify it.""" from huggingface_hub import snapshot_download
if not re.fullmatch(r"[0-9a-f]{40}", revision): raise ValueError("Use the full 40-character commit revision, not a moving branch.") directory = Path(directory) if directory.exists(): raise FileExistsError(directory) directory.parent.mkdir(parents=True, exist_ok=True) stage = Path(tempfile.mkdtemp(prefix=f".{directory.name}.", dir=directory.parent)) try: snapshot_download(repo_id, revision=revision, local_dir=stage, token=False, allow_patterns=[*REQUIRED_FILES, "manifest.json"]) verify_checkpoint(stage) shutil.rmtree(stage / ".cache", ignore_errors=True) stage.rename(directory) except BaseException: shutil.rmtree(stage, ignore_errors=True) raise return directory
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) download = sub.add_parser("download", help="Download a pinned Hub model bundle.") download.add_argument("--repo", required=True) download.add_argument("--revision", required=True, help="Full immutable commit hash.") download.add_argument("--output", required=True, type=Path) verify = sub.add_parser("verify", help="Verify all files of a local bundle.") verify.add_argument("directory", type=Path) args = parser.parse_args() if args.command == "download": print(download_checkpoint(args.repo, args.revision, args.output)) else: verify_checkpoint(args.directory) print("Checkpoint verified.")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""The publication architecture, with only model geometry left configurable."""
from __future__ import annotations
import mathfrom dataclasses import asdict, dataclassfrom typing import Any
EOD_ID = 50_256PAD_ID = 50_257BOS_ID = 50_258EOC_ID = 50_259
@dataclass(frozen=True)class PATConfig: """PAT and its full-attention ablation share this fixed decoder contract.
``memory_slots`` gives the number of summary rows written at each layer. ``qk_key_counts`` and ``qk_reference_key_counts`` are corpus-calibrated visible-key quantiles, used once to initialize the learned QK scale. The reference uses two summary slots. They are required for PAT, so a new geometry cannot silently reuse another experiment's initialization. ``ce_chunk_size`` limits vocabulary-projection workspace, not attention. """
architecture: str = "PAT" d_model: int = 2048 n_heads: int = 32 n_layers: int = 32 vocab_size: int = 50_304 chunk_size: int = 16 context_length: int = 16_384 memory_slots: tuple[int, ...] = () ffw_mult_by_layer: tuple[float, ...] = () qk_key_counts: tuple[float, ...] = () qk_reference_key_counts: tuple[float, ...] = () seed: int = 42 ce_chunk_size: int = 1024
def __post_init__(self) -> None: if self.architecture not in {"PAT", "FA"}: raise ValueError("architecture must be PAT or FA") for name in ( "d_model", "n_heads", "n_layers", "vocab_size", "chunk_size", "context_length", "ce_chunk_size", ): value = getattr(self, name) if type(value) is not int or value <= 0: raise ValueError(f"{name} must be a positive integer") if self.vocab_size <= EOC_ID or self.d_model % self.n_heads: raise ValueError( "vocabulary must contain the fixed special IDs; width must divide evenly into heads" ) if self.chunk_size not in {16, 32}: raise ValueError("chunk_size must be 16 or 32") if self.context_length % self.chunk_size or self.context_length < 4 * self.chunk_size: raise ValueError( "context_length must be a multiple of chunk_size and contain at least four chunks" ) if self.head_dim % 4 or not 20 <= self.head_dim <= 128: raise ValueError("head dimension must be divisible by four and lie in [20, 128]") slots = ( tuple(self.memory_slots) or ((2 if self.architecture == "PAT" else 0),) * self.n_layers ) multipliers = tuple(float(x) for x in self.ffw_mult_by_layer) or (4.0,) * self.n_layers if len(slots) != self.n_layers or any(type(x) is not int or x < 0 for x in slots): raise ValueError("memory_slots needs one nonnegative integer per layer") if self.architecture == "PAT" and any(x == 0 for x in slots): raise ValueError("PAT needs positive memory_slots in every layer") if self.architecture == "FA" and any(slots): raise ValueError("FA has zero memory_slots") if len(multipliers) != self.n_layers or any( not math.isfinite(x) or x < 1 for x in multipliers ): raise ValueError("ffw_mult_by_layer needs one finite multiplier >= 1 per layer") object.__setattr__(self, "memory_slots", slots) object.__setattr__(self, "ffw_mult_by_layer", multipliers) for name in ("qk_key_counts", "qk_reference_key_counts"): values = tuple(float(x) for x in getattr(self, name)) if self.architecture == "PAT": if len(values) != self.n_layers or any( not math.isfinite(x) or x < 1 for x in values ): raise ValueError(f"{name} needs one calibrated count >= 1 per layer for PAT") elif values: raise ValueError( "FA uses the fixed QK scale initialization and has no key-count calibration" ) object.__setattr__(self, name, values)
@property def head_dim(self) -> int: return self.d_model // self.n_heads
@property def max_memory_size(self) -> int: return self.context_length // self.chunk_size
def qk_scale(self, layer: int) -> float: if self.architecture == "FA": return 10.0 actual, reference = self.qk_key_counts[layer], self.qk_reference_key_counts[layer] if min(actual, reference) < 2: return 10.0 return 10.0 * math.log(actual * (actual - 1)) / math.log(reference * (reference - 1))
def to_dict(self) -> dict[str, Any]: return asdict(self)
@classmethod def from_dict(cls, values: dict[str, Any]) -> PATConfig: return cls(**values)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""Document pieces and the deterministic token-budget batching rule.
Each piece contains lexical token IDs and, only at a document's actual end,one EOD. BOS and abstraction slots are added by the model, never stored here."""
from __future__ import annotations
import hashlibimport heapqimport itertoolsimport jsonimport mathimport randomfrom pathlib import Path
import numpy as npimport torch
EOD = 50256
def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: while block := stream.read(8 * 1024 * 1024): digest.update(block) return digest.hexdigest()
class PieceDataset: """Read a prepared corpus without loading its token array into RAM.
Hash verification occurs once when opening the dataset. The resulting fingerprint is saved with training state and checked on every resume. """
def __init__(self, path: str | Path): self.path = Path(path) manifest_path = self.path / "manifest.json" self.fingerprint = file_sha256(manifest_path) self.manifest = json.loads(manifest_path.read_text()) if self.manifest.get("format") != "pat-document-pieces-1": raise ValueError("Unsupported dataset format; use python -m pat.prepare") expected = {"tokens.bin", "offsets.npy", "lexical_lengths.npy"} if set(self.manifest["files"]) != expected: raise ValueError("Dataset manifest must identify the three required arrays") for filename, digest in self.manifest["files"].items(): if file_sha256(self.path / filename) != digest: raise ValueError(f"Dataset file checksum mismatch: {filename}") self.tokens = np.memmap(self.path / "tokens.bin", mode="r", dtype="<u4") self.offsets = np.load(self.path / "offsets.npy", mmap_mode="r", allow_pickle=False) self.lexical_lengths = np.load( self.path / "lexical_lengths.npy", mmap_mode="r", allow_pickle=False ) if self.offsets.dtype != np.dtype("<i8") or self.offsets.ndim != 1: raise ValueError("Piece offsets must be a one-dimensional int64 array") if (self.offsets.size != self.lexical_lengths.size + 1 or self.offsets[0] != 0 or self.offsets[-1] != len(self.tokens) or np.any(np.diff(self.offsets) <= 0)): raise ValueError("Invalid document-piece offsets") if self.lexical_lengths.ndim != 1 or self.lexical_lengths.dtype != np.dtype("<i8"): raise ValueError("Lexical lengths must be a one-dimensional int64 array") self.routed_lengths = np.diff(self.offsets) if np.any(self.lexical_lengths <= 0): raise ValueError("Each document piece must have at least one lexical token") endings = self.routed_lengths - self.lexical_lengths if np.any((endings != 0) & (endings != 1)): raise ValueError("Only a terminal EOD may extend a lexical piece") if np.any(self.lexical_lengths > int(self.manifest["context_length"])): raise ValueError("Piece exceeds the declared context length")
def __len__(self) -> int: return len(self.lexical_lengths)
def __getitem__(self, index: int) -> torch.Tensor: start, end = int(self.offsets[index]), int(self.offsets[index + 1]) values = np.array(self.tokens[start:end], dtype=np.int64) final = int(self.routed_lengths[index] - self.lexical_lengths[index]) == 1 lexical = values[:-1] if final else values if np.any(lexical >= EOD) or (final and values[-1] != EOD): raise ValueError(f"Invalid lexical IDs or document boundary at piece {index}") return torch.from_numpy(values)
def _bucket_order(routed_lengths, lexical_lengths, budget, seed, epoch): """Shared fixed-width buckets and seeded within-bucket piece ordering.""" routed = np.asarray(routed_lengths, dtype=np.int64) lexical = np.asarray(lexical_lengths, dtype=np.int64) if routed.ndim != 1 or lexical.shape != routed.shape: raise ValueError("Lengths must be equally sized one-dimensional arrays") if budget <= 0 or epoch < 0 or np.any(lexical <= 0): raise ValueError("Budgets and lengths must be positive, epoch nonnegative") if np.any(routed < lexical): raise ValueError("Routed lengths cannot be smaller than lexical lengths") count = math.ceil(int(lexical.sum()) / budget) order = list(range(len(lexical))) random.Random(seed + epoch).shuffle(order) order.sort(key=lambda index: -((int(routed[index]) - 1) // 20)) return routed, lexical, count, order
def training_batches( routed_lengths: np.ndarray, lexical_lengths: np.ndarray, *, budget: int, seed: int, epoch: int, quantum: int = 1,) -> list[list[int]]: """Preallocate bins, place longest buckets first, then shuffle bins.
This reproduces the paper's Python Fisher–Yates shuffles and worst-fit tie breaking. A bin's budget counts lexical tokens. Pieces that do not fit the preallocated capacity are dropped for this epoch. The last incomplete distributed accumulation window is dropped without wrapping. """ if quantum <= 0: raise ValueError("The distributed optimizer window must be positive") _, lexical, count, order = _bucket_order( routed_lengths, lexical_lengths, budget, seed, epoch ) slots = list(range(count)) random.Random(f"{seed}:{epoch}:prealloc-slot-order").shuffle(slots) heap = [(-budget, ordinal, slot) for ordinal, slot in enumerate(slots)] heapq.heapify(heap) bins: list[list[int]] = [[] for _ in slots] ordinal = count for index in order: length = int(lexical[index]) if length > budget or not heap: continue negative_remaining, _, slot = heapq.heappop(heap) remaining = -negative_remaining if remaining >= length: bins[slot].append(index) remaining -= length if remaining > 0: heapq.heappush(heap, (-remaining, ordinal, slot)) ordinal += 1 emitted = [slot for slot, batch in enumerate(bins) if batch] random.Random(f"{seed}:{epoch}:final-batch-order").shuffle(emitted) emitted = emitted[: len(emitted) // quantum * quantum] return [bins[slot] for slot in emitted]
def validation_batches(dataset: PieceDataset, budget: int, *, seed: int = 42) -> list[list[int]]: """Preserve the paper's complete-coverage, fixed validation batch plan.
Length buckets retain seeded piece order. Preallocated slots are visited cyclically, with no slot/final shuffle. Capacity too small for the current bucket is reconsidered in the next bucket. Overflow receives extra bins, so every validation piece appears exactly once, including oversized ones. """ routed, lexical, count, order = _bucket_order( dataset.routed_lengths, dataset.lexical_lengths, budget, seed, 0 ) bins: list[list[int]] = [[] for _ in range(count)] used = [0] * count active = list(range(count)) cursor = 0 overflow: list[list[int]] = [] overflow_used = 0 for _, bucket in itertools.groupby(order, key=lambda index: (int(routed[index]) - 1) // 20): group = list(bucket) minimum = min(int(lexical[index]) for index in group) deferred = [] for index in group: length = int(lexical[index]) attempts, candidates = 0, len(active) placed = False while active and attempts < candidates: cursor %= len(active) slot = active[cursor] if budget - used[slot] < minimum: deferred.append(active.pop(cursor)) if not active or cursor >= len(active): cursor = 0 continue if used[slot] + length <= budget: bins[slot].append(index) used[slot] += length if used[slot] == budget: active.pop(cursor) if not active or cursor >= len(active): cursor = 0 else: cursor = (cursor + 1) % len(active) placed = True break attempts += 1 cursor = (cursor + 1) % len(active) if not placed: if not overflow or length > budget or overflow_used + length > budget: overflow.append([]) overflow_used = 0 overflow[-1].append(index) overflow_used += length active.extend(deferred) cursor = cursor % len(active) if active else 0 return [batch for batch in bins if batch] + overflow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Text generation with explicit document boundaries and a fixed CUDA path."""
from __future__ import annotations
import argparseimport jsonimport mathfrom pathlib import Path
import torch
from .checkpoint import load_checkpointfrom .inference import create_cachefrom .tokenizer import EOD_ID, Tokenizer
def sample(logits: torch.Tensor, temperature: float, top_p: float, generator) -> int: """Sample text or EOD; packing markers and unused rows are never emitted.""" if not math.isfinite(temperature) or temperature < 0 or not 0 < top_p <= 1: raise ValueError("temperature must be finite and nonnegative; top_p must be in (0, 1]") logits = logits.float().flatten()[: EOD_ID + 1] if not torch.isfinite(logits).all(): raise FloatingPointError("Nonfinite model logits") if temperature == 0: return int(logits.argmax().item()) probabilities = torch.softmax(logits / temperature, dim=-1) sorted_probs, indices = probabilities.sort(descending=True) # Retain the token which crosses the cumulative threshold, including at # least the most likely token. This avoids an empty distribution. remove = sorted_probs.cumsum(0) - sorted_probs > top_p sorted_probs[remove] = 0 chosen = torch.multinomial(sorted_probs, 1, generator=generator) return int(indices[chosen].item())
@torch.inference_mode()def generate( model, prompt: str, *, tokenizer: Tokenizer | None = None, max_new_tokens: int = 128, temperature: float = 0.0, top_p: float = 0.95, seed: int = 42,) -> dict: """Prefill one document, then decode with the checkpoint's fixed KV cache.
Context capacity includes BOS. PAT commits completed chunks to its memory internally; callers supply ordinary text without packing markers. """ tokenizer = tokenizer or Tokenizer() if type(max_new_tokens) is not int or max_new_tokens <= 0: raise ValueError("max_new_tokens must be a positive integer") if not math.isfinite(temperature) or temperature < 0 or not 0 < top_p <= 1: raise ValueError("Invalid sampling parameters") tokens = tokenizer.encode(prompt) if not tokens: raise ValueError("The prompt must contain at least one text token") if any(token >= EOD_ID for token in tokens): raise ValueError("The prompt contains reserved control tokens") if len(tokens) + max_new_tokens + 1 > model.config.context_length: raise ValueError("Prompt plus requested generation exceeds the configured context length") device = next(model.parameters()).device if device.type != "cuda": raise RuntimeError("PAT and FA generation require CUDA") generator = torch.Generator(device=device).manual_seed(seed) model.eval() generated = [] stop_reason = "length" with torch.autocast("cuda", dtype=torch.bfloat16): # The final selected token is returned without another forward pass. cache = create_cache(model, tokens, capacity=len(tokens) + max_new_tokens) for index in range(max_new_tokens): token = sample(cache.next_token_logits, temperature, top_p, generator) generated.append(token) if token == EOD_ID: stop_reason = "end_of_document" break if index + 1 < max_new_tokens: cache.append(token) return {"text": tokenizer.decode(generated), "token_ids": generated, "prompt_tokens": len(tokens), "generated_tokens": len(generated), "stop_reason": stop_reason}
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--checkpoint", type=Path, required=True, help="Verified released checkpoint directory") parser.add_argument("--prompt", required=True, help="Raw text prefix; no chat template is inserted") parser.add_argument("--max-new-tokens", type=int, default=128, help="Maximum generated tokens") parser.add_argument("--temperature", type=float, default=0.0, help="0 selects deterministic greedy decoding") parser.add_argument("--top-p", type=float, default=0.95, help="Nucleus mass for positive temperatures") parser.add_argument("--seed", type=int, default=42, help="Sampling seed") args = parser.parse_args() model = load_checkpoint(args.checkpoint, device="cuda") result = generate(model, args.prompt, tokenizer=Tokenizer(args.checkpoint / "tokenizer.json"), max_new_tokens=args.max_new_tokens, temperature=args.temperature, top_p=args.top_p, seed=args.seed) print(json.dumps(result, ensure_ascii=False))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Single-document cached decoding with each model's fixed attention path.
Use caches under ``torch.inference_mode()`` and CUDA BF16 autocast. The cachecapacity counts BOS as well as content tokens; exceeding it is an error."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import TYPE_CHECKING
import torchfrom torch.nn import functional as Ffrom torch.nn.attention import SDPBackend, sdpa_kernel
from .config import BOS_ID, EOD_ID
if TYPE_CHECKING: from .model import PATModel
def _attention(query, key, value, *, causal: bool): """Prefill attends causally; a newly appended query sees its entire prefix.""" query = query.permute(1, 0, 2).unsqueeze(0) key = key.permute(1, 0, 2).unsqueeze(0) value = value.permute(1, 0, 2).unsqueeze(0) with sdpa_kernel(SDPBackend.FLASH_ATTENTION): output = F.scaled_dot_product_attention( query, key, value, dropout_p=0.0, is_causal=causal ) return output.squeeze(0).permute(1, 0, 2).contiguous()
@dataclassclass FACache: """One FA document's projected key/value history and next-token logits."""
model: PATModel keys: list[torch.Tensor] values: list[torch.Tensor] token_count: int capacity: int next_token_logits: torch.Tensor
@classmethod def prefill(cls, model: PATModel, prompt_ids, *, capacity: int) -> FACache: """Encode BOS plus a nonempty text prefix, retaining every layer's KV.""" if model.config.architecture != "FA": raise ValueError("FACache requires an FA checkpoint") device = model.token_embed.weight.device if device.type != "cuda": raise RuntimeError("FA cached decoding requires CUDA FlashAttention") prompt = torch.as_tensor(prompt_ids, device=device) if prompt.ndim != 1 or prompt.dtype not in {torch.int32, torch.int64}: raise ValueError("The prompt must be a one-dimensional integer token sequence") if not prompt.numel() or bool(((prompt < 0) | (prompt >= EOD_ID)).any().item()): raise ValueError("The prompt must contain nonempty text without document or packing markers") token_count = prompt.numel() + 1 if type(capacity) is not int or not token_count <= capacity <= model.config.context_length: raise ValueError("Cache capacity must fit BOS and the prompt within context_length") tokens = torch.cat((prompt.new_tensor([BOS_ID]), prompt)).to(dtype=torch.long) positions = torch.arange(token_count, dtype=torch.long, device=device) # Inference has fixed eager projection arithmetic. Calling the class # methods also preserves it if this model was compiled for training. hidden = type(model.token_embed).forward(model.token_embed, tokens) keys, values = [], [] for layer in model.layers: query, key, value, _ = type(layer).prepare(layer, hidden, positions, positions) context = _attention(query, key, value, causal=True) hidden = type(layer).finish(layer, hidden, context, hidden.size(0)) key_cache = key.new_empty((capacity, *key.shape[1:])) value_cache = value.new_empty((capacity, *value.shape[1:])) key_cache[:token_count].copy_(key) value_cache[:token_count].copy_(value) keys.append(key_cache) values.append(value_cache) normalized = type(model.final_norm).forward(model.final_norm, hidden[-1]) logits = type(model.lm_head).forward(model.lm_head, normalized).detach().contiguous() return cls(model, keys, values, token_count, capacity, logits)
def append(self, token_id: int) -> torch.Tensor: """Encode one new text token and return its next-token prediction.""" if type(token_id) is not int or not 0 <= token_id < EOD_ID: raise ValueError("Append requires one text token; stop generation when EOD is selected") if self.token_count >= self.capacity: raise ValueError("FA cache capacity exhausted") device = self.model.token_embed.weight.device token = torch.tensor([token_id], dtype=torch.long, device=device) position = torch.tensor([self.token_count], dtype=torch.long, device=device) hidden = type(self.model.token_embed).forward(self.model.token_embed, token) for index, layer in enumerate(self.model.layers): query, key, value, _ = type(layer).prepare(layer, hidden, position, position) self.keys[index][self.token_count : self.token_count + 1].copy_(key) self.values[index][self.token_count : self.token_count + 1].copy_(value) context = _attention( query, self.keys[index][: self.token_count + 1], self.values[index][: self.token_count + 1], causal=False, ) hidden = type(layer).finish(layer, hidden, context, hidden.size(0)) self.token_count += 1 normalized = type(self.model.final_norm).forward(self.model.final_norm, hidden[-1]) self.next_token_logits = ( type(self.model.lm_head).forward(self.model.lm_head, normalized).detach().contiguous() ) return self.next_token_logits
def create_cache(model: PATModel, prompt_ids, capacity: int): """Prefill the fixed PAT or FA cache selected by the checkpoint geometry.""" if model.config.architecture == "FA": return FACache.prefill(model, prompt_ids, capacity=capacity) from .pat_cache import PATCache
return PATCache.prefill(model, prompt_ids, capacity=capacity)1"""Fused PAT attention kernels."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415"""Fixed PAT cached attention kernels, preserving published arithmetic."""
import torchimport tritonimport triton.language as tl
from .attention import KernelConfig, _cached_pat_attention_phases
@triton.jitdef _pat_rotate_rows( x, cosine, sine, BLOCK_M: tl.constexpr, BLOCK_D: tl.constexpr, FP32_PRODUCTS: tl.constexpr = False,): if FP32_PRODUCTS: # d68a14e3: retain the existing phase values and interface dtype. source = x.to(tl.float32) cosine, sine = cosine.to(tl.float32), sine.to(tl.float32) pairs = tl.reshape(source, (BLOCK_M, BLOCK_D // 2, 2)) even, odd = tl.split(pairs) quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_M, BLOCK_D)) return tl.fma(quarter_turn, sine, source * cosine).to(x.dtype) else: pairs = tl.reshape(x, (BLOCK_M, BLOCK_D // 2, 2)) even, odd = tl.split(pairs) quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_M, BLOCK_D)) return x * cosine + quarter_turn * sine
@triton.jitdef _pat_rotate_vector( x, cosine, sine, BLOCK_D: tl.constexpr, FP32_PRODUCTS: tl.constexpr = False,): if FP32_PRODUCTS: source = x.to(tl.float32) cosine, sine = cosine.to(tl.float32), sine.to(tl.float32) pairs = tl.reshape(source, (BLOCK_D // 2, 2)) even, odd = tl.split(pairs) quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_D,)) return tl.fma(quarter_turn, sine, source * cosine).to(x.dtype) else: pairs = tl.reshape(x, (BLOCK_D // 2, 2)) even, odd = tl.split(pairs) quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_D,)) return x * cosine + quarter_turn * sine
@triton.jitdef _pat_online_step( q, k, v, valid, has_key, m, denominator, output, qk_scale,): scores = tl.dot(q, k, input_precision="ieee") * qk_scale scores = tl.where(valid, scores, -float("inf")) tile_max = tl.max(scores, axis=1) next_m = tl.where(has_key, tl.maximum(m, tile_max), m) alpha = tl.where(has_key, tl.exp2(m - next_m), 1.0) probability = tl.where(valid, tl.exp2(scores - next_m[:, None]), 0.0) output = output * alpha[:, None] + tl.dot(probability.to(v.dtype), v, input_precision="ieee") denominator = denominator * alpha + tl.sum(probability, axis=1) return next_m, denominator, output
@triton.jitdef _pat_active_q1_online_step( q, k, v, valid, has_key, m, denominator, output, qk_scale,): """Scalar-query online softmax using vector reductions, never MMA."""
scores = ( tl.sum( q[None, :].to(tl.float32) * k.to(tl.float32), axis=1, ) * qk_scale ) scores = tl.where(valid, scores, -float("inf")) tile_max = tl.max(scores, axis=0) next_m = tl.where(has_key, tl.maximum(m, tile_max), m) alpha = tl.where(has_key, tl.exp2(m - next_m), 1.0) probability = tl.where(valid, tl.exp2(scores - next_m), 0.0) output = output * alpha + tl.sum( probability[:, None] * v.to(tl.float32), axis=0, ) denominator = denominator * alpha + tl.sum(probability, axis=0) return next_m, denominator, output
@triton.jitdef _pat_active_q1_last_cta_combine( partial_ptr, completion_counter_ptr, out_ptr, row, head, completion_index, heads, head_dim, BLOCK_D: tl.constexpr, MEMORY_SPLITS: tl.constexpr,): """Reduce published split states and reset the replay counter."""
offs_d = tl.arange(0, BLOCK_D) d_mask = offs_d < head_dim state_base = (row * heads + head) * MEMORY_SPLITS * (BLOCK_D + 2) global_m = -float("inf") any_partial = False for split in tl.static_range(0, MEMORY_SPLITS): split_base = state_base + split * (BLOCK_D + 2) split_denominator = tl.load(partial_ptr + split_base + 1) split_present = split_denominator > 0.0 split_m = tl.load(partial_ptr + split_base) global_m = tl.maximum( global_m, tl.where(split_present, split_m, -float("inf")), ) any_partial = any_partial | split_present safe_global_m = tl.where(any_partial, global_m, 0.0) combined_denominator = 0.0 combined_output = tl.zeros((BLOCK_D,), tl.float32) for split in tl.static_range(0, MEMORY_SPLITS): split_base = state_base + split * (BLOCK_D + 2) split_denominator = tl.load(partial_ptr + split_base + 1) split_present = split_denominator > 0.0 split_m = tl.load(partial_ptr + split_base) split_alpha = tl.where( split_present, tl.exp2(split_m - safe_global_m), 0.0, ) split_output = tl.load( partial_ptr + split_base + 2 + offs_d, mask=d_mask, other=0.0, ) combined_denominator += split_denominator * split_alpha combined_output += split_output * split_alpha safe_denominator = tl.where( combined_denominator > 0.0, combined_denominator, 1.0, ) tl.store( out_ptr + row * heads * head_dim + head * head_dim + offs_d, combined_output / safe_denominator, mask=d_mask, ) tl.atomic_xchg( completion_counter_ptr + completion_index, 0, sem="release", scope="gpu", )
@triton.jit( do_not_specialize=("memory_slots", "exact_slots", "local_slots"), do_not_specialize_on_alignment=( "memory_slots", "exact_slots", "local_slots", ),)def _pat_active_forward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, k_exact_ptr, v_exact_ptr, k_local_ptr, v_local_ptr, out_ptr, row_lengths_ptr, memory_query_start_ptr, row_memory_start_ptr, row_memory_length_ptr, row_token_memory_length_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, row_local_start_ptr, phase_cos_ptr, phase_sin_ptr, q_tile_rows_ptr, q_tile_starts_ptr, q_row_offsets_ptr, q_row_starts_ptr, scale, memory_slots, exact_slots, local_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K_MEMORY: tl.constexpr, BLOCK_K_TOKEN: tl.constexpr, BLOCK_D: tl.constexpr, QUERY_IS_EOC: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False,): """Cached PAT decode over caller-owned persistent K/V arenas."""
tile = tl.program_id(0) head = tl.program_id(1) row = tl.load(q_tile_rows_ptr + tile) q_start = tl.load(q_tile_starts_ptr + tile)
row_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) offs_q = tl.arange(0, BLOCK_Q) offs_d = tl.arange(0, BLOCK_D) q_pos = q_start + offs_q q_mask = (q_pos < row_length) & tl.where( QUERY_IS_EOC, q_pos >= lexical_length, q_pos < lexical_length, ) q_row_offset = tl.load(q_row_offsets_ptr + row) q_row_start = tl.load(q_row_starts_ptr + row) q_flat = q_row_offset + q_pos - q_row_start d_mask = offs_d < head_dim q = tl.load( q_ptr + q_flat[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=q_mask[:, None] & d_mask[None, :], other=0.0, )
m = tl.full((BLOCK_Q,), -float("inf"), tl.float32) denominator = tl.zeros((BLOCK_Q,), tl.float32) output = tl.zeros((BLOCK_Q, BLOCK_D), tl.float32) qk_scale = scale * 1.4426950408889634
local_row_start = tl.load(row_local_start_ptr + row) local_stop = tl.where( QUERY_IS_EOC, row_length, tl.minimum(lexical_length, q_start + BLOCK_Q), ) offs_k = tl.arange(0, BLOCK_K_TOKEN) local_start = 0 while local_start < local_stop: local_pos = local_start + offs_k local_abs = local_row_start + local_pos local_mask = (local_pos < local_stop) & (local_abs < local_slots) k = tl.load( k_local_ptr + local_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & local_mask[None, :], other=0.0, ) v = tl.load( v_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) visible = QUERY_IS_EOC | (local_pos[None, :] <= q_pos[:, None]) valid = q_mask[:, None] & local_mask[None, :] & visible m, denominator, output = _pat_online_step( q, k, v, valid, q_mask, m, denominator, output, qk_scale, ) local_start += BLOCK_K_TOKEN
if not QUERY_IS_EOC: exact_start = tl.load(row_exact_start_ptr + row) exact_length = tl.load(row_exact_length_ptr + row) exact_delta = tl.load(row_exact_delta_ptr + row) exact_phase_offset = exact_delta * BLOCK_D + offs_d table_cosine = tl.load( phase_cos_ptr + exact_phase_offset, mask=d_mask, other=1.0, ) table_sine = tl.load( phase_sin_ptr + exact_phase_offset, mask=d_mask, other=0.0, ) has_exact_phase = exact_delta != 0 exact_cosine = tl.where(has_exact_phase, table_cosine, 1.0) exact_sine = tl.where(has_exact_phase, -table_sine, 0.0) q_exact = _pat_rotate_rows( q, exact_cosine[None, :].to(q.dtype), exact_sine[None, :].to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) exact_offset_start = 0 while exact_offset_start < exact_length: exact_offset = exact_offset_start + offs_k exact_abs = exact_start + exact_offset exact_mask = (exact_offset < exact_length) & (exact_abs < exact_slots) k = tl.load( k_exact_ptr + exact_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & exact_mask[None, :], other=0.0, ) v = tl.load( v_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) valid = q_mask[:, None] & exact_mask[None, :] & (exact_offset[None, :] > q_pos[:, None]) exact_tile_stop = tl.minimum( exact_offset_start + BLOCK_K_TOKEN, exact_length, ) has_exact_key = q_mask & (q_pos + 1 < exact_tile_stop) m, denominator, output = _pat_online_step( q_exact, k, v, valid, has_exact_key, m, denominator, output, qk_scale, ) exact_offset_start += BLOCK_K_TOKEN
memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.where( QUERY_IS_EOC, tl.load(row_memory_length_ptr + row), tl.load(row_token_memory_length_ptr + row), ) memory_offsets = tl.arange(0, BLOCK_K_MEMORY) if QUERY_IS_EOC: newest_length = 0 # Keep the multi-query owner free of the same zero-iteration dot body. if GLOBAL_SLOTS > 0 and not QUERY_IS_EOC: newest_length = tl.where( memory_length >= GLOBAL_SLOTS, GLOBAL_SLOTS, 0, ) newest_start = memory_start + memory_length - newest_length newest_phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d newest_cosine = tl.load( phase_cos_ptr + newest_phase_offset, mask=d_mask, other=1.0, ) newest_sine = tl.load( phase_sin_ptr + newest_phase_offset, mask=d_mask, other=0.0, ) q_newest = _pat_rotate_rows( q, newest_cosine[None, :].to(q.dtype), newest_sine[None, :].to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) newest_offset_start = 0 while newest_offset_start < newest_length: newest_offset = newest_offset_start + memory_offsets newest_abs = newest_start + newest_offset newest_mask = (newest_offset < newest_length) & (newest_abs < memory_slots) k = tl.load( k_memory_ptr + newest_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & newest_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) valid = q_mask[:, None] & newest_mask[None, :] m, denominator, output = _pat_online_step( q_newest, k, v, valid, q_mask & (newest_length > 0), m, denominator, output, qk_scale, ) newest_offset_start += BLOCK_K_MEMORY
phase_row = tl.where( QUERY_IS_EOC, CHUNK_SIZE - 1, tl.minimum(q_pos, CHUNK_SIZE - 1), ) phase_offset = phase_row[:, None] * BLOCK_D + offs_d[None, :] cosine = tl.load( phase_cos_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=1.0, ) sine = tl.load( phase_sin_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=0.0, ) q_memory = _pat_rotate_rows( q, cosine.to(q.dtype), sine.to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) remote_memory_length = memory_length if not QUERY_IS_EOC: remote_memory_length = tl.maximum(memory_length - GLOBAL_SLOTS, 0) memory_offset_start = 0 while memory_offset_start < remote_memory_length: memory_offset = memory_offset_start + memory_offsets memory_abs = memory_start + memory_offset memory_mask = (memory_offset < remote_memory_length) & (memory_abs < memory_slots) k = tl.load( k_memory_ptr + memory_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & memory_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) valid = q_mask[:, None] & memory_mask[None, :] m, denominator, output = _pat_online_step( q_memory, k, v, valid, q_mask, m, denominator, output, qk_scale, ) memory_offset_start += BLOCK_K_MEMORY
safe_denominator = tl.where(q_mask, denominator, 1.0) normalized = output / safe_denominator[:, None] tl.store( out_ptr + q_flat[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], normalized, mask=q_mask[:, None] & d_mask[None, :], )
@triton.jit( do_not_specialize=("memory_slots", "exact_slots", "local_slots"), do_not_specialize_on_alignment=( "memory_slots", "exact_slots", "local_slots", ),)def _pat_active_q1_forward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, k_exact_ptr, v_exact_ptr, k_local_ptr, v_local_ptr, out_ptr, row_lengths_ptr, memory_query_start_ptr, row_memory_start_ptr, row_memory_length_ptr, row_token_memory_length_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, row_local_start_ptr, phase_cos_ptr, phase_sin_ptr, q_row_starts_ptr, scale, memory_slots, exact_slots, local_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_K_MEMORY: tl.constexpr, BLOCK_K_TOKEN: tl.constexpr, BLOCK_D: tl.constexpr, QUERY_IS_EOC: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False,): """One scalar query per row/head, with no padded query or dot tile."""
row = tl.program_id(0) head = tl.program_id(1) q_pos = tl.load(q_row_starts_ptr + row) row_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) query_valid = (q_pos < row_length) & tl.where( QUERY_IS_EOC, q_pos >= lexical_length, q_pos < lexical_length, ) offs_d = tl.arange(0, BLOCK_D) d_mask = offs_d < head_dim q_flat = row q = tl.load( q_ptr + q_flat * heads * head_dim + head * head_dim + offs_d, mask=query_valid & d_mask, other=0.0, ) m = -float("inf") denominator = 0.0 output = tl.zeros((BLOCK_D,), tl.float32) qk_scale = scale * 1.4426950408889634
offs_token = tl.arange(0, BLOCK_K_TOKEN) local_row_start = tl.load(row_local_start_ptr + row) local_stop = tl.where( QUERY_IS_EOC, row_length, tl.minimum(lexical_length, q_pos + 1), ) local_start = 0 while local_start < local_stop: local_pos = local_start + offs_token local_abs = local_row_start + local_pos local_mask = query_valid & (local_pos < local_stop) & (local_abs < local_slots) k = tl.load( k_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) m, denominator, output = _pat_active_q1_online_step( q, k, v, local_mask, query_valid, m, denominator, output, qk_scale, ) local_start += BLOCK_K_TOKEN
if not QUERY_IS_EOC: exact_start = tl.load(row_exact_start_ptr + row) exact_length = tl.load(row_exact_length_ptr + row) exact_delta = tl.load(row_exact_delta_ptr + row) exact_phase_offset = exact_delta * BLOCK_D + offs_d table_cosine = tl.load( phase_cos_ptr + exact_phase_offset, mask=query_valid & d_mask, other=1.0, ) table_sine = tl.load( phase_sin_ptr + exact_phase_offset, mask=query_valid & d_mask, other=0.0, ) has_exact_phase = exact_delta != 0 exact_cosine = tl.where(has_exact_phase, table_cosine, 1.0) exact_sine = tl.where(has_exact_phase, -table_sine, 0.0) q_exact = _pat_rotate_vector( q, exact_cosine.to(q.dtype), exact_sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) exact_offset_start = 0 while exact_offset_start < exact_length: exact_offset = exact_offset_start + offs_token exact_abs = exact_start + exact_offset exact_mask = ( query_valid & (exact_offset < exact_length) & (exact_abs < exact_slots) & (exact_offset > q_pos) ) k = tl.load( k_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) has_exact = query_valid & (q_pos + 1 < exact_length) m, denominator, output = _pat_active_q1_online_step( q_exact, k, v, exact_mask, has_exact, m, denominator, output, qk_scale, ) exact_offset_start += BLOCK_K_TOKEN
memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.where( QUERY_IS_EOC, tl.load(row_memory_length_ptr + row), tl.load(row_token_memory_length_ptr + row), ) offs_memory = tl.arange(0, BLOCK_K_MEMORY) if QUERY_IS_EOC: newest_length = 0 # Both predicates are constexpr. Elide a provably empty newest loop # instead of asking the compiler to lower a zero-iteration dot body. if GLOBAL_SLOTS > 0 and not QUERY_IS_EOC: newest_length = tl.where( memory_length >= GLOBAL_SLOTS, GLOBAL_SLOTS, 0, ) newest_start = memory_start + memory_length - newest_length newest_phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d newest_cosine = tl.load( phase_cos_ptr + newest_phase_offset, mask=query_valid & d_mask, other=1.0, ) newest_sine = tl.load( phase_sin_ptr + newest_phase_offset, mask=query_valid & d_mask, other=0.0, ) q_newest = _pat_rotate_vector( q, newest_cosine.to(q.dtype), newest_sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) newest_offset_start = 0 while newest_offset_start < newest_length: newest_offset = newest_offset_start + offs_memory newest_abs = newest_start + newest_offset newest_mask = ( query_valid & (newest_offset < newest_length) & (newest_abs < memory_slots) ) k = tl.load( k_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) m, denominator, output = _pat_active_q1_online_step( q_newest, k, v, newest_mask, query_valid & (newest_length > 0), m, denominator, output, qk_scale, ) newest_offset_start += BLOCK_K_MEMORY
phase_row = tl.where( QUERY_IS_EOC, CHUNK_SIZE - 1, tl.minimum(q_pos, CHUNK_SIZE - 1), ) phase_offset = phase_row * BLOCK_D + offs_d cosine = tl.load( phase_cos_ptr + phase_offset, mask=query_valid & d_mask, other=1.0, ) sine = tl.load( phase_sin_ptr + phase_offset, mask=query_valid & d_mask, other=0.0, ) q_memory = _pat_rotate_vector( q, cosine.to(q.dtype), sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) remote_memory_length = memory_length if not QUERY_IS_EOC: remote_memory_length = tl.maximum(memory_length - GLOBAL_SLOTS, 0) memory_offset_start = 0 while memory_offset_start < remote_memory_length: memory_offset = memory_offset_start + offs_memory memory_abs = memory_start + memory_offset memory_mask = ( query_valid & (memory_offset < remote_memory_length) & (memory_abs < memory_slots) ) k = tl.load( k_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) has_memory = query_valid & (remote_memory_length > 0) m, denominator, output = _pat_active_q1_online_step( q_memory, k, v, memory_mask, has_memory, m, denominator, output, qk_scale, ) memory_offset_start += BLOCK_K_MEMORY
safe_denominator = tl.where(query_valid, denominator, 1.0) normalized = output / safe_denominator tl.store( out_ptr + q_flat * heads * head_dim + head * head_dim + offs_d, normalized, mask=query_valid & d_mask, )
@triton.jit( do_not_specialize=("memory_slots", "exact_slots", "local_slots"), do_not_specialize_on_alignment=( "memory_slots", "exact_slots", "local_slots", ),)def _pat_active_q1_splitk_forward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, k_exact_ptr, v_exact_ptr, k_local_ptr, v_local_ptr, partial_ptr, completion_counter_ptr, out_ptr, row_lengths_ptr, memory_query_start_ptr, row_memory_start_ptr, row_token_memory_length_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, row_local_start_ptr, phase_cos_ptr, phase_sin_ptr, q_row_starts_ptr, scale, memory_slots, exact_slots, local_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_K_MEMORY: tl.constexpr, BLOCK_K_TOKEN: tl.constexpr, BLOCK_D: tl.constexpr, MEMORY_SPLITS: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False,): """Eight disjoint Q1 owners; the last CTA combines in this launch."""
row = tl.program_id(0) head = tl.program_id(1) memory_split = tl.program_id(2) q_pos = tl.load(q_row_starts_ptr + row) row_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) query_valid = (q_pos < row_length) & (q_pos < lexical_length) offs_d = tl.arange(0, BLOCK_D) d_mask = offs_d < head_dim q = tl.load( q_ptr + row * heads * head_dim + head * head_dim + offs_d, mask=query_valid & d_mask, other=0.0, ) m = -float("inf") denominator = 0.0 output = tl.zeros((BLOCK_D,), tl.float32) qk_scale = scale * 1.4426950408889634
# Split zero owns the short local, previous-exact, and newest-global # lanes. Those lanes are intentionally not replicated across the # seven remote-only owners. if memory_split == 0: offs_token = tl.arange(0, BLOCK_K_TOKEN) local_row_start = tl.load(row_local_start_ptr + row) local_stop = tl.minimum(lexical_length, q_pos + 1) local_start = 0 while local_start < local_stop: local_pos = local_start + offs_token local_abs = local_row_start + local_pos local_mask = query_valid & (local_pos < local_stop) & (local_abs < local_slots) k = tl.load( k_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) m, denominator, output = _pat_active_q1_online_step( q, k, v, local_mask, query_valid, m, denominator, output, qk_scale, ) local_start += BLOCK_K_TOKEN
exact_start = tl.load(row_exact_start_ptr + row) exact_length = tl.load(row_exact_length_ptr + row) exact_delta = tl.load(row_exact_delta_ptr + row) exact_phase_offset = exact_delta * BLOCK_D + offs_d table_cosine = tl.load( phase_cos_ptr + exact_phase_offset, mask=query_valid & d_mask, other=1.0, ) table_sine = tl.load( phase_sin_ptr + exact_phase_offset, mask=query_valid & d_mask, other=0.0, ) has_exact_phase = exact_delta != 0 exact_cosine = tl.where(has_exact_phase, table_cosine, 1.0) exact_sine = tl.where(has_exact_phase, -table_sine, 0.0) q_exact = _pat_rotate_vector( q, exact_cosine.to(q.dtype), exact_sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) exact_offset_start = 0 while exact_offset_start < exact_length: exact_offset = exact_offset_start + offs_token exact_abs = exact_start + exact_offset exact_mask = ( query_valid & (exact_offset < exact_length) & (exact_abs < exact_slots) & (exact_offset > q_pos) ) k = tl.load( k_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) has_exact = query_valid & (q_pos + 1 < exact_length) m, denominator, output = _pat_active_q1_online_step( q_exact, k, v, exact_mask, has_exact, m, denominator, output, qk_scale, ) exact_offset_start += BLOCK_K_TOKEN
memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.load(row_token_memory_length_ptr + row) offs_memory = tl.arange(0, BLOCK_K_MEMORY) if GLOBAL_SLOTS > 0: newest_length = tl.where( memory_length >= GLOBAL_SLOTS, GLOBAL_SLOTS, 0, ) newest_start = memory_start + memory_length - newest_length newest_phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d newest_cosine = tl.load( phase_cos_ptr + newest_phase_offset, mask=query_valid & d_mask, other=1.0, ) newest_sine = tl.load( phase_sin_ptr + newest_phase_offset, mask=query_valid & d_mask, other=0.0, ) q_newest = _pat_rotate_vector( q, newest_cosine.to(q.dtype), newest_sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) newest_offset_start = 0 while newest_offset_start < newest_length: newest_offset = newest_offset_start + offs_memory newest_abs = newest_start + newest_offset newest_mask = ( query_valid & (newest_offset < newest_length) & (newest_abs < memory_slots) ) k = tl.load( k_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) m, denominator, output = _pat_active_q1_online_step( q_newest, k, v, newest_mask, query_valid & (newest_length > 0), m, denominator, output, qk_scale, ) newest_offset_start += BLOCK_K_MEMORY
memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.load(row_token_memory_length_ptr + row) remote_memory_length = tl.maximum(memory_length - GLOBAL_SLOTS, 0) offs_memory = tl.arange(0, BLOCK_K_MEMORY) phase_offset = tl.minimum(q_pos, CHUNK_SIZE - 1) * BLOCK_D + offs_d cosine = tl.load( phase_cos_ptr + phase_offset, mask=query_valid & d_mask, other=1.0, ) sine = tl.load( phase_sin_ptr + phase_offset, mask=query_valid & d_mask, other=0.0, ) q_memory = _pat_rotate_vector( q, cosine.to(q.dtype), sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) memory_offset_start = memory_split * BLOCK_K_MEMORY while memory_offset_start < remote_memory_length: memory_offset = memory_offset_start + offs_memory memory_abs = memory_start + memory_offset memory_mask = ( query_valid & (memory_offset < remote_memory_length) & (memory_abs < memory_slots) ) k = tl.load( k_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) m, denominator, output = _pat_active_q1_online_step( q_memory, k, v, memory_mask, query_valid & (remote_memory_length > 0), m, denominator, output, qk_scale, ) memory_offset_start += MEMORY_SPLITS * BLOCK_K_MEMORY
partial_base = ((row * heads + head) * MEMORY_SPLITS + memory_split) * (BLOCK_D + 2) tl.store(partial_ptr + partial_base, m) tl.store(partial_ptr + partial_base + 1, denominator) tl.store( partial_ptr + partial_base + 2 + offs_d, output, mask=d_mask, )
# Every split publishes its state before entering one GPU-scope # acq_rel release sequence. The CTA observing MEMORY_SPLITS - 1 is # therefore the last arrival and has acquired every partial store. # It performs the stable reduction in this same kernel launch, then # resets the persistent counter so the buffer is CUDA-graph replayable. completion_index = row * heads + head completed_before = tl.atomic_add( completion_counter_ptr + completion_index, 1, sem="acq_rel", scope="gpu", ) is_last = completed_before == MEMORY_SPLITS - 1 if is_last: _pat_active_q1_last_cta_combine( partial_ptr, completion_counter_ptr, out_ptr, row, head, completion_index, heads, head_dim, BLOCK_D=BLOCK_D, MEMORY_SPLITS=MEMORY_SPLITS, )
@triton.jitdef _active_q1_post_projection_kernel( packed_qkv_ptr, query_cos_ptr, query_sin_ptr, key_cos_ptr, key_sin_ptr, qk_log_scale_ptr, flat_storage_indices_ptr, query_out_ptr, key_out_ptr, key_storage_ptr, value_storage_ptr, n_heads: tl.constexpr, head_dim: tl.constexpr, block_d: tl.constexpr, qk_norm_enabled: tl.constexpr, qk_norm_eps: tl.constexpr, q_scale_multiplier: tl.constexpr,): token = tl.program_id(0) head = tl.program_id(1) offsets = tl.arange(0, block_d) mask = offsets < head_dim pair_offsets = offsets ^ 1 projected_base = (token * n_heads + head) * head_dim packed_token_base = token * 3 * n_heads * head_dim query_base = packed_token_base + head * head_dim key_base = query_base + n_heads * head_dim value_base = key_base + n_heads * head_dim rope_base = token * head_dim
element_type = packed_qkv_ptr.dtype.element_ty query_raw = tl.load( packed_qkv_ptr + query_base + offsets, mask=mask, other=0.0, ) query_pair = tl.load( packed_qkv_ptr + query_base + pair_offsets, mask=mask, other=0.0, ) key_raw = tl.load( packed_qkv_ptr + key_base + offsets, mask=mask, other=0.0, ) key_pair = tl.load( packed_qkv_ptr + key_base + pair_offsets, mask=mask, other=0.0, ) query_cos = tl.load( query_cos_ptr + rope_base + offsets, mask=mask, other=0.0, ) query_sin = tl.load( query_sin_ptr + rope_base + offsets, mask=mask, other=0.0, ) key_cos = tl.load( key_cos_ptr + rope_base + offsets, mask=mask, other=0.0, ) key_sin = tl.load( key_sin_ptr + rope_base + offsets, mask=mask, other=0.0, ) pair_sign = tl.where((offsets & 1) == 0, -1.0, 1.0)
# Preserve the eager low-precision operation boundaries. GPU # qualification still owns final bitwise/tolerance adjudication because # the fused reduction tree is necessarily kernel-local. query_cos_term = (query_raw * query_cos).to(element_type) query_sin_term = (query_pair * pair_sign * query_sin).to(element_type) query = (query_cos_term + query_sin_term).to(element_type) key_cos_term = (key_raw * key_cos).to(element_type) key_sin_term = (key_pair * pair_sign * key_sin).to(element_type) key = (key_cos_term + key_sin_term).to(element_type)
if qk_norm_enabled: query_fp32 = query.to(tl.float32) key_fp32 = key.to(tl.float32) query_denom = tl.maximum( tl.sqrt(tl.sum(query_fp32 * query_fp32, axis=0)), qk_norm_eps, ) key_denom = tl.maximum( tl.sqrt(tl.sum(key_fp32 * key_fp32, axis=0)), qk_norm_eps, ) query_unit = (query_fp32 / query_denom).to(element_type) key = (key_fp32 / key_denom).to(element_type) scale = tl.exp(tl.load(qk_log_scale_ptr + head).to(tl.float32)).to(element_type) query = (query_unit * scale).to(element_type) query = (query * q_scale_multiplier).to(element_type)
tl.store(query_out_ptr + projected_base + offsets, query, mask=mask) tl.store(key_out_ptr + projected_base + offsets, key, mask=mask) flat_index = tl.load(flat_storage_indices_ptr + token) storage_base = (flat_index * n_heads + head) * head_dim tl.store(key_storage_ptr + storage_base + offsets, key, mask=mask) projected_value = tl.load( packed_qkv_ptr + value_base + offsets, mask=mask, other=0.0, ) tl.store( value_storage_ptr + storage_base + offsets, projected_value, mask=mask, )
def prepare_one(packed, layer, positions, key_storage, value_storage, offset): """Fuse rotary/QK normalization and publish a single lexical token's KV.""" heads, dimension = layer.n_heads, layer.head_dim cosine, sine = layer.rope.cache(positions, dtype=packed.dtype, device=packed.device) query = packed.new_empty((1, heads, dimension)) key = torch.empty_like(query) index = torch.tensor([offset], device=packed.device, dtype=torch.long) _active_q1_post_projection_kernel[(1, heads)]( packed, cosine, sine, cosine, sine, layer.qk_log_scale, index, query, key, key_storage, value_storage, n_heads=heads, head_dim=dimension, block_d=triton.next_power_of_2(dimension), qk_norm_enabled=True, qk_norm_eps=layer.qk_norm_eps, q_scale_multiplier=dimension**0.5, num_warps=1, ) return query
def attend( query, memory, exact, local, *, offset, lexical_count, global_slots, chunk_size, max_memory_size, tail,): """One active document row; lexical Q1 uses the fixed eight-way reduction.""" km, vm = memory ke, ve = exact kl, vl = local config = KernelConfig(chunk_size, max_memory_size, warps=2) heads, dimension = query.shape[1:] block_d = triton.next_power_of_2(dimension) pc, ps = _cached_pat_attention_phases( config=config, device=query.device, dtype=query.dtype, head_dim=dimension )
def integer(value): return torch.tensor([value], dtype=torch.int32, device=query.device)
zero = integer(0) length = integer(offset + query.size(0)) lexical = integer(lexical_count) memory_length, exact_length = integer(km.size(0)), integer(ke.size(0)) start = integer(offset) output = torch.empty_like(query) args = ( query, km, vm, ke, ve, kl, vl, output, length, lexical, zero, memory_length, memory_length, zero, exact_length, zero, zero, pc, ps, ) scalars = (dimension**-0.5, km.size(0), ke.size(0), kl.size(0), heads, dimension) launch = { "GLOBAL_SLOTS": global_slots, "CHUNK_SIZE": chunk_size, "BLOCK_K_MEMORY": 64, "BLOCK_K_TOKEN": 16, "BLOCK_D": block_d, "QUERY_IS_EOC": tail, "num_warps": 2, "num_stages": 3, "FP32_ROTARY_PRODUCTS": True, } if not tail: workspace = torch.empty( (1, heads, 8, block_d + 2), device=query.device, dtype=torch.float32 ) counters = torch.zeros((1, heads), device=query.device, dtype=torch.int32) _pat_active_q1_splitk_forward_kernel[(1, heads, 8)]( query, km, vm, ke, ve, kl, vl, workspace, counters, output, length, lexical, zero, memory_length, zero, exact_length, zero, zero, pc, ps, start, *scalars, GLOBAL_SLOTS=global_slots, CHUNK_SIZE=chunk_size, BLOCK_K_MEMORY=64, BLOCK_K_TOKEN=16, BLOCK_D=block_d, MEMORY_SPLITS=8, num_warps=2, num_stages=3, FP32_ROTARY_PRODUCTS=True, ) elif query.size(0) == 1: _pat_active_q1_forward_kernel[(1, heads)](*args, start, *scalars, **launch) else: tiles = triton.cdiv(query.size(0), 16) tile_rows = torch.zeros(tiles, dtype=torch.int32, device=query.device) tile_starts = torch.arange(tiles, dtype=torch.int32, device=query.device) * 16 + offset _pat_active_forward_kernel[(tiles, heads)]( *args, tile_rows, tile_starts, zero, start, *scalars, BLOCK_Q=16, **launch, ) return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153"""Packed metadata passed to the fused attention kernel."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Any
import torch
@dataclass(frozen=True)class PackedLayout: """PAT row and memory geometry, shared by every layer."""
row_offsets: torch.Tensor row_pos_to_flat: torch.Tensor row_lengths: torch.Tensor memory_query_start: torch.Tensor row_memory_start_abs: torch.Tensor row_memory_length: torch.Tensor local_positions: torch.Tensor eoc_abs_idx: torch.Tensor memory_positions: torch.Tensor row_chunk_indices: torch.Tensor row_pos_to_flat_is_identity: bool max_row_length: int max_chunk_index: int query_positions: torch.Tensor | None row_token_memory_length: torch.Tensor | None row_exact_start_abs: torch.Tensor | None row_exact_length: torch.Tensor | None row_exact_query_phase_delta: torch.Tensor | None row_compressed_eoc_local_key_phase_delta: torch.Tensor | None planner_cache: Any = None planner_cache_key: Any = None token_context_schedule: str = "uniform" fixed_window_contiguous_position_width: int = 0 chronological_fixed_window: bool = False global_memory_slots_per_chunk: int = 0 active_local_row_start_abs: torch.Tensor | None = None active_local_row_starts: tuple[int, ...] | None = None active_token_count: int | None = None
def __post_init__(self) -> None: for field_name in ("max_row_length", "max_chunk_index"): value = getattr(self, field_name) if isinstance(value, bool) or not isinstance(value, int): raise TypeError(f"PackedLayout.{field_name} must be a Python int") if not isinstance(self.chronological_fixed_window, bool): raise TypeError("PackedLayout.chronological_fixed_window must be a bool") if ( isinstance(self.global_memory_slots_per_chunk, bool) or not isinstance(self.global_memory_slots_per_chunk, int) or self.global_memory_slots_per_chunk < 0 ): raise TypeError( "PackedLayout.global_memory_slots_per_chunk must be a non-negative Python int" ) if self.row_count > 0: if self.max_row_length <= 0: raise ValueError("nonempty PackedLayout requires max_row_length > 0") if self.max_chunk_index < 0: raise ValueError("nonempty PackedLayout requires max_chunk_index >= 0") t2_metadata = ( ("row_token_memory_length", self.row_token_memory_length), ("row_exact_start_abs", self.row_exact_start_abs), ("row_exact_length", self.row_exact_length), ("row_exact_query_phase_delta", self.row_exact_query_phase_delta), ( "row_compressed_eoc_local_key_phase_delta", self.row_compressed_eoc_local_key_phase_delta, ), ) present = tuple((value is not None for _, value in t2_metadata)) if any(present) and (not all(present)): missing = ", ".join( ( name for (name, _), is_present in zip(t2_metadata, present, strict=True) if not is_present ) ) raise ValueError( f"PackedLayout T2 metadata must be all present or all None; missing: {missing}" ) for field_name, value in t2_metadata: if value is not None and (not torch.is_tensor(value)): raise TypeError(f"PackedLayout.{field_name} must be a tensor or None") if self.query_positions is not None and (not torch.is_tensor(self.query_positions)): raise TypeError("PackedLayout.query_positions must be a tensor or None") active_values = ( self.active_local_row_start_abs, self.active_local_row_starts, self.active_token_count, ) if any(value is not None for value in active_values) and ( not all(value is not None for value in active_values) ): raise ValueError("active layout requires both row bases and logical token count") if self.active_local_row_start_abs is not None: if ( not torch.is_tensor(self.active_local_row_start_abs) or self.active_local_row_start_abs.dim() != 1 or int(self.active_local_row_start_abs.numel()) != self.row_count ): raise ValueError("active local row bases must contain one value per row") if ( not isinstance(self.active_local_row_starts, tuple) or len(self.active_local_row_starts) != self.row_count or any( isinstance(value, bool) or not isinstance(value, int) or int(value) < 0 for value in self.active_local_row_starts ) ): raise ValueError( "active Python row bases must contain one non-negative integer per row" ) if ( isinstance(self.active_token_count, bool) or not isinstance(self.active_token_count, int) or int(self.active_token_count) <= 0 ): raise ValueError("active logical token count must be positive")
@property def row_count(self) -> int: return int(self.row_lengths.numel())
@property def token_count(self) -> int: if self.active_token_count is not None: return int(self.active_token_count) return int(self.row_pos_to_flat.numel())
@property def memory_tail_slots(self) -> int: return int(self.eoc_abs_idx.size(1))
@property def local_qk_rope_positions(self) -> torch.Tensor: return self.local_positions
@property def local_query_rope_positions(self) -> torch.Tensor: return self.local_positions if self.query_positions is None else self.query_positions
@property def has_previous_exact_context(self) -> bool: return self.row_exact_length is not None
@property def global_k_rope_positions(self) -> torch.Tensor: return self.memory_positions123456789101112131415161718192021222324252627282930313233343536373839404142"""Fixed memory-efficient PAT training objective."""
import torchfrom torch.nn import functional as F
from .config import EOD_ID
def pat_training_loss(hidden, weight, targets): """Fuse vocabulary projection and CE with the publication's FP32 sum.""" from liger_kernel.transformers.functional import liger_fused_linear_cross_entropy
loss_sum = liger_fused_linear_cross_entropy( hidden, weight, targets.contiguous(), bias=None, ce_weight=None, ignore_index=-100, lse_square_scale=0.0, label_smoothing=0.0, reduction="sum", softcap=None, return_z_loss=False, accum_dtype=torch.float32, use_token_scaling=False, return_token_accuracy=False, return_predicted_tokens=False, ) with torch.no_grad(): special = targets.eq(EOD_ID) if not bool(special.any().item()): lexical_sum = loss_sum.detach() elif bool(special.all().item()): lexical_sum = loss_sum.detach().new_zeros(()) else: special_logits = F.linear(hidden[special], weight) special_loss = F.cross_entropy( special_logits, targets[special], reduction="sum" ).float() lexical_sum = loss_sum.detach() - special_loss return loss_sum, lexical_sum123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284"""Minimal PAT/FA decoder with document-local training and text inference."""
from __future__ import annotations
import mathfrom collections.abc import Sequencefrom dataclasses import dataclass
import torchfrom torch import nnfrom torch.nn import functional as Ffrom torch.utils.checkpoint import checkpoint
from .attention import DecoderLayer, MemoryTransition, full_attentionfrom .config import EOD_ID, PATConfigfrom .packing import PackedBatch, pack_pieces
@dataclassclass ModelOutput: loss_sum: torch.Tensor token_count: int lexical_loss_sum: torch.Tensor lexical_token_count: int targets: torch.Tensor logits: torch.Tensor | None = None
@property def loss(self) -> torch.Tensor: return self.loss_sum / self.token_count
class PATModel(nn.Module): """The fixed publication decoder; ``architecture`` selects PAT or FA."""
def __init__(self, config: PATConfig) -> None: super().__init__() self.config = config self.token_embed = nn.Embedding(config.vocab_size, config.d_model) self.final_norm = nn.LayerNorm(config.d_model, eps=1e-6) self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) self.layers = nn.ModuleList(DecoderLayer(config, i) for i in range(config.n_layers)) self.transitions = nn.ModuleDict( { str(i): MemoryTransition(config, i) for i in range(config.n_layers - 1) if config.memory_slots[i] != config.memory_slots[i + 1] } ) self._initialize() self.lm_head.weight = self.token_embed.weight self._components_compiled = False
def _initialize(self) -> None: for module in self.modules(): if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0, std=0.02) if isinstance(module, nn.Linear) and module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.LayerNorm): nn.init.ones_(module.weight) nn.init.zeros_(module.bias) scale = 0.02 / math.sqrt(2 * self.config.n_layers) for layer in self.layers: nn.init.normal_(layer.out_proj.weight, mean=0, std=scale) nn.init.normal_(layer.mlp[2].weight, mean=0, std=scale)
def compile_components(self) -> None: """Compile projection and feed-forward components used by training.""" if self._components_compiled: return self.token_embed.forward = torch.compile(self.token_embed.forward, dynamic=True) self.final_norm.forward = torch.compile(self.final_norm.forward, dynamic=True) if self.config.architecture == "FA": self.lm_head.forward = torch.compile(self.lm_head.forward, dynamic=True) for index, layer in enumerate(self.layers): # The first PAT layer preserves explicit low-precision casts; the # later layers retain the producer's ordinary compiler arithmetic. options = ( {"emulate_precision_casts": True} if self.config.architecture == "PAT" and index == 0 else None ) layer.prepare = torch.compile(layer.prepare, dynamic=True, options=options) layer.prepare_with_memory = torch.compile( layer.prepare_with_memory, dynamic=True, fullgraph=True ) layer.finish = torch.compile(layer.finish, dynamic=True) for transition in self.transitions.values(): transition.forward = torch.compile(transition.forward, dynamic=True, fullgraph=True) self._components_compiled = True
def _pat_hidden(self, batch: PackedBatch, physical_hidden: torch.Tensor) -> torch.Tensor: from .kernels.attention import KernelConfig, attention, bind_plan, materialize_layout
cfg = self.config kernel = KernelConfig(cfg.chunk_size, cfg.max_memory_size, warps=2) geometry = batch.geometry(cfg) signatures = tuple( (width, cfg.memory_slots[max(0, i - 1)]) for i, width in enumerate(cfg.memory_slots) ) layouts = { signature: materialize_layout( geometry, local_slots=signature[0], global_slots=signature[1], config=kernel ) for signature in dict.fromkeys(signatures) } first = layouts[signatures[0]] hidden = physical_hidden.index_select(0, first.canonical_order) lexical_count = first.total_lexical_tokens previous_summary = None for index, layer in enumerate(self.layers): materialized = layouts[signatures[index]]
def run_layer( current, source, layer=layer, materialized=materialized, first_layer=index == 0 ): positions = materialized.canonical_positions key_positions = materialized.canonical_key_positions if first_layer: query, key, value, _ = layer.prepare(current, positions, key_positions) memory_key = key.new_empty((0, cfg.n_heads, cfg.head_dim)) memory_value = memory_key else: if source.numel() == 0: combined, start = current, lexical_count else: combined, start = torch.cat((current, source), dim=0), current.size(0) query, key, value, _, memory_key, memory_value = layer.prepare_with_memory( combined, positions, combined[: current.size(0)], combined[:start], materialized.layout.memory_positions, key_positions, ) plan = bind_plan( materialized, heads=cfg.n_heads, head_dim=cfg.head_dim, dtype=query.dtype, config=kernel, layer_zero=first_layer, ) context = attention( q_canonical=query, k_memory=memory_key, v_memory=memory_value, k_token_canonical=key, v_token_canonical=value, scale=cfg.head_dim**-0.5, plan=plan, ) return layer.finish(current, context, lexical_count)
source = hidden.new_empty((0,)) if previous_summary is None else previous_summary previous_summary = None if self.training and torch.is_grad_enabled(): hidden = checkpoint(run_layer, hidden, source, use_reentrant=False) else: hidden = run_layer(hidden, source) if str(index) in self.transitions: previous_summary = hidden[lexical_count:] summary = previous_summary.reshape( geometry.row_count, cfg.memory_slots[index], cfg.d_model ) transitioned = ( self.transitions[str(index)](summary).reshape(-1, cfg.d_model).to(hidden.dtype) ) hidden = torch.cat((hidden[:lexical_count], transitioned), dim=0) return hidden[:lexical_count]
def hidden_states( self, pieces: Sequence[torch.Tensor], document_ends: Sequence[bool] | None = None, *, for_inference: bool = False, ): """Return final normalized lexical states and their supervision map.""" if self.token_embed.weight.device.type != "cuda": raise RuntimeError("PAT and FA require CUDA; there is no CPU attention implementation") self.compile_components() batch = pack_pieces( pieces, self.config, device=self.token_embed.weight.device, document_ends=document_ends, for_inference=for_inference, ) hidden = self.token_embed(batch.token_ids) if self.config.architecture == "PAT": hidden = self._pat_hidden(batch, hidden) else: positions = torch.cat( [torch.arange(length, device=hidden.device) for length in batch.piece_lengths] ) for layer in self.layers:
def run_layer(current, layer=layer): query, key, value, _ = layer.prepare(current, positions, positions) context = full_attention( query, key, value, batch.piece_lengths, self.config.context_length ) return layer.finish(current, context, current.size(0))
if self.training and torch.is_grad_enabled(): hidden = checkpoint(run_layer, hidden, use_reentrant=False) else: hidden = run_layer(hidden) return self.final_norm(hidden), batch
def forward( self, pieces: Sequence[torch.Tensor], document_ends: Sequence[bool] | None = None, return_logits: bool = False, ) -> ModelOutput: hidden, batch = self.hidden_states(pieces, document_ends) if not batch.token_count: raise ValueError("training needs at least one target token") selected = hidden.index_select(0, batch.source_indices) if self.config.architecture == "PAT" and self.training: from .losses import pat_training_loss
loss_sum, lexical_sum = pat_training_loss(selected, self.lm_head.weight, batch.targets) logits = None if return_logits: logits = torch.cat( [ self.lm_head(selected[start : start + self.config.ce_chunk_size]) for start in range(0, batch.token_count, self.config.ce_chunk_size) ] ) return ModelOutput( loss_sum, batch.token_count, lexical_sum, batch.lexical_token_count, batch.targets, logits, ) logits_parts = [] loss_sum = selected.new_zeros((), dtype=torch.float32) lexical_loss_sum = loss_sum.detach().clone() for start in range(0, batch.token_count, self.config.ce_chunk_size): states = selected[start : start + self.config.ce_chunk_size] labels = batch.targets[start : start + self.config.ce_chunk_size]
def loss_chunk(states, labels): logits = self.lm_head(states) losses = F.cross_entropy(logits, labels, reduction="none") return losses.sum(), losses[labels.ne(EOD_ID)].sum()
if torch.is_grad_enabled(): summed, lexical = checkpoint(loss_chunk, states, labels, use_reentrant=False) else: summed, lexical = loss_chunk(states, labels) loss_sum = loss_sum + summed lexical_loss_sum = lexical_loss_sum + lexical.detach() if return_logits: logits_parts.append(self.lm_head(states)) return ModelOutput( loss_sum, batch.token_count, lexical_loss_sum, batch.lexical_token_count, batch.targets, torch.cat(logits_parts) if return_logits else None, )
@torch.no_grad() def next_token_logits(self, tokens: torch.Tensor) -> torch.Tensor: """Teacher-forced diagnostic using the compiled training arithmetic.
Use ``pat.generate.generate`` or ``pat.inference.create_cache`` for text generation. Cached decoding preserves the original inference arithmetic, which can differ near chunk boundaries from this full- prefix diagnostic. No artificial document end is appended here. """ if tokens.numel() and bool(tokens.eq(EOD_ID).any().item()): raise ValueError("a generation prefix must be an open document without EOD") hidden, _ = self.hidden_states([tokens], document_ends=[False], for_inference=True) return self.lm_head(hidden[-1]).float()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Document-local framing, fixed chunks, and next-token supervision.
Input pieces contain content IDs, followed by EOD only when the originaldocument ends. Each piece gets one BOS; PAT also appends summary rows aftereach chunk. Targets follow the original token stream across chunk boundaries,and never cross a piece boundary or train the appended summary rows."""
from __future__ import annotations
from collections.abc import Sequencefrom dataclasses import dataclass
import torch
from .config import BOS_ID, EOC_ID, EOD_ID, PATConfig
@dataclassclass PackedBatch: token_ids: torch.Tensor lexical_positions: torch.Tensor source_indices: torch.Tensor targets: torch.Tensor piece_lengths: tuple[int, ...] row_lengths: tuple[int, ...] row_content_lengths: tuple[int, ...] row_offsets: tuple[int, ...] chunk_piece_ids: tuple[int, ...] piece_chunk_bases: tuple[int, ...] chunks_per_piece: tuple[int, ...] eoc_positions: tuple[tuple[int, ...], ...]
@property def token_count(self) -> int: return self.targets.numel()
@property def lexical_token_count(self) -> int: return int(self.targets.ne(EOD_ID).sum().item())
def geometry(self, config: PATConfig): from .kernels.attention import FixedGeometry
device = self.token_ids.device tensor = lambda values: torch.tensor(values, device=device, dtype=torch.long) key = ( "packed_training", True, len(self.row_lengths), max(self.row_lengths), self.token_ids.numel(), config.chunk_size, config.memory_slots[0], config.max_memory_size, self.chunks_per_piece, tuple( (i, size) for i, size in enumerate(self.row_content_lengths) if size != config.chunk_size ), ) return FixedGeometry( row_offsets=tensor(self.row_offsets), row_lengths=tensor(self.row_lengths), row_content_lengths=tensor(self.row_content_lengths), chunk_piece_id=tensor(self.chunk_piece_ids), piece_chunk_base=tensor(self.piece_chunk_bases), eoc_abs_idx=tensor(self.eoc_positions), token_count=self.token_ids.numel(), max_row_length=max(self.row_lengths), max_chunk_index=max(self.chunks_per_piece) - 1, planner_cache_key=key, )
def pack_pieces( pieces: Sequence[torch.Tensor], config: PATConfig, *, device: torch.device, document_ends: Sequence[bool] | None = None, for_inference: bool = False,) -> PackedBatch: if not pieces: raise ValueError("at least one document piece is required") if document_ends is not None and len(document_ends) != len(pieces): raise ValueError("document_ends needs one flag per piece") token_parts, targets, sources, lexical_positions = [], [], [], [] ( row_lengths, row_contents, row_offsets, chunk_piece_ids, piece_bases, chunk_counts, eoc_positions, ) = [], [], [], [], [], [], [] piece_lengths = [] physical_cursor = lexical_cursor = 0 slots = config.memory_slots[0] for index, piece in enumerate(pieces): if piece.ndim != 1 or piece.dtype not in {torch.int32, torch.int64}: raise ValueError("pieces must be rank-one integer tensors") piece = piece.to(device=device, dtype=torch.long) # Every input token is either content or the final EOD. This prevents # accidental double framing when importing tokenized corpora. if piece.numel() and bool(((piece < 0) | (piece > EOD_ID)).any().item()): raise ValueError("input pieces may contain only content IDs and terminal EOD") ends = bool(piece.numel() and piece[-1].item() == EOD_ID) if piece.numel() > 1 and bool(piece[:-1].eq(EOD_ID).any().item()): raise ValueError("EOD may appear only at a document's end") if document_ends is not None and bool(document_ends[index]) != ends: raise ValueError("document_ends must agree with the terminal EOD token") if piece.numel() - int(ends) > config.context_length: raise ValueError("piece exceeds context_length; split it before batching") if config.architecture == "FA" and not for_inference: if not piece.numel(): raise ValueError("FA training needs at least one target per piece") # The final target has no following target of its own. Omitting # that unused input preserves the producer's FlashAttention and # projection shapes, including their finite-precision arithmetic. framed = torch.cat((piece.new_tensor([BOS_ID]), piece[:-1])) else: framed = torch.cat((piece.new_tensor([BOS_ID]), piece)) length = framed.numel() piece_lengths.append(length) targets.append(piece) sources.extend(range(lexical_cursor, lexical_cursor + piece.numel())) lexical_cursor += length piece_bases.append(len(row_lengths)) count = 0 step = config.chunk_size if config.architecture == "PAT" else length for start in range(0, length, step): row = framed[start : start + step] size = row.numel() row_offsets.append(physical_cursor) row_contents.append(size) row_lengths.append(size + slots) chunk_piece_ids.append(index) lexical_positions.extend(range(physical_cursor, physical_cursor + size)) tail = tuple(range(physical_cursor + size, physical_cursor + size + slots)) eoc_positions.append(tail) token_parts.append(torch.cat((row, row.new_full((slots,), EOC_ID)))) physical_cursor += size + slots count += 1 chunk_counts.append(count) return PackedBatch( token_ids=torch.cat(token_parts), lexical_positions=torch.tensor(lexical_positions, device=device), source_indices=torch.tensor(sources, device=device, dtype=torch.long), targets=torch.cat(targets), piece_lengths=tuple(piece_lengths), row_lengths=tuple(row_lengths), row_content_lengths=tuple(row_contents), row_offsets=tuple(row_offsets), chunk_piece_ids=tuple(chunk_piece_ids), piece_chunk_bases=tuple(piece_bases), chunks_per_piece=tuple(chunk_counts), eoc_positions=tuple(eoc_positions), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"""Single-document PAT decoding with bounded summaries and one exact chunk.
Each lexical append projects only the new token. A completed chunk publishesits EOC summaries for deeper layers and preserves its final lexical predictionas the bridge into the following chunk. Canonical checkpoint tensors are nevermodified by the cache."""
from __future__ import annotations
import torchfrom torch.nn import functional as F
from .config import BOS_ID, EOC_ID, EOD_IDfrom .kernels.decoding import attend, prepare_onefrom .rotary import normalize_key
class PATCache: """Cached inference state for a single PAT document; use BF16 autocast."""
@classmethod def prefill(cls, model, prompt_ids, *, capacity): if model.config.architecture != "PAT": raise ValueError("PATCache requires a PAT checkpoint") device = model.token_embed.weight.device if device.type != "cuda": raise RuntimeError("PAT cached decoding requires CUDA") prompt = torch.as_tensor(prompt_ids, device=device) if prompt.ndim != 1 or prompt.dtype not in {torch.int32, torch.int64}: raise ValueError("The prompt must be a one-dimensional integer sequence") if not prompt.numel() or bool(((prompt < 0) | (prompt >= EOD_ID)).any().item()): raise ValueError("The prompt must contain text without document or packing markers") if ( type(capacity) is not int or not prompt.numel() + 1 <= capacity <= model.config.context_length ): raise ValueError("Cache capacity must fit BOS and the prompt within context_length") self = cls() self.model, self.capacity = model, capacity self.token_count = self.chunk_index = self.offset = 0 self.device = device config = model.config geometry = (config.n_heads, config.head_dim)
def arena(length): return torch.empty((length, *geometry), device=device, dtype=torch.bfloat16)
self.keys = [arena(config.chunk_size + slots) for slots in config.memory_slots] self.values = [torch.empty_like(key) for key in self.keys] self.memory_keys = [arena(0)] + [ arena( min(capacity // config.chunk_size, config.max_memory_size - 1) * config.memory_slots[index - 1] ) for index in range(1, config.n_layers) ] self.memory_values = [torch.empty_like(key) for key in self.memory_keys] self.exact_keys = [arena(0) for _ in model.layers] self.exact_values = [arena(0) for _ in model.layers] # The published inference residual starts from a BF16 embedding shadow # converted back to FP32, while checkpoint parameters remain FP32. self.embedding = model.token_embed.weight.to(torch.bfloat16) self._append(BOS_ID) for token in prompt.tolist(): self._append(int(token)) return self
def _embed(self, ids): tokens = torch.tensor(ids, device=self.device, dtype=torch.long) return F.embedding(tokens, self.embedding).to(self.model.token_embed.weight.dtype)
def _positions(self, count, *, tail=False): chunk = self.model.config.chunk_size base = 0 if self.chunk_index == 0 else self.chunk_index + chunk - 1 query = torch.arange(count, device=self.device, dtype=torch.long) + base + self.offset key = torch.full_like(query, base + chunk) if tail else query return query, key
def _project_memory(self, layer, hidden): normalized = layer.norm1(hidden) width = self.model.config.d_model projected = F.linear(normalized, layer.qkv_proj.weight[width:], layer.qkv_proj.bias[width:]) raw, value = projected.split(width, dim=-1) raw = raw.view(-1, layer.n_heads, layer.head_dim) value = value.view_as(raw) positions = torch.full( (raw.size(0),), self.chunk_index, device=self.device, dtype=torch.long ) key = normalize_key(layer.rope(raw, positions), layer.qk_norm_eps) return key.contiguous(), value.contiguous()
def _forward(self, hidden, *, tail): config = self.model.config pending = None updates = [] for index, layer in enumerate(self.model.layers): positions, key_positions = self._positions(hidden.size(0), tail=tail) if tail: query, key, value, raw = type(layer).prepare( layer, hidden, positions, key_positions ) self.keys[index][self.offset : self.offset + key.size(0)].copy_(key) self.values[index][self.offset : self.offset + value.size(0)].copy_(value) if index: if pending is not None: updates.append(pending) pending = None else: global_positions = torch.full_like(positions, self.chunk_index) global_key = normalize_key( layer.rope(raw, global_positions), layer.qk_norm_eps ) updates.append((global_key.contiguous(), value.contiguous())) else: packed = layer.qkv_proj(layer.norm1(hidden)) query = prepare_one( packed, layer, positions, self.keys[index], self.values[index], self.offset ) slots = config.memory_slots[max(0, index - 1)] used = self.chunk_index * slots if index else 0 exact = (self.exact_keys[index], self.exact_values[index]) context = attend( query, (self.memory_keys[index][:used], self.memory_values[index][:used]), exact, (self.keys[index], self.values[index]), offset=self.offset, lexical_count=self.offset if tail else self.offset + hidden.size(0), global_slots=slots, chunk_size=config.chunk_size, max_memory_size=config.max_memory_size, tail=tail, ) hidden = type(layer).finish(layer, hidden, context, 0 if tail else hidden.size(0)) if tail and str(index) in self.model.transitions: pending = self._project_memory(self.model.layers[index + 1], hidden) transition = self.model.transitions[str(index)] hidden = type(transition).forward(transition, hidden.unsqueeze(0)).squeeze(0) return hidden, updates
def _append(self, token): hidden, _ = self._forward(self._embed([token]), tail=False) normalized = type(self.model.final_norm).forward(self.model.final_norm, hidden[-1]) self.next_token_logits = F.linear(normalized, self.embedding).detach().contiguous() self.offset += 1 self.token_count += 1 if self.offset == self.model.config.chunk_size and self.token_count < self.capacity: _, updates = self._forward( self._embed([EOC_ID] * self.model.config.memory_slots[0]), tail=True ) for index, (key, value) in enumerate(updates, start=1): start = self.chunk_index * key.size(0) self.memory_keys[index][start : start + key.size(0)].copy_(key) self.memory_values[index][start : start + value.size(0)].copy_(value) # The first completed chunk moves by -1; subsequent exact chunks # move by -C in the next reader's chronological coordinate system. delta = -1 if self.chunk_index == 0 else -self.model.config.chunk_size positions = torch.full((self.offset,), delta, device=self.device, dtype=torch.long) for index, layer in enumerate(self.model.layers): self.exact_keys[index] = layer.rope( self.keys[index][: self.offset], positions ).contiguous() self.exact_values[index] = self.values[index][: self.offset].clone() self.chunk_index += 1 self.offset = 0 return self.next_token_logits
def append(self, token_id: int): """Encode one lexical token; stop rather than append a selected EOD.""" if type(token_id) is not int or not 0 <= token_id < EOD_ID: raise ValueError("Append requires a text token; stop generation on EOD") if self.token_count >= self.capacity: raise ValueError("PAT cache capacity exhausted") return self._append(token_id)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Prepare JSONL documents with the release's exact tokenizer."""
from __future__ import annotations
import argparseimport jsonimport shutilimport tempfilefrom pathlib import Path
import numpy as np
from .data import EOD, file_sha256
def prepare(input_path: Path, output: Path, tokenizer_path: Path | None, context_length: int) -> dict: from .tokenizer import Tokenizer
if context_length <= 0: raise ValueError("context_length must be positive") if output.exists(): raise FileExistsError(f"Output already exists: {output}") artifact = tokenizer_path / "tokenizer.json" if tokenizer_path and tokenizer_path.is_dir() else tokenizer_path tokenizer = Tokenizer(artifact) artifact = tokenizer.path output.parent.mkdir(parents=True, exist_ok=True) temporary = Path(tempfile.mkdtemp(prefix=".prepare-", dir=output.parent)) offsets, lengths = [0], [] documents = 0 try: with input_path.open() as source, (temporary / "tokens.bin").open("wb") as sink: for line_number, line in enumerate(source, 1): row = json.loads(line) if not isinstance(row, dict) or not isinstance(row.get("text"), str): raise TypeError(f"Line {line_number} must contain a string 'text' field") ids = tokenizer.encode(row["text"]) if any(token >= EOD for token in ids): raise ValueError(f"Line {line_number} contains reserved control tokens") if not ids: continue documents += 1 for start in range(0, len(ids), context_length): piece = ids[start:start + context_length] lengths.append(len(piece)) if start + context_length >= len(ids): piece = piece + [EOD] np.asarray(piece, dtype="<u4").tofile(sink) offsets.append(offsets[-1] + len(piece)) if not lengths: raise ValueError("Input contains no nonempty documents") np.save(temporary / "offsets.npy", np.asarray(offsets, dtype="<i8"), allow_pickle=False) np.save(temporary / "lexical_lengths.npy", np.asarray(lengths, dtype="<i8"), allow_pickle=False) manifest = { "format": "pat-document-pieces-1", "context_length": context_length, "documents": documents, "pieces": len(lengths), "lexical_tokens": sum(lengths), "tokenizer_sha256": file_sha256(artifact), "source_sha256": file_sha256(input_path), "files": {name: file_sha256(temporary / name) for name in ("tokens.bin", "offsets.npy", "lexical_lengths.npy")}, } (temporary / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") temporary.rename(output) return manifest finally: if temporary.exists(): shutil.rmtree(temporary)
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, required=True, help="JSONL with one text field per document") parser.add_argument("--output", type=Path, required=True, help="New prepared dataset directory") parser.add_argument("--tokenizer", type=Path, help="Exact release tokenizer file or directory (default: bundled)") parser.add_argument("--context-length", type=int, default=16384, help="Maximum lexical tokens per piece") args = parser.parse_args() print(json.dumps(prepare(args.input, args.output, args.tokenizer, args.context_length), indent=2))
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Interleaved rotary positions and learned, normalized query/key scales."""
from __future__ import annotations
import math
import torchfrom torch import nn
class RotaryEmbedding(nn.Module): def __init__(self, head_dim: int) -> None: super().__init__() self.head_dim = head_dim # Explicit CPU construction keeps this nonpersistent buffer materialized # during meta-device checkpoint loading. It moves with the model. inv_freq = 1.0 / ( 10_000.0 ** (torch.arange(0, head_dim, 2, device="cpu", dtype=torch.float32) / head_dim) ) self.register_buffer("inv_freq", inv_freq, persistent=False)
def cache(self, positions, *, dtype, device): resolved_positions = positions.to(device=device).reshape(-1) pos_idx = resolved_positions.to(dtype=torch.long) freqs = torch.outer(pos_idx.to(dtype=torch.float32), self.inv_freq.to(device=device)) return ( torch.repeat_interleave(freqs.cos(), 2, dim=-1).to(dtype=dtype).unsqueeze(1), torch.repeat_interleave(freqs.sin(), 2, dim=-1).to(dtype=dtype).unsqueeze(1), )
def forward(self, values: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: cosine, sine = self.cache(positions, dtype=values.dtype, device=values.device) return (values * cosine) + (rotate_half(values) * sine)
def apply_pair(self, query, key, positions): cosine, sine = self.cache(positions, dtype=query.dtype, device=query.device) return (query * cosine) + (rotate_half(query) * sine), (key * cosine) + ( rotate_half(key) * sine )
def rotate_half(values: torch.Tensor) -> torch.Tensor: first, second = values[..., ::2], values[..., 1::2] return torch.stack((-second, first), dim=-1).flatten(start_dim=-2)
def normalize_key(values: torch.Tensor, eps: float) -> torch.Tensor: source = values.float() denominator = source.norm(p=2, dim=-1, keepdim=True).clamp_min(float(eps)) return (source / denominator).to(values.dtype)
def normalize_query( values: torch.Tensor, log_scale: torch.Tensor, head_dim: int, eps: float) -> torch.Tensor: unit = normalize_key(values, eps) scale = ( log_scale.float() .exp() .to(device=values.device, dtype=values.dtype) .view(1, int(values.size(-2)), 1) ) multiplier = math.sqrt(float(head_dim)) return unit * scale * multiplier1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Serve one released checkpoint through a small local HTTP generation API."""
from __future__ import annotations
import argparseimport jsonfrom http.server import BaseHTTPRequestHandler, HTTPServerfrom pathlib import Path
from .checkpoint import load_checkpointfrom .generate import generatefrom .tokenizer import Tokenizer
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--checkpoint", type=Path, required=True) parser.add_argument("--port", type=int, default=8000, help="Local listening port") args = parser.parse_args() model = load_checkpoint(args.checkpoint, device="cuda") tokenizer = Tokenizer(args.checkpoint / "tokenizer.json")
class Handler(BaseHTTPRequestHandler): def reply(self, status: int, body: dict): data = json.dumps(body, ensure_ascii=False).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data)
def do_GET(self): if self.path == "/health": self.reply(200, {"status": "ready", "architecture": model.config.architecture}) else: self.reply(404, {"error": "Unknown endpoint"})
def do_POST(self): if self.path != "/generate": self.reply(404, {"error": "Unknown endpoint"}) return try: length = int(self.headers.get("Content-Length", 0)) if not 0 < length <= 1024 * 1024: raise ValueError("Request must be a JSON object smaller than 1 MiB") payload = json.loads(self.rfile.read(length)) if not isinstance(payload, dict) or not isinstance(payload.get("prompt"), str): raise TypeError("Request must contain a text prompt") unknown = set(payload) - {"prompt", "max_new_tokens", "temperature", "top_p", "seed"} if unknown: raise ValueError(f"Unknown generation fields: {sorted(unknown)}") self.reply(200, generate(model, tokenizer=tokenizer, **payload)) except (ValueError, TypeError) as error: self.reply(400, {"error": str(error)}) except (RuntimeError, FloatingPointError): self.reply(500, {"error": "Model execution failed; inspect the server process"}) raise
server = HTTPServer(("127.0.0.1", args.port), Handler) print(f"Serving {model.config.architecture} at http://127.0.0.1:{args.port}", flush=True) try: server.serve_forever() finally: server.server_close()
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""The byte-level BPE tokenizer shared by the released PAT and FA checkpoints."""
import hashlibimport jsonfrom pathlib import Path
from tokenizers import Tokenizer as BPETokenizer
TOKENIZER_SHA256 = "67df57fd93740b7feb7462529fffb9edc0c7c9a30724489472385980b5bdd0b5"VOCAB_SIZE = 50304EOD_ID, PAD_ID, BOS_ID, EOC_ID = 50256, 50257, 50258, 50259
class Tokenizer: """Encode text without adding tokens; the model handles document boundaries.
IDs 0–50255 encode text. ID 50256 ends a document, 50257 pads batches, 50258 starts a document, and 50259 marks a chunk boundary. IDs 50260–50303 only align the vocabulary size and must never be generated. """
vocab_size = VOCAB_SIZE eod_token_id = EOD_ID pad_token_id = PAD_ID bos_token_id = BOS_ID eoc_token_id = EOC_ID
def __init__(self, path: str | Path | None = None): self.path = Path(path) if path else Path(__file__).parent / "assets" / "tokenizer.json" payload = self.path.read_bytes() if hashlib.sha256(payload).hexdigest() != TOKENIZER_SHA256: raise ValueError("Tokenizer does not match the released checkpoint vocabulary.") self._tokenizer = BPETokenizer.from_str(payload.decode("utf-8")) # Literal marker text remains ordinary text. Packing supplies framing # IDs explicitly; added-token matching must not insert those IDs here. ordinary = json.loads(payload) ordinary["added_tokens"] = [] self._content = BPETokenizer.from_str(json.dumps(ordinary))
def encode(self, text: str) -> list[int]: """Encode a raw prompt or document, without implicit truncation or BOS.""" return self._content.encode(text, add_special_tokens=False).ids
def decode(self, ids: list[int]) -> str: """Decode generated text, omitting document and packing markers.""" return self._tokenizer.decode(ids, skip_special_tokens=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""Train PAT or FA with CUDA BF16, using one device or torchrun."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osimport randomimport signalimport tempfileimport timefrom pathlib import Path
import numpy as npimport torchimport torch.distributed as distfrom torch.nn.parallel import DistributedDataParallel
from .checkpoint import load_checkpoint, save_checkpoint, sha256, verify_checkpointfrom .config import PATConfigfrom .data import PieceDataset, training_batches, validation_batchesfrom .model import PATModelfrom .tokenizer import TOKENIZER_SHA256from .training import ( TrainingConfig, backward_loss, optimizer_for, validate_resume_plan, validate_resume_state,)
def _sum(values: torch.Tensor, world_size: int) -> torch.Tensor: if world_size > 1: dist.all_reduce(values, op=dist.ReduceOp.SUM) return values
def _plan_hash(plan: list[list[int]]) -> str: return hashlib.sha256(json.dumps(plan, separators=(",", ":")).encode()).hexdigest()
@torch.no_grad()def validate(model, data: PieceDataset, budget: int, device, rank: int, world: int) -> dict: model.eval() totals = torch.zeros(4, device=device, dtype=torch.float64) for index, batch in enumerate(validation_batches(data, budget, seed=model.config.seed)): if index % world != rank: continue pieces = [data[item].to(device) for item in batch] with torch.autocast("cuda", dtype=torch.bfloat16): output = model(pieces) totals += torch.tensor([ output.loss_sum.item(), output.token_count, output.lexical_loss_sum.item(), output.lexical_token_count, ], device=device, dtype=torch.float64) _sum(totals, world) if totals[1].item() <= 0 or totals[3].item() <= 0: raise ValueError("Validation corpus contains no supervised lexical tokens") model.train() return {"loss": (totals[0] / totals[1]).item(), "lexical_loss": (totals[2] / totals[3]).item(), "targets": int(totals[1].item()), "lexical_targets": int(totals[3].item())}
def _save(model, optimizer, directory: Path, state: dict, rank: int, world: int) -> None: rng = {"cpu": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state().cpu()} states = [None] * world if rank == 0 else None if world > 1: dist.gather_object(rng, states, dst=0) else: states = [rng] if rank == 0: # The outer directory is published only after both weights and resume # state have been written and hashed; interrupted saves are never latest. stage_root = Path(tempfile.mkdtemp(prefix=".saving-", dir=directory.parent)) stage = stage_root / "checkpoint" save_checkpoint(model, stage, metadata={"tokens": state["seen_tokens"], "step": state["step"]}) torch.save({**state, "optimizer": optimizer.state_dict(), "rng_by_rank": states}, stage / "training.pt") manifest = json.loads((stage / "manifest.json").read_text()) manifest["files"]["training.pt"] = { "sha256": sha256(stage / "training.pt"), "size_bytes": (stage / "training.pt").stat().st_size, } (stage / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") stage.rename(directory) stage_root.rmdir() if world > 1: dist.barrier()
def run(args) -> None: if not torch.cuda.is_available(): raise RuntimeError("Training requires a CUDA GPU; no alternate attention implementation is provided") rank, world = int(os.environ.get("RANK", "0")), int(os.environ.get("WORLD_SIZE", "1")) device = torch.device("cuda", int(os.environ.get("LOCAL_RANK", "0"))) torch.cuda.set_device(device) if not torch.cuda.is_bf16_supported(): raise RuntimeError("Training requires BF16 support") if world > 1: dist.init_process_group("nccl", device_id=device) document = json.loads(args.config.read_text()) if set(document) != {"model", "training"}: raise ValueError("Training config must contain exactly 'model' and 'training'") model_config = PATConfig.from_dict(document["model"]) training_values = dict(document["training"]) if args.tokens is not None: training_values["tokens"] = args.tokens config = TrainingConfig(**training_values) if config.seed != model_config.seed: raise ValueError("Model and training initialization seeds must agree") random.seed(config.seed) np.random.seed(config.seed) torch.manual_seed(config.seed) torch.cuda.manual_seed_all(config.seed) torch.backends.cuda.matmul.allow_tf32 = False torch._dynamo.config.optimize_ddp = False dataset = PieceDataset(args.data) val_dataset = PieceDataset(args.validation) if args.validation else None for data in (dataset, val_dataset): if data is None: continue if data.manifest["tokenizer_sha256"] != TOKENIZER_SHA256: raise ValueError("Dataset tokenizer differs from the model tokenizer") if data.manifest["context_length"] != model_config.context_length: raise ValueError("Dataset context length differs from model configuration") if config.microbatch_tokens < model_config.context_length: raise ValueError("Microbatch token budget must fit one maximum-length piece") if args.resume and args.init_checkpoint: raise ValueError("Choose resume or initialize from weights, not both") source = args.resume or args.init_checkpoint model = load_checkpoint(source, device=device) if source else PATModel(model_config).to(device) if model.config.to_dict() != model_config.to_dict(): raise ValueError("Checkpoint architecture differs from the training configuration") model.train() optimizer = optimizer_for(model, config) state = {"format": "pat-training-state-1", "seen_tokens": 0, "step": 0, "epoch": 0, "cursor": 0, "data_fingerprint": dataset.fingerprint, "validation_fingerprint": val_dataset.fingerprint if val_dataset else None, "training_config": config.to_dict(), "world_size": world, "plan_sha256": None} if args.resume: verify_checkpoint(args.resume) restored = torch.load(args.resume / "training.pt", map_location="cpu", weights_only=True) validate_resume_state(restored, state) optimizer.load_state_dict(restored.pop("optimizer")) rng = restored.pop("rng_by_rank")[rank] torch.set_rng_state(rng["cpu"]) torch.cuda.set_rng_state(rng["cuda"], device) state = restored if args.output.exists() and any(args.output.iterdir()) and not args.resume: raise FileExistsError("Use a new output directory for a new training run") args.output.mkdir(parents=True, exist_ok=True) wrapped = ( DistributedDataParallel(model, device_ids=[device.index], find_unused_parameters=True) if world > 1 else model ) stopping = False
def request_stop(_signal, _frame): nonlocal stopping stopping = True
for number in (signal.SIGTERM, signal.SIGINT, signal.SIGUSR1): signal.signal(number, request_stop) log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None last_save = state["seen_tokens"] last_eval = state["seen_tokens"] quantum = world * config.accumulation_steps try: while state["seen_tokens"] < config.tokens: plan = training_batches(dataset.routed_lengths, dataset.lexical_lengths, budget=config.microbatch_tokens, seed=config.seed, epoch=state["epoch"], quantum=quantum) if not plan: raise ValueError("Dataset is too small for one distributed optimizer window") identity = _plan_hash(plan) validate_resume_plan(state, len(plan), identity) state["plan_sha256"] = identity while state["cursor"] < len(plan) and state["seen_tokens"] < config.tokens: started = time.perf_counter() batches = plan[state["cursor"]:state["cursor"] + quantum] # With explicit next-token labels, each routed token has exactly # one predecessor (including BOS->first token and lexical->EOD). lexical = [int(dataset.lexical_lengths[batch].sum()) for batch in batches] targets = [int(dataset.routed_lengths[batch].sum()) for batch in batches] total_lexical, total_targets = sum(lexical), sum(targets) optimizer.zero_grad(set_to_none=True) lr = config.lr_at(state["seen_tokens"]) for group in optimizer.param_groups: group["lr"] = lr metrics = torch.zeros(4, device=device, dtype=torch.float64) for microstep in range(config.accumulation_steps): position = microstep * world + rank batch = batches[position] pieces = [dataset[item].to(device) for item in batch] with torch.autocast("cuda", dtype=torch.bfloat16): result = wrapped(pieces) if result.token_count != targets[position]: raise RuntimeError("Model target count differs from the planned objective") loss_sum = result.loss_sum.to(dtype=next(model.parameters()).dtype) global_loss_sum = ( _sum(result.loss_sum.detach().to(torch.float64), world) if world > 1 else None ) loss = backward_loss( loss_sum, model_config.architecture, world_size=world, local_lexical=lexical[position], global_microbatch_targets=sum(targets[microstep * world:(microstep + 1) * world]), global_window_targets=total_targets, global_window_lexical=total_lexical, global_loss_sum=global_loss_sum, ) # DDP reduces every microstep, preserving accumulation and # reduction order even when multiple microsteps form an update. loss.backward() metrics += torch.tensor([result.loss_sum.item(), result.token_count, result.lexical_loss_sum.item(), result.lexical_token_count], device=device, dtype=torch.float64) grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=True) if not torch.isfinite(metrics).all(): raise FloatingPointError("Nonfinite loss; optimizer update was not performed") optimizer.step() state["step"] += 1 state["cursor"] += quantum state["seen_tokens"] += total_lexical _sum(metrics, world) stop_flag = torch.tensor(int(stopping), device=device) _sum(stop_flag, world) stopping = stop_flag.item() > 0 row = {"step": state["step"], "tokens": state["seen_tokens"], "lr": lr, "loss": (metrics[0] / metrics[1]).item(), "lexical_loss": (metrics[2] / metrics[3]).item(), "grad_norm": float(grad_norm), "tokens_per_second": total_lexical / (time.perf_counter() - started)} finished = state["seen_tokens"] >= config.tokens if val_dataset and (finished or state["seen_tokens"] - last_eval >= config.validate_every): row["validation"] = validate(model, val_dataset, config.microbatch_tokens, device, rank, world) last_eval = state["seen_tokens"] if rank == 0: log.write(json.dumps(row) + "\n") if state["step"] % 10 == 0 or finished or stopping: print(json.dumps(row), flush=True) if finished or stopping or state["seen_tokens"] - last_save >= config.checkpoint_every: path = args.output / f"step-{state['step']:08d}" _save(model, optimizer, path, state, rank, world) last_save = state["seen_tokens"] if rank == 0: (args.output / "latest.txt").write_text(path.name + "\n") if stopping: return if state["cursor"] == len(plan): state["epoch"] += 1 state["cursor"] = 0 state["plan_sha256"] = None finally: if log: log.close() if world > 1: dist.destroy_process_group()
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", type=Path, required=True, help="Model and training JSON recipe") parser.add_argument("--data", type=Path, required=True, help="Prepared training dataset") parser.add_argument("--validation", type=Path, help="Prepared held-out validation dataset") parser.add_argument("--output", type=Path, required=True, help="Run directory for metrics and checkpoints") parser.add_argument("--resume", type=Path, help="Complete checkpoint from this trainer, including training.pt") parser.add_argument("--init-checkpoint", type=Path, help="Initialize weights; start a NEW optimizer and token clock") parser.add_argument("--tokens", type=int, help="Override lexical training horizon; complete the final optimizer window") run(parser.parse_args())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145"""The fixed optimizer, token-clock schedule, and model-family objectives."""
from __future__ import annotations
import mathfrom dataclasses import asdict, dataclassfrom decimal import ROUND_CEILING, Decimal
import torch
@dataclass(frozen=True)class TrainingConfig: tokens: int = 9_520_000_000 warmup_tokens: int = 100_000_000 decay_fraction: float = 0.3 learning_rate: float = 0.00025 min_lr_ratio: float = 0.1 weight_decay: float = 0.01 microbatch_tokens: int = 25000 accumulation_steps: int = 1 seed: int = 42 checkpoint_every: int = 100_000_000 validate_every: int = 200_000_000
def __post_init__(self): for name in ("tokens", "microbatch_tokens", "accumulation_steps", "checkpoint_every", "validate_every"): value = getattr(self, name) if type(value) is not int or value <= 0: raise ValueError(f"{name} must be a positive integer") if type(self.warmup_tokens) is not int or self.warmup_tokens < 0: raise ValueError("warmup_tokens must be a nonnegative integer") if not 0 < self.decay_fraction < 1: raise ValueError("decay_fraction must be between zero and one") if self.warmup_tokens >= self.stable_end: raise ValueError("Warmup must finish before the decay phase") if not math.isfinite(self.learning_rate) or self.learning_rate <= 0: raise ValueError("learning_rate must be finite and positive") if not 0 < self.min_lr_ratio <= 1 or not 0 <= self.weight_decay < float("inf"): raise ValueError("Invalid minimum learning rate or weight decay")
@property def stable_end(self) -> int: decay = Decimal(self.tokens) * Decimal(str(float(self.decay_fraction))) return self.tokens - int(decay.to_integral_value(rounding=ROUND_CEILING))
def to_dict(self) -> dict: return asdict(self)
def lr_at(self, seen_tokens: int) -> float: """Learning rate BEFORE the update, measured in lexical input tokens.""" if seen_tokens < self.warmup_tokens: ratio = max(1, seen_tokens) / self.warmup_tokens elif seen_tokens <= self.stable_end: ratio = 1.0 else: progress = min(1.0, (seen_tokens - self.stable_end) / (self.tokens - self.stable_end)) ratio = self.min_lr_ratio + (1 - self.min_lr_ratio) * (1 + math.cos(math.pi * progress)) / 2 return self.learning_rate * ratio
def optimizer_for(model, config: TrainingConfig) -> torch.optim.AdamW: """Decay matrices; exclude biases, normalization, and learned QK scales.""" groups: dict[str, list] = {"decay": [], "no_decay": [], "qk_scale": []} for name, parameter in model.named_parameters(): if not parameter.requires_grad: continue if name.endswith("qk_log_scale"): key = "qk_scale" elif parameter.ndim == 1 or name.endswith(".bias") or ".norm" in name: key = "no_decay" else: key = "decay" groups[key].append(parameter) return torch.optim.AdamW( [{"params": parameters, "weight_decay": config.weight_decay if name == "decay" else 0.0} for name, parameters in groups.items() if parameters], lr=config.lr_at(0), betas=(0.9, 0.999), eps=1e-8, fused=True, foreach=False, )
def backward_loss( loss_sum: torch.Tensor, architecture: str, *, world_size: int, local_lexical: int, global_microbatch_targets: int, global_window_targets: int, global_window_lexical: int, global_loss_sum: torch.Tensor | None = None,) -> torch.Tensor: """Construct the objective in the released training arithmetic order.
Normalize each microstep first, then apply its accumulation weight. Combining these factors changes FP32 gradients. In distributed training, a detached correction displays the global mean while the local gradient retains compensation for DDP averaging. The caller supplies the globally reduced loss sum in float64 and synchronizes every backward microstep. """ if min(world_size, global_microbatch_targets, global_window_targets, global_window_lexical) <= 0: raise ValueError("Every optimizer window must have positive target counts") if world_size > 1: if global_loss_sum is None: raise ValueError("Distributed training requires the global loss sum") denominator = loss_sum.new_tensor(global_microbatch_targets).clamp_min(1) scaled = loss_sum * float(world_size) / denominator global_mean = ( global_loss_sum.to(dtype=torch.float64) / global_loss_sum.new_tensor(global_microbatch_targets, dtype=torch.float64).clamp_min(1) ).to(dtype=scaled.dtype) normalized = scaled + (global_mean.detach() - scaled.detach()) else: normalized = loss_sum / float(global_microbatch_targets) if architecture == "PAT": outer = float(global_microbatch_targets) / float(global_window_targets) elif architecture == "FA": outer = float(world_size) * float(local_lexical) / float(global_window_lexical) else: raise ValueError("Architecture must be PAT or FA") return normalized * outer
def validate_resume_state(restored: dict, expected: dict) -> None: """Reject a changed data/optimizer contract or an incomplete update cursor.""" for field in ("format", "data_fingerprint", "validation_fingerprint", "training_config", "world_size"): if restored.get(field) != expected[field]: raise ValueError(f"Resume contract differs: {field}") for field in ("seen_tokens", "step", "epoch", "cursor"): value = restored.get(field) if type(value) is not int or value < 0: raise ValueError(f"Invalid resume counter: {field}") quantum = expected["world_size"] * expected["training_config"]["accumulation_steps"] if restored["cursor"] % quantum: raise ValueError("Resume cursor is not at a complete optimizer boundary") if restored["cursor"] and not isinstance(restored.get("plan_sha256"), str): raise ValueError("Resume state is missing its batch-plan identity")
def validate_resume_plan(state: dict, plan_length: int, plan_sha256: str) -> None: """Admit a saved cursor only within the regenerated epoch's exact plan.""" if state["cursor"] > plan_length: raise ValueError("Resume cursor exceeds the saved epoch's batch plan") if state["cursor"] and state["plan_sha256"] != plan_sha256: raise ValueError("Resume batch order differs from the saved plan")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Checkpoint round trips and integrity failures do not need a GPU."""
import json
import pytestimport torch
from pat.checkpoint import download_checkpoint, load_checkpoint, save_checkpoint, verify_checkpointfrom pat.config import PATConfigfrom pat.model import PATModelfrom pat.tokenizer import Tokenizer
def test_weight_round_trip_and_tamper_detection(tmp_path): model = PATModel(PATConfig(architecture="FA", d_model=80, n_heads=4, n_layers=1, context_length=64)) directory = tmp_path / "checkpoint" save_checkpoint(model, directory, {"training_tokens": 0}) loaded = load_checkpoint(directory) assert loaded.lm_head.weight is loaded.token_embed.weight assert not loaded.training for name, tensor in model.state_dict().items(): assert torch.equal(tensor, loaded.state_dict()[name]), name with pytest.raises(FileExistsError): save_checkpoint(model, directory) config = directory / "config.json" config.write_text(config.read_text().replace('"seed": 42', '"seed": 43')) with pytest.raises(ValueError, match="SHA-256 mismatch"): verify_checkpoint(directory)
def test_manifest_rejects_parent_path(tmp_path): (tmp_path / "manifest.json").write_text(json.dumps({ "format": "pat-checkpoint-v1", "files": {name: {} for name in ["config.json", "model.safetensors", "tokenizer.json", "TOKENIZER_LICENSE.txt", "metadata.json", "../outside"]}, })) # Validate the filename before any file content is consulted. data = json.loads((tmp_path / "manifest.json").read_text()) data["files"] = {"../outside": {}, **data["files"]} (tmp_path / "manifest.json").write_text(json.dumps(data)) with pytest.raises(ValueError, match="basenames"): verify_checkpoint(tmp_path)
def test_download_requires_immutable_revision(tmp_path): with pytest.raises(ValueError, match="commit revision"): download_checkpoint("example/model", "main", tmp_path / "model")
def test_bundled_tokenizer_contract(): tokenizer = Tokenizer() text = "Hello, café 日本語.\n x = 3" assert tokenizer.decode(tokenizer.encode(text)) == text assert tokenizer.encode("") == [] for marker in ("[BOS]", "[EOC]", "[PAD]", "<|endoftext|>", "[V64PAD_00]"): ids = tokenizer.encode(marker) assert all(token < 50256 for token in ids) assert tokenizer.decode(ids) == marker1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Document boundaries and deterministic token-budget batches."""
import jsonfrom types import SimpleNamespace
import numpy as npimport pytest
from pat.data import PieceDataset, training_batches, validation_batchesfrom pat.prepare import preparefrom pat.tokenizer import EOD_ID, Tokenizer
def test_preparation_preserves_complete_content_and_final_boundary(tmp_path): tokenizer = Tokenizer() documents = ["one two three four five six seven eight nine ten " * 5, "second document"] source = tmp_path / "input.jsonl" source.write_text("".join(json.dumps({"text": text}) + "\n" for text in documents)) destination = tmp_path / "prepared" prepare(source, destination, None, context_length=16) dataset = PieceDataset(destination) recovered, current = [], [] for piece in dataset: ids = piece.tolist() assert EOD_ID not in ids[:-1] is_final = ids[-1] == EOD_ID current.extend(ids[:-1] if is_final else ids) if is_final: recovered.append(current) current = [] assert not current assert recovered == [tokenizer.encode(text) for text in documents] assert sum(dataset.lexical_lengths) == sum(map(len, recovered)) batches = list(validation_batches(dataset, 20)) assert sorted(index for batch in batches for index in batch) == list(range(len(dataset)))
def test_prepared_data_hash_detects_changed_token_array(tmp_path): source = tmp_path / "input.jsonl" source.write_text(json.dumps({"text": "An ordinary document."}) + "\n") destination = tmp_path / "prepared" prepare(source, destination, None, 16384) path = destination / "tokens.bin" data = bytearray(path.read_bytes()) data[0] ^= 1 path.write_bytes(data) with pytest.raises(ValueError, match="checksum"): PieceDataset(destination)
def test_batching_budget_uniqueness_epoch_and_distributed_window(): lexical = np.asarray([10, 19, 20, 21, 29, 30, 31, 39, 40, 49, 50] * 8) routed = lexical + np.asarray([0, 1] * 44) first = training_batches(routed, lexical, budget=100, seed=42, epoch=0, quantum=4) again = training_batches(routed, lexical, budget=100, seed=42, epoch=0, quantum=4) later = training_batches(routed, lexical, budget=100, seed=42, epoch=1, quantum=4) assert first == again assert first != later assert len(first) % 4 == 0 flattened = [index for batch in first for index in batch] assert len(flattened) == len(set(flattened)) assert all(int(lexical[batch].sum()) <= 100 for batch in first)
def test_validation_preserves_reference_order_and_overflow_coverage(): # Fixed oracle output exercises deferred capacity, cyclic slot placement, # and a piece larger than the nominal batch budget without dropping it. lexical = np.asarray([91, 81, 71, 61, 51, 41, 31, 21, 11, 1, 101]) dataset = SimpleNamespace(lexical_lengths=lexical, routed_lengths=lexical + 1) batches = validation_batches(dataset, 100, seed=42) assert batches == [[0, 9], [1], [3, 7], [2], [5, 6], [4, 8], [10]] assert sorted(index for batch in batches for index in batch) == list(range(len(lexical))) assert all(int(lexical[batch].sum()) <= 100 or len(batch) == 1 for batch in batches)
def test_preparation_rejects_missing_text(tmp_path): source = tmp_path / "input.jsonl" source.write_text('{"wrong": "field"}\n') with pytest.raises(TypeError, match="text"): prepare(source, tmp_path / "prepared", None, 16384)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Sampling respects the public vocabulary and explicit sampling settings."""
from types import SimpleNamespace
import pytestimport torch
from pat.generate import generate, samplefrom pat.tokenizer import EOD_ID
def test_internal_ids_cannot_win_greedy_selection(): logits = torch.zeros(50304) logits[EOD_ID + 1:] = 1000 logits[17] = 10 assert sample(logits, 0, 0.95, None) == 17 logits[EOD_ID] = 20 assert sample(logits, 0, 0.95, None) == EOD_ID
def test_small_nucleus_keeps_highest_probability_token(): logits = torch.tensor([3., 2., 1.]) generator = torch.Generator().manual_seed(42) for _ in range(10): assert sample(logits, 1, 0.1, generator) == 0
@pytest.mark.parametrize("temperature,top_p", [(-1, .9), (float('nan'), .9), (1, 0), (1, 2)])def test_invalid_sampling_settings_are_rejected(temperature, top_p): with pytest.raises(ValueError): sample(torch.zeros(3), temperature, top_p, None)
def test_nonfinite_logits_are_rejected(): with pytest.raises(FloatingPointError): sample(torch.tensor([0., float('nan')]), 0, .9, None)
def test_generation_requires_a_nonempty_text_prompt(): tokenizer = SimpleNamespace(encode=lambda _: []) with pytest.raises(ValueError, match="at least one text token"): generate(None, "", tokenizer=tokenizer)
def test_generation_context_budget_includes_bos(): tokenizer = SimpleNamespace(encode=lambda _: [1, 2, 3]) model = SimpleNamespace(config=SimpleNamespace(context_length=4)) with pytest.raises(ValueError, match="context length"): generate(model, "three tokens", tokenizer=tokenizer, max_new_tokens=1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""Token accounting, optimizer objectives, and resume boundaries."""
from copy import deepcopy
import pytestimport torch
from pat.training import ( TrainingConfig, backward_loss, validate_resume_plan, validate_resume_state,)
def test_schedule_token_boundaries_and_cooldown(): config = TrainingConfig(tokens=200_000_000) assert config.stable_end == 140_000_000 assert config.lr_at(0) == config.learning_rate / 100_000_000 assert config.lr_at(50_000_000) == config.learning_rate / 2 assert config.lr_at(100_000_000) == config.learning_rate assert config.lr_at(140_000_000) == config.learning_rate assert config.lr_at(170_000_000) == pytest.approx(config.learning_rate * 0.55) assert config.lr_at(200_000_000) == pytest.approx(config.learning_rate * 0.1) assert config.lr_at(200_050_000) == config.lr_at(200_000_000) # Floating point multiplication must not add a spurious cooldown token. assert TrainingConfig(tokens=100, warmup_tokens=10, decay_fraction=0.14).stable_end == 86
@pytest.mark.parametrize("architecture", ["PAT", "FA"])def test_distributed_objective_with_unequal_rank_and_microstep_counts(architecture): # Unequal lexical/valid-target proportions reveal weighting differences # which equal-sized batches would hide. Entries are [microstep, rank]. lexical = torch.tensor([[3, 7], [11, 5]], dtype=torch.float64) targets = torch.tensor([[4, 9], [12, 6]], dtype=torch.float64) coefficients = torch.tensor([[2., 3.], [5., 7.]], dtype=torch.float64) parameter = torch.tensor(1.25, dtype=torch.float64, requires_grad=True) global_window_targets = int(targets.sum()) global_window_lexical = int(lexical.sum()) objective = 0.0 for microstep in range(2): for rank in range(2): summed_loss = parameter.square() * coefficients[microstep, rank] loss = backward_loss( summed_loss, architecture, world_size=2, local_lexical=int(lexical[microstep, rank]), global_microbatch_targets=int(targets[microstep].sum()), global_window_targets=global_window_targets, global_window_lexical=global_window_lexical, global_loss_sum=(parameter.square() * coefficients[microstep].sum()).detach(), ) objective = objective + loss / 2 # DDP gradient mean. objective.backward() if architecture == "PAT": expected_coefficient = coefficients.sum() / targets.sum() else: expected_coefficient = sum( 2 * lexical[m, r] * coefficients[m, r] / (targets[m].sum() * lexical.sum()) for m in range(2) for r in range(2) ) assert parameter.grad == pytest.approx(float(2 * parameter.detach() * expected_coefficient))
@pytest.mark.parametrize("architecture,micro,lexical,window,content,expected_gradient", [ ("PAT", 50238, 23228, 98102, 97126, 2.0386942196637392e-05), ("FA", 45244, 23191, 98895, 96952, 2.1147630832274444e-05),])def test_backward_preserves_fp32_normalization_order( architecture, micro, lexical, window, content, expected_gradient,): # These unequal-count fixtures distinguish the original two-stage FP32 # gradient from collapsing its algebra into one multiplier by one ULP. summed_loss = torch.tensor(123456.789, requires_grad=True) loss = backward_loss( summed_loss, architecture, world_size=2, local_lexical=lexical, global_microbatch_targets=micro, global_window_targets=window, global_window_lexical=content, global_loss_sum=summed_loss.detach().double() * 2, ) gradient = torch.autograd.grad(loss, summed_loss)[0] assert torch.equal(gradient, torch.tensor(expected_gradient)) collapsed = 2 / window if architecture == "PAT" else 4 * lexical / (micro * content) assert not torch.equal(gradient, torch.tensor(collapsed))
def test_resume_rejects_changed_data_horizon_world_size_and_partial_update(): expected = { "format": "pat-training-state-1", "data_fingerprint": "train-digest", "validation_fingerprint": "validation-digest", "world_size": 2, "training_config": TrainingConfig(tokens=200_000_000, accumulation_steps=2).to_dict(), } saved = {**deepcopy(expected), "seen_tokens": 123456, "step": 2, "epoch": 0, "cursor": 8, "plan_sha256": "batch-plan-digest"} validate_resume_state(saved, expected) for field, value in [("data_fingerprint", "different"), ("validation_fingerprint", "different"), ("world_size", 1), ("cursor", 7), ("seen_tokens", -1), ("plan_sha256", None)]: changed = {**deepcopy(saved), field: value} with pytest.raises(ValueError): validate_resume_state(changed, expected) changed = deepcopy(saved) changed["training_config"]["tokens"] += 100000000 with pytest.raises(ValueError, match="training_config"): validate_resume_state(changed, expected)
def test_resume_plan_accepts_epoch_boundary_and_rejects_out_of_bounds_cursor(): # Checkpoints are saved before the end-of-epoch cursor resets. Equal is # valid; greater would leave the training loop unable to make progress. state = {"cursor": 12, "plan_sha256": "same-plan"} validate_resume_plan(state, 12, "same-plan") with pytest.raises(ValueError, match="exceeds"): validate_resume_plan(state, 8, "same-plan") with pytest.raises(ValueError, match="batch order"): validate_resume_plan(state, 12, "different-plan") validate_resume_plan({"cursor": 0, "plan_sha256": None}, 12, "new-plan")
@pytest.mark.parametrize("values", [ {"warmup_tokens": 140_000_000}, {"decay_fraction": float("nan")}, {"learning_rate": float("inf")}, {"accumulation_steps": 0},])def test_invalid_training_settings_fail_before_training(values): with pytest.raises(ValueError): TrainingConfig(tokens=200_000_000, **values).gitignoreAdded+15
CHECKPOINTS.jsonAdded+19
PAT-supplement.zipAdded+3
PAT-supplement.zip.sha256Added+1
README.mdAdded+246
THIRD_PARTY_NOTICES.mdAdded+18
THIRD_PARTY_NOTICES/tokenizer/LICENSEAdded+24
configs/fa32.jsonAdded+96
configs/fa32_200m.jsonAdded+96
configs/pat32.jsonAdded+162
configs/pat32_200m.jsonAdded+162
docs/architecture.mdAdded+77
docs/configuration.mdAdded+102
docs/reproducibility.mdAdded+86
docs/verification.jsonAdded+2121
docs/verification.mdAdded+146
pyproject.tomlAdded+37
scripts/build_supplement.pyAdded+90
scripts/train_fa32.shAdded+16
scripts/train_fa32_200m.shAdded+17
scripts/train_pat32.shAdded+16
scripts/train_pat32_200m.shAdded+17
src/pat/__init__.pyAdded+6
src/pat/assets/tokenizer.jsonAdded
src/pat/assets/tokenizer_contract.jsonAdded+21
src/pat/assets/tokenizer_license.txtAdded+24
src/pat/attention.pyAdded+195
src/pat/checkpoint.pyAdded+171
src/pat/config.pyAdded+118
src/pat/data.pyAdded+202
src/pat/generate.pyAdded+103
src/pat/inference.pyAdded+116
src/pat/kernels/__init__.pyAdded+1
src/pat/kernels/attention.pyAdded
src/pat/kernels/decoding.pyAdded+1415
src/pat/kernels/layout.pyAdded+153
src/pat/losses.pyAdded+42
src/pat/model.pyAdded+284
src/pat/packing.pyAdded+161
src/pat/pat_cache.pyAdded+175
src/pat/prepare.pyAdded+83
src/pat/rotary.pyAdded+64
src/pat/serve.pyAdded+68
src/pat/tokenizer.pyAdded+46
src/pat/train.pyAdded+275
src/pat/training.pyAdded+145
tests/test_checkpoint.pyAdded+59
tests/test_data.pyAdded+80
tests/test_generation.pyAdded+49
tests/test_training.pyAdded+125