Download README.md from ICLRPAT27/PAT-code: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/README.md
- Command line
-
hf download hf://ICLRPAT27/PAT-code/README.md
-
curl -L -o README.md https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/README.md
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 explains the fixed model choices; the reproducibility guide records the training recipe and the verification record records measured checks and their limits.
Installation
The anonymous source repository contains this code and documentation. Clone it before installing, or extract the supplied source ZIP and open its root directory:
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:
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 for measured checks. The CUDA 12.8 wheel installation follows the official PyTorch instructions.
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.
| Model | Parameters | Training target | Checkpoint publication |
|---|---|---|---|
| PAT-32 | approximately 1.715B | 9.52B tokens | Pinned weights |
| FA-32 | approximately 1.715B | 9.52B tokens | Pinned weights |
Download either model at its immutable revision:
python -m pat.checkpoint download --repo ICLRPAT27/PAT-32 \
--revision 3b88d323731efcac57bf6df2fa6b2aa22a93c792 --output checkpoints/PAT-32
python -m pat.checkpoint verify checkpoints/PAT-32
python -m pat.checkpoint download --repo ICLRPAT27/FA-32 \
--revision b71320e3a015dc94fc1147fe8891ebd46dfd429f --output checkpoints/FA-32
python -m pat.checkpoint verify checkpoints/FA-32
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.
Generate text
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:
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.
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:
{"text": "The first document's text goes here."}
{"text": "Another independent document goes here."}
Prepare the training and validation sets separately:
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 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:
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:
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 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:
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:
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.
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 reports exact scopes and numerical limits, including the strict small-PAT validation criterion that remained unmet.
--tokens overrides the complete schedule horizon for a new run. Resuming an existing run must preserve its declared horizon.
Python API
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 documents model construction and the architecture guide 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
python -m pat.serve --checkpoint checkpoints/PAT-32 --port 8000
The server exposes the same text-continuation behavior as the generation command:
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 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 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.