File size: 15,281 Bytes
643267a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# 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:

```bash
git clone https://huggingface.co/ICLRPAT27/PAT-code
cd 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:

```bash
python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cu128
python -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:

```bash
python -m pat.checkpoint download --repo ICLRPAT27/PAT-32 \
  --revision 3b88d323731efcac57bf6df2fa6b2aa22a93c792 --output checkpoints/PAT-32
python -m pat.checkpoint verify checkpoints/PAT-32
```

```bash
python -m pat.checkpoint download --repo ICLRPAT27/FA-32 \
  --revision b71320e3a015dc94fc1147fe8891ebd46dfd429f --output checkpoints/FA-32
python -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

```bash
python -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:

```bash
python -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:

```bash
python -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:

```bash
DATA=data/train VALIDATION=data/val OUTPUT=runs/pat32 bash scripts/train_pat32.sh
DATA=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:

```bash
torchrun --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:

```bash
TRAINING_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:

```bash
DATA=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

```python
from pat.checkpoint import load_checkpoint, save_checkpoint, verify_checkpoint
from pat.generate import generate
from 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

```bash
python -m pat.serve --checkpoint checkpoints/PAT-32 --port 8000
```

The server exposes the same text-continuation behavior as the generation command:

```bash
curl 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).