Upload AR-4B pretraining codebase, configs, and cluster scripts
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- PROGRESS.md +37 -0
- README.md +153 -0
- ar/__init__.py +0 -0
- ar/data/__init__.py +0 -0
- ar/data/dataset.py +54 -0
- ar/data/prepare_data.py +188 -0
- ar/data/readonce.py +83 -0
- ar/data/tokenizer.py +24 -0
- ar/eval/__init__.py +0 -0
- ar/eval/batch_gen.py +48 -0
- ar/eval/export_ckpt.py +43 -0
- ar/eval/generate.py +66 -0
- ar/eval/gsm8k.py +63 -0
- ar/eval/humaneval.py +59 -0
- ar/eval/val_loss.py +51 -0
- ar/model/__init__.py +0 -0
- ar/model/attention.py +55 -0
- ar/model/block.py +28 -0
- ar/model/config.py +41 -0
- ar/model/mask.py +22 -0
- ar/model/mlp.py +19 -0
- ar/model/model.py +89 -0
- ar/model/rmsnorm.py +30 -0
- ar/model/rope.py +39 -0
- ar/train/__init__.py +0 -0
- ar/train/stage2.py +79 -0
- ar/train/train.py +88 -0
- ar/train/train_config.py +39 -0
- ar/train/train_fsdp.py +284 -0
- autoreload.sh +9 -0
- cleanup.sh +47 -0
- dataeval.sbatch +24 -0
- diskwatch.sh +11 -0
- eval_here.sh +39 -0
- eval_latest.sh +47 -0
- find_nodes.sh +8 -0
- finish_fw.sh +68 -0
- memtrace.sh +13 -0
- new_data.sh +52 -0
- nodecheck.sh +13 -0
- preflight.sh +7 -0
- redo_english.sh +39 -0
- resume_tok.sh +39 -0
- run_args.sh +13 -0
- sanity_4node.sbatch +46 -0
- save_final.sh +54 -0
- save_stage1.sh +51 -0
- status.sh +33 -0
- swap.sh +10 -0
- swap2.sh +66 -0
PROGRESS.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AR progress
|
| 2 |
+
|
| 3 |
+
## Done
|
| 4 |
+
- Milestone 1: data pipeline (tokenizer, prepare_data, dataset) — 10M FineWeb tokens at /fsx/ajay-stu/ar-data/bin/fineweb.bin
|
| 5 |
+
- Milestone 2: model architecture — 4.022B params, replicates Qwen3-4B
|
| 6 |
+
- Milestone 3: single-GPU training loop — loss drops 12 -> 7.2 on 0.5B test. WORKS.
|
| 7 |
+
- Fixed: weight init bug (logits were exploding to std~32; added small-normal + residual scaling)
|
| 8 |
+
|
| 9 |
+
## Next: Milestone 4 — scale to 8 GPUs (FSDP)
|
| 10 |
+
|
| 11 |
+
## Open issues
|
| 12 |
+
- Storage: /fsx is 100% full. Need /fsxb write access from admin for real run.
|
| 13 |
+
- TODO: intra-document masking (option 2) before real training
|
| 14 |
+
- TODO: full 4B needs FSDP + bf16 + grad checkpointing (single GPU OOMs)
|
| 15 |
+
|
| 16 |
+
## Run that works
|
| 17 |
+
python -m ar.train.train --bin /fsx/ajay-stu/ar-data/bin/fineweb.bin --model_size small --max_steps 200 --batch_size 2 --seq_len 1024 --warmup_steps 20
|
| 18 |
+
|
| 19 |
+
## Session 2 update
|
| 20 |
+
- Milestone 4 DONE: FSDP2 multi-GPU works. Full 4B trains across 8 H100s (was OOM on 1 GPU).
|
| 21 |
+
- train_fsdp.py is the multi-GPU script. Launch: torchrun --nproc_per_node=8 -m ar.train.train_fsdp ...
|
| 22 |
+
- Verified: 2-GPU (0.5B) and 8-GPU (full 4B) both run, loss at correct 11.9 baseline.
|
| 23 |
+
|
| 24 |
+
## BLOCKER for real training: storage + data
|
| 25 |
+
- Only have 10M tokens (40MB, english only) — too small, would overfit.
|
| 26 |
+
- Need: (1) /fsxb access or other big storage, (2) prep real multi-source dataset (200B+ tokens for strong base)
|
| 27 |
+
- Storage frees up in mornings when others aren't using cluster.
|
| 28 |
+
|
| 29 |
+
## Next session (morning)
|
| 30 |
+
1. Sort storage (check /fsxb, /fsx free space)
|
| 31 |
+
2. Prep real dataset: all 3 sources, target 200B+ tokens (uint32 = ~800GB, so storage matters)
|
| 32 |
+
3. THEN launch real training run (this is the overnight-worthy job)
|
| 33 |
+
|
| 34 |
+
## Minor TODOs
|
| 35 |
+
- torch.manual_seed() in setup to silence DTensor RNG warning
|
| 36 |
+
- intra-document masking (option 2) before real run
|
| 37 |
+
- Milestones remaining: M5 multi-node, M6 efficiency, M7 sampling/eval
|
README.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AR (Autoregressive 4B) — Full Pretraining Codebase & Infrastructure
|
| 2 |
+
|
| 3 |
+
Pretraining codebase, cluster orchestration scripts, data pipeline, and evaluation harness for **AR-4B**, a 4.02B-parameter decoder-only transformer pretrained from scratch on ~325B tokens across up to 64x NVIDIA H100 GPUs.
|
| 4 |
+
|
| 5 |
+
- **Pretrained Weights & Model Card:** [AjayRangoji/AR-4B-base](https://huggingface.co/AjayRangoji/AR-4B-base)
|
| 6 |
+
- **Architecture:** 4.02B parameters, 36 layers, hidden size 2,560, GQA (32/8 heads, head dim 128), SwiGLU MLP (inner size 9,728), QK-norm RMSNorm, RoPE (theta = 1,000,000), tied input/output embeddings, 151,936 vocab (Qwen3 BPE).
|
| 7 |
+
- **Scale:** ~325 Billion tokens (Stage 1 ~300B general + Stage 2 ~25B reasoning & code anneal).
|
| 8 |
+
- **Framework:** PyTorch FSDP2, bf16 compute / fp32 reductions, activation checkpointing, FlexAttention with document masking.
|
| 9 |
+
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
## Repository Structure
|
| 13 |
+
|
| 14 |
+
```
|
| 15 |
+
AR/
|
| 16 |
+
├── ar/ # Core Python package
|
| 17 |
+
│ ├── model/ # Model architecture (Qwen3 / Llama-style transformer)
|
| 18 |
+
│ │ ├── attention.py # Grouped-Query Attention with QK-norm & RoPE
|
| 19 |
+
│ │ ├── block.py # Transformer decoder block with pre-RMSNorm & residual
|
| 20 |
+
│ │ ├── config.py # ModelConfig dataclass
|
| 21 |
+
│ │ ├── mask.py # Intra-document causal attention masking
|
| 22 |
+
│ │ ├── mlp.py # SwiGLU feed-forward network
|
| 23 |
+
│ │ ├── model.py # Full AR transformer causal LM implementation
|
| 24 |
+
│ │ ├── rmsnorm.py # fp32 RMSNorm implementation
|
| 25 |
+
│ │ └── rope.py # Rotary Position Embedding
|
| 26 |
+
│ ├── train/ # Distributed training routines
|
| 27 |
+
│ │ ├── train_fsdp.py # Distributed FSDP2 training engine (multi-node, 64x H100)
|
| 28 |
+
│ │ ├── train.py # Single-GPU training loop (development & testing)
|
| 29 |
+
│ │ ├── train_config.py # Training hyperparameters & config
|
| 30 |
+
│ │ └── stage2.py # Stage 2 data loader & reasoning anneal curriculum
|
| 31 |
+
│ ├── data/ # Data preparation & dataset iterators
|
| 32 |
+
│ │ ├── prepare_data.py # Tokenization pipeline for FineWeb, FineMath, The Stack
|
| 33 |
+
│ │ ├── dataset.py # Chunked binary dataset reader
|
| 34 |
+
│ │ ├── readonce.py # Memory-efficient streaming data loader
|
| 35 |
+
│ │ └── tokenizer.py # Tokenizer wrapper
|
| 36 |
+
│ └── eval/ # Benchmarking & checkpoint export
|
| 37 |
+
│ ├── val_loss.py # Held-out validation loss evaluation
|
| 38 |
+
│ ├── gsm8k.py # 8-shot GSM8K evaluation
|
| 39 |
+
│ ├── humaneval.py # HumanEval pass@1 coding benchmark
|
| 40 |
+
│ ├── generate.py # Greedy & top-p text generation
|
| 41 |
+
│ ├── batch_gen.py # Batched inference
|
| 42 |
+
│ └── export_ckpt.py # Weights-only bf16 checkpoint exporter
|
| 43 |
+
│
|
| 44 |
+
├── Slurm Job Scripts:
|
| 45 |
+
│ ├── train_real.sbatch # Production multi-node training job launcher (FSDP2)
|
| 46 |
+
│ ├── tokenize.sbatch # Parallel tokenization batch job
|
| 47 |
+
│ ├── dataeval.sbatch # Dataset validation job
|
| 48 |
+
│ ├── sweep_lr.sbatch # Learning rate sweep job
|
| 49 |
+
│ ├── test_ckpt.sbatch # Checkpoint sanity testing
|
| 50 |
+
│ └── sanity_4node.sbatch # Multi-node interconnect & cluster sanity check
|
| 51 |
+
│
|
| 52 |
+
├── Cluster Operations & Automation:
|
| 53 |
+
│ ├── watchdog.sh # Autonomous monitoring daemon (detects hangs/crashes, auto-resumes)
|
| 54 |
+
│ ├── save_stage1.sh # Waits for Stage 1 checkpoint & exports bf16 model
|
| 55 |
+
│ ├── save_final.sh # Waits for final checkpoint (ckpt_619699) & exports bf16 model
|
| 56 |
+
│ ├── run_args.sh # Training hyperparameters, data mix, learning rate schedule
|
| 57 |
+
│ ├── status.sh # Live cluster & GPU status summary
|
| 58 |
+
│ ├── autoreload.sh # Hot-reloads training code upon checkpoint completion
|
| 59 |
+
│ ├── cleanup.sh # Checkpoint garbage collection & disk space management
|
| 60 |
+
│ ├── diskwatch.sh # Disk utilization watcher
|
| 61 |
+
│ ├── eval_here.sh / eval_latest.sh # Quick local and remote evaluation runners
|
| 62 |
+
│ ├── find_nodes.sh / nodecheck.sh / testnodes.sh # Node diagnostics & bad-node isolation
|
| 63 |
+
│ └── swap.sh / swap2.sh # Node swapping utilities
|
| 64 |
+
│
|
| 65 |
+
├── upload/ # Hugging Face export & conversion utilities
|
| 66 |
+
│ ├── convert_and_check.py # Converts PyTorch FSDP weights to safetensors & validates parity
|
| 67 |
+
│ ├── modeling_ar.py # Hugging Face Transformers custom model definition
|
| 68 |
+
│ └── README.md # Model card published with weights
|
| 69 |
+
│
|
| 70 |
+
└── PROGRESS.md # Training log notes, milestones, and decisions
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
---
|
| 74 |
+
|
| 75 |
+
## Training Methodology
|
| 76 |
+
|
| 77 |
+
### 1. Model Architecture
|
| 78 |
+
| Specification | Value |
|
| 79 |
+
|---|---|
|
| 80 |
+
| **Parameters** | 4,022,238,720 (4.02B) |
|
| 81 |
+
| **Layers** | 36 decoder blocks |
|
| 82 |
+
| **Hidden dimension** | 2,560 |
|
| 83 |
+
| **Heads (Q / KV)** | 32 query heads / 8 key-value heads (GQA) |
|
| 84 |
+
| **Head dimension** | 128 |
|
| 85 |
+
| **MLP inner dimension** | 9,728 (SwiGLU) |
|
| 86 |
+
| **Position encoding** | RoPE (base $\theta = 1,000,000$) |
|
| 87 |
+
| **Normalization** | RMSNorm ($\epsilon = 10^{-6}$), computed in fp32; QK-norm per head |
|
| 88 |
+
| **Embeddings** | Tied input embedding and output projection |
|
| 89 |
+
| **Vocabulary** | 151,936 BPE tokens (`Qwen/Qwen3-4B`) |
|
| 90 |
+
| **Context Length** | 4,096 tokens per sequence |
|
| 91 |
+
|
| 92 |
+
### 2. Multi-Stage Pretraining Curriculum
|
| 93 |
+
- **Stage 1 (General Pretraining, Steps 0 - 572,000, ~300B tokens):**
|
| 94 |
+
- 65% FineWeb-Edu (English web)
|
| 95 |
+
- 20% The Stack (dedup) across 9 programming languages
|
| 96 |
+
- 15% FineMath 4+ / 3+
|
| 97 |
+
- LR schedule: Warmup to $3 \times 10^{-4} \to$ Cosine decay to $3 \times 10^{-5}$
|
| 98 |
+
- **Stage 2 (Reasoning Anneal, Steps 572,000 - 619,699, ~25B tokens):**
|
| 99 |
+
- 40% FineMath & InfiWebMath (high quality math)
|
| 100 |
+
- 30% The Stack (code)
|
| 101 |
+
- 20% FineWeb-Edu (educational quality $\ge 4$)
|
| 102 |
+
- 10% Cosmopedia v2 (synthetic textbooks & tutorials)
|
| 103 |
+
- LR schedule: Warmup to $1 \times 10^{-4} \to$ Cosine decay to $1 \times 10^{-5}$
|
| 104 |
+
|
| 105 |
+
### 3. Benchmarks & Results
|
| 106 |
+
| Benchmark | Stage 1 Final | Stage 2 Final |
|
| 107 |
+
|---|---|---|
|
| 108 |
+
| **Python held-out loss** | 0.966 | **0.929** |
|
| 109 |
+
| **English held-out loss** | 2.220 | 2.300 |
|
| 110 |
+
| **HumanEval pass@1 (greedy)** | 18.9% (31/164) | **25.0% (41/164)** |
|
| 111 |
+
| **GSM8K 8-shot exact match** | 31.6% (79/250) | **43.6% (109/250)** |
|
| 112 |
+
|
| 113 |
+
---
|
| 114 |
+
|
| 115 |
+
## Quickstart
|
| 116 |
+
|
| 117 |
+
### Environment Setup
|
| 118 |
+
```bash
|
| 119 |
+
python3 -m venv .venv
|
| 120 |
+
source .venv/bin/activate
|
| 121 |
+
pip install torch transformers datasets safetensors huggingface_hub
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
### Single GPU Smoke Test
|
| 125 |
+
```bash
|
| 126 |
+
python -m ar.train.train --model_size small --max_steps 100 --batch_size 2 --seq_len 1024
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
### Distributed Multi-GPU Training (FSDP2)
|
| 130 |
+
```bash
|
| 131 |
+
# Launch across 8 GPUs on a single node:
|
| 132 |
+
torchrun --nproc_per_node=8 -m ar.train.train_fsdp
|
| 133 |
+
|
| 134 |
+
# Launch on Slurm cluster (64x H100):
|
| 135 |
+
sbatch train_real.sbatch
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
### Checkpoint Export & Hugging Face Conversion
|
| 139 |
+
```bash
|
| 140 |
+
# Export trained checkpoint to weights-only bf16:
|
| 141 |
+
python -m ar.eval.export_ckpt --ckpt /path/to/ckpt --out /path/to/model.pt
|
| 142 |
+
|
| 143 |
+
# Convert to Hugging Face safetensors format and verify numerical outputs:
|
| 144 |
+
python upload/convert_and_check.py \
|
| 145 |
+
--ckpt /path/to/model.pt \
|
| 146 |
+
--out /path/to/hf_export \
|
| 147 |
+
--tokenizer_src /path/to/tokenizer
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
---
|
| 151 |
+
|
| 152 |
+
## License
|
| 153 |
+
Apache-2.0
|
ar/__init__.py
ADDED
|
File without changes
|
ar/data/__init__.py
ADDED
|
File without changes
|
ar/data/dataset.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class BinDataset:
|
| 6 |
+
"""Serves training batches from one or more memory-mapped .bin token files.
|
| 7 |
+
|
| 8 |
+
Memory-mapping lets us read slices of a huge file without loading it into RAM.
|
| 9 |
+
Each sample is a random window; input and target are the window shifted by one.
|
| 10 |
+
Also returns segment IDs so attention can stay inside document boundaries.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
bin_paths: list[str],
|
| 16 |
+
seq_len: int,
|
| 17 |
+
weights: list[float] | None = None,
|
| 18 |
+
eot_token_id: int = 151643,
|
| 19 |
+
):
|
| 20 |
+
self.seq_len = seq_len
|
| 21 |
+
self.eot_token_id = eot_token_id
|
| 22 |
+
# open each source as a read-only memory map of uint32 token ids
|
| 23 |
+
self.data = [np.memmap(p, dtype=np.uint32, mode="r") for p in bin_paths]
|
| 24 |
+
self.lengths = [len(d) for d in self.data]
|
| 25 |
+
|
| 26 |
+
# sampling weights = the data mix (e.g. 0.65 english, 0.20 code, 0.15 math)
|
| 27 |
+
if weights is None:
|
| 28 |
+
weights = [n / sum(self.lengths) for n in self.lengths]
|
| 29 |
+
self.weights = np.array(weights) / np.sum(weights)
|
| 30 |
+
|
| 31 |
+
def get_batch(self, batch_size: int, device: str = "cuda"):
|
| 32 |
+
x = np.empty((batch_size, self.seq_len), dtype=np.int64)
|
| 33 |
+
y = np.empty((batch_size, self.seq_len), dtype=np.int64)
|
| 34 |
+
seg = np.empty((batch_size, self.seq_len), dtype=np.int32)
|
| 35 |
+
|
| 36 |
+
for i in range(batch_size):
|
| 37 |
+
# pick a source according to the mix, then a random window inside it
|
| 38 |
+
src = np.random.choice(len(self.data), p=self.weights)
|
| 39 |
+
arr, n = self.data[src], self.lengths[src]
|
| 40 |
+
start = np.random.randint(0, n - self.seq_len - 1)
|
| 41 |
+
chunk = arr[start : start + self.seq_len + 1].astype(np.int64)
|
| 42 |
+
x[i] = chunk[:-1] # input: tokens 0..seq_len-1
|
| 43 |
+
y[i] = chunk[1:] # target: same window shifted by one
|
| 44 |
+
|
| 45 |
+
# segment IDs bump AFTER each EOT, so EOT stays with the doc it ends.
|
| 46 |
+
# Example x[i]=[a,b,EOT,c,d,EOT,e] -> seg[i]=[0,0,0,1,1,1,2]
|
| 47 |
+
is_eot = (x[i] == self.eot_token_id).astype(np.int32)
|
| 48 |
+
seg[i] = np.cumsum(is_eot) - is_eot
|
| 49 |
+
|
| 50 |
+
# pin_memory + non_blocking speeds up the CPU->GPU copy during training
|
| 51 |
+
xt = torch.from_numpy(x).pin_memory().to(device, non_blocking=True)
|
| 52 |
+
yt = torch.from_numpy(y).pin_memory().to(device, non_blocking=True)
|
| 53 |
+
st = torch.from_numpy(seg).pin_memory().to(device, non_blocking=True)
|
| 54 |
+
return xt, yt, st
|
ar/data/prepare_data.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Offline data preparation (parallel tokenization).
|
| 2 |
+
|
| 3 |
+
Streams raw text from a Hugging Face dataset, tokenizes it across many CPU
|
| 4 |
+
worker processes, and appends the token ids to a per-source .bin file (uint32).
|
| 5 |
+
Documents are separated by the tokenizer's end-of-text id.
|
| 6 |
+
|
| 7 |
+
Code sources are read one language at a time (e.g. "stack_python" reads only
|
| 8 |
+
Python) and pass a quality filter that drops data dumps and minified files.
|
| 9 |
+
|
| 10 |
+
--skip_docs skips documents an earlier run already used, so batches never
|
| 11 |
+
overlap. Each run prints the value to pass as the next run's --skip_docs.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
# each worker is its own process, so the tokenizer must NOT also spawn internal
|
| 17 |
+
# threads — those Rust threads race Python's shutdown and crash on exit
|
| 18 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import itertools
|
| 22 |
+
import multiprocessing as mp
|
| 23 |
+
import re
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
from datasets import load_dataset
|
| 27 |
+
|
| 28 |
+
from .tokenizer import Tokenizer
|
| 29 |
+
|
| 30 |
+
# stop cleanly (keeping everything written) if the shared disk gets this full
|
| 31 |
+
MIN_FREE_BYTES = 300 * 1024**3
|
| 32 |
+
DTYPE = np.uint32 # vocab > 65535, so 2 bytes is not enough
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def free_bytes(path: str) -> int:
|
| 36 |
+
st = os.statvfs(path)
|
| 37 |
+
return st.f_bavail * st.f_frsize
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# each source: (HF repo, config, data_dir, text column, split, is_code)
|
| 41 |
+
SOURCES = {
|
| 42 |
+
"fineweb": ("HuggingFaceFW/fineweb-edu", "sample-350BT", None, "text", "train", False),
|
| 43 |
+
"finemath": ("HuggingFaceTB/finemath", "finemath-4plus", None, "text", "train", False),
|
| 44 |
+
"finemath3": ("HuggingFaceTB/finemath", "finemath-3plus", None, "text", "train", False),
|
| 45 |
+
"cosmopedia": ("HuggingFaceTB/smollm-corpus", "cosmopedia-v2", None, "text", "train", False),
|
| 46 |
+
"infiwebmath": ("HuggingFaceTB/finemath", "infiwebmath-4plus", None, "text", "train", False),
|
| 47 |
+
"fineweb_hq": ("HuggingFaceFW/fineweb-edu", "sample-350BT", None, "text", "train", False),
|
| 48 |
+
"stack": ("bigcode/the-stack-dedup", None, None, "content", "train", True),
|
| 49 |
+
}
|
| 50 |
+
# one source per language: "stack_python" reads only the data/python folder
|
| 51 |
+
CODE_LANGS = ["python", "javascript", "java", "cpp", "typescript",
|
| 52 |
+
"go", "rust", "shell", "sql"]
|
| 53 |
+
for _lang in CODE_LANGS:
|
| 54 |
+
SOURCES[f"stack_{_lang}"] = ("bigcode/the-stack-dedup", None, f"data/{_lang}",
|
| 55 |
+
"content", "train", True)
|
| 56 |
+
# keep only documents with at least this quality score (fineweb-edu's 0-5 "int_score")
|
| 57 |
+
MIN_INT_SCORE = {"fineweb_hq": 4}
|
| 58 |
+
|
| 59 |
+
# --- code quality filter (StarCoder-style rules) --------------------------
|
| 60 |
+
_HEX = re.compile(r"0x[0-9a-fA-F]{2,}")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _looks_like_good_code(text: str) -> bool:
|
| 64 |
+
lines = text.split("\n")
|
| 65 |
+
if max(len(l) for l in lines) > 1000: # minified / one giant line
|
| 66 |
+
return False
|
| 67 |
+
if len(text) / len(lines) > 100: # very long lines on average
|
| 68 |
+
return False
|
| 69 |
+
if sum(c.isalnum() for c in text) / len(text) < 0.25: # mostly symbols
|
| 70 |
+
return False
|
| 71 |
+
if sum(len(m) for m in _HEX.findall(text)) / len(text) > 0.2: # hex data tables
|
| 72 |
+
return False
|
| 73 |
+
if sum(c.isdigit() for c in text) / len(text) > 0.4: # numeric data tables
|
| 74 |
+
return False
|
| 75 |
+
return True
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# --- worker side ---------------------------------------------------------
|
| 79 |
+
# each worker builds its own tokenizer once (tokenizers aren't shareable
|
| 80 |
+
# across processes), then reuses it for every document it receives
|
| 81 |
+
_worker_tok = None
|
| 82 |
+
_worker_is_code = False
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _init_worker(is_code):
|
| 86 |
+
global _worker_tok, _worker_is_code
|
| 87 |
+
_worker_tok = Tokenizer()
|
| 88 |
+
_worker_is_code = is_code
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _encode_one(text: str) -> np.ndarray:
|
| 92 |
+
# a rejected document comes back empty; the main process skips it
|
| 93 |
+
if not text or (_worker_is_code and not _looks_like_good_code(text)):
|
| 94 |
+
return np.empty(0, dtype=DTYPE)
|
| 95 |
+
ids = _worker_tok.encode(text)
|
| 96 |
+
ids.append(_worker_tok.eot_id)
|
| 97 |
+
return np.array(ids, dtype=DTYPE)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# --- main side -----------------------------------------------------------
|
| 101 |
+
SCORE_STATS = {"seen": 0, "low": 0} # docs streamed / docs below min score
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _doc_texts(ds, text_col, min_score=0):
|
| 105 |
+
# pull the text out of each document, skipping low-quality ones if asked
|
| 106 |
+
for doc in ds:
|
| 107 |
+
SCORE_STATS["seen"] += 1
|
| 108 |
+
if min_score and (doc.get("int_score") or 0) < min_score:
|
| 109 |
+
SCORE_STATS["low"] += 1
|
| 110 |
+
continue
|
| 111 |
+
yield doc[text_col] or ""
|
| 112 |
+
|
| 113 |
+
def prepare(source: str, out_dir: str, target_tokens: int,
|
| 114 |
+
num_workers: int, chunk_docs: int = 10_000, skip_docs: int = 0,
|
| 115 |
+
data_files=None):
|
| 116 |
+
repo, config, data_dir, text_col, split, is_code = SOURCES[source]
|
| 117 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 118 |
+
out_path = os.path.join(out_dir, f"{source}.bin")
|
| 119 |
+
# fresh data appended to an old file would mix two different runs
|
| 120 |
+
if skip_docs == 0 and os.path.exists(out_path) and os.path.getsize(out_path) > 0:
|
| 121 |
+
raise SystemExit(f"[refuse] {out_path} already has data: delete it first")
|
| 122 |
+
|
| 123 |
+
if data_files:
|
| 124 |
+
# read one specific file directly (e.g. a late shard for a held-out set)
|
| 125 |
+
ds = load_dataset(repo, data_files=data_files, split=split, streaming=True)
|
| 126 |
+
else:
|
| 127 |
+
ds = load_dataset(repo, config, data_dir=data_dir, split=split, streaming=True)
|
| 128 |
+
print(f"[read] {repo} files={data_files} config={config} data_dir={data_dir}", flush=True)
|
| 129 |
+
texts = _doc_texts(ds, text_col, MIN_INT_SCORE.get(source, 0))
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# skip documents an earlier run already consumed, so batches never overlap
|
| 133 |
+
if skip_docs > 0:
|
| 134 |
+
print(f" [skip] skipping first {skip_docs:,} documents", flush=True)
|
| 135 |
+
texts = itertools.islice(texts, skip_docs, None)
|
| 136 |
+
|
| 137 |
+
written = n_docs = n_kept = 0
|
| 138 |
+
stopped_early = False
|
| 139 |
+
|
| 140 |
+
# imap keeps results IN ORDER and pulls lazily, so memory stays small
|
| 141 |
+
pool = mp.Pool(num_workers, initializer=_init_worker, initargs=(is_code,))
|
| 142 |
+
try:
|
| 143 |
+
with open(out_path, "ab") as f:
|
| 144 |
+
for arr in pool.imap(_encode_one, texts, chunksize=64):
|
| 145 |
+
n_docs += 1 # counts every streamed doc (for --skip_docs)
|
| 146 |
+
if arr.size:
|
| 147 |
+
arr.tofile(f) # main process is the only writer
|
| 148 |
+
written += arr.size
|
| 149 |
+
n_kept += 1
|
| 150 |
+
if written >= target_tokens:
|
| 151 |
+
break
|
| 152 |
+
if n_docs % chunk_docs == 0:
|
| 153 |
+
if free_bytes(out_dir) < MIN_FREE_BYTES:
|
| 154 |
+
print(f"\n[stop] free space below {MIN_FREE_BYTES/1e9:.0f} GB",
|
| 155 |
+
flush=True)
|
| 156 |
+
stopped_early = True
|
| 157 |
+
break
|
| 158 |
+
finally:
|
| 159 |
+
pool.terminate()
|
| 160 |
+
pool.join()
|
| 161 |
+
|
| 162 |
+
if MIN_INT_SCORE.get(source):
|
| 163 |
+
low = 100 * SCORE_STATS["low"] / max(SCORE_STATS["seen"], 1)
|
| 164 |
+
print(f"\n[score] {low:.0f}% of streamed docs had int_score < {MIN_INT_SCORE[source]}")
|
| 165 |
+
status = "STOPPED EARLY (disk)" if stopped_early else "done"
|
| 166 |
+
dropped = 100 * (1 - n_kept / max(n_docs, 1))
|
| 167 |
+
print(f"\n[{status}] {source}: {written/1e6:.1f}M tokens, "
|
| 168 |
+
f"{n_docs:,} docs read, {dropped:.0f}% dropped by code filter")
|
| 169 |
+
print(f"[next] for the following run, pass --skip_docs {skip_docs + n_docs}",
|
| 170 |
+
flush=True)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
p = argparse.ArgumentParser()
|
| 175 |
+
p.add_argument("--source", required=True, choices=list(SOURCES))
|
| 176 |
+
p.add_argument("--out_dir", default="/fsx/ajay-stu/ar-data/bin")
|
| 177 |
+
p.add_argument("--target_tokens", type=int, default=100_000_000)
|
| 178 |
+
p.add_argument("--skip_docs", type=int, default=0)
|
| 179 |
+
p.add_argument("--num_workers", type=int, default=max(1, mp.cpu_count() - 4))
|
| 180 |
+
p.add_argument("--data_files", default=None)
|
| 181 |
+
|
| 182 |
+
args = p.parse_args()
|
| 183 |
+
prepare(args.source, args.out_dir, args.target_tokens, args.num_workers,
|
| 184 |
+
skip_docs=args.skip_docs, data_files=args.data_files or None)
|
| 185 |
+
|
| 186 |
+
# HF's fast tokenizer leaves native threads that crash normal interpreter
|
| 187 |
+
# shutdown; the file is closed above, so exit immediately
|
| 188 |
+
os._exit(0)
|
ar/data/readonce.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-once data loader (Stage 2).
|
| 2 |
+
|
| 3 |
+
Each file is cut into windows of seq_len+1 tokens that overlap by exactly one token
|
| 4 |
+
(x = first seq_len tokens, y = the same window shifted by one), so every token is a
|
| 5 |
+
prediction target once. Each file's windows are shuffled once with a fixed seed, and a
|
| 6 |
+
fixed schedule says which file every sample comes from, following the mix weights.
|
| 7 |
+
|
| 8 |
+
Everything is computed from (seed, step, slot), so a restart at any step continues
|
| 9 |
+
exactly where training stopped, with no saved loader state. A window is only reused
|
| 10 |
+
after its whole file has been read once.
|
| 11 |
+
"""
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
# 524,288 tokens / 4096 = 128 sequences: the most any node count uses in one step.
|
| 15 |
+
# Each step owns 128 sample slots; node counts that use fewer just skip the rest.
|
| 16 |
+
SAMPLES_PER_STEP = 128
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ReadOnceDataset:
|
| 20 |
+
def __init__(self, bin_paths, seq_len, weights, start_step, end_step, eot_token_id, seed=1234):
|
| 21 |
+
assert end_step > start_step, "empty stage"
|
| 22 |
+
self.seq_len = seq_len
|
| 23 |
+
self.start_step = start_step
|
| 24 |
+
self.eot = eot_token_id
|
| 25 |
+
self.data = [np.memmap(p, dtype=np.uint32, mode="r") for p in bin_paths]
|
| 26 |
+
self.n_windows = [(len(d) - 1) // seq_len for d in self.data]
|
| 27 |
+
assert all(n > 0 for n in self.n_windows), "a file is shorter than one window"
|
| 28 |
+
w = np.asarray(weights, dtype=np.float64)
|
| 29 |
+
assert len(w) == len(self.data) and (w >= 0).all() and w.sum() > 0, "bad weights"
|
| 30 |
+
w = w / w.sum()
|
| 31 |
+
|
| 32 |
+
# each file's windows in one fixed shuffled order (int32 keeps RAM small)
|
| 33 |
+
self.perm = [np.random.default_rng(seed + 1000 + f).permutation(n).astype(np.int32)
|
| 34 |
+
for f, n in enumerate(self.n_windows)]
|
| 35 |
+
|
| 36 |
+
# which file each sample of the stage reads, and how many earlier samples used that file
|
| 37 |
+
self.total = (end_step - start_step) * SAMPLES_PER_STEP
|
| 38 |
+
self.src = np.random.default_rng(seed).choice(len(w), size=self.total, p=w).astype(np.int16)
|
| 39 |
+
self.occ = np.empty(self.total, dtype=np.int64)
|
| 40 |
+
for f in range(len(w)):
|
| 41 |
+
idx = np.flatnonzero(self.src == f)
|
| 42 |
+
self.occ[idx] = np.arange(len(idx))
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
def slot(micro, i, rank, world, batch_size):
|
| 46 |
+
"""Position of one sequence inside its step's 128 slots; unique per (micro, i, rank)."""
|
| 47 |
+
s = (micro * batch_size + i) * world + rank
|
| 48 |
+
assert s < SAMPLES_PER_STEP, "more than 128 sequences per step: raise SAMPLES_PER_STEP"
|
| 49 |
+
return s
|
| 50 |
+
|
| 51 |
+
def window(self, step, slot):
|
| 52 |
+
"""(file index, window index, tokens) for one sample; tokens has seq_len+1 entries."""
|
| 53 |
+
k = (step - self.start_step) * SAMPLES_PER_STEP + slot
|
| 54 |
+
assert 0 <= k < self.total, f"step {step} is outside this stage"
|
| 55 |
+
f = int(self.src[k])
|
| 56 |
+
w = int(self.perm[f][self.occ[k] % self.n_windows[f]])
|
| 57 |
+
start = w * self.seq_len
|
| 58 |
+
tokens = np.asarray(self.data[f][start : start + self.seq_len + 1], dtype=np.int64)
|
| 59 |
+
return f, w, tokens
|
| 60 |
+
|
| 61 |
+
def get_numpy(self, step, micro, batch_size, rank, world):
|
| 62 |
+
"""One micro-batch as numpy arrays: inputs, targets, document ids."""
|
| 63 |
+
x = np.empty((batch_size, self.seq_len), dtype=np.int64)
|
| 64 |
+
y = np.empty((batch_size, self.seq_len), dtype=np.int64)
|
| 65 |
+
seg = np.empty((batch_size, self.seq_len), dtype=np.int32)
|
| 66 |
+
for i in range(batch_size):
|
| 67 |
+
_, _, chunk = self.window(step, self.slot(micro, i, rank, world, batch_size))
|
| 68 |
+
x[i], y[i] = chunk[:-1], chunk[1:]
|
| 69 |
+
# document id goes up AFTER each end-of-text, so the EOT stays with its own document
|
| 70 |
+
is_eot = (x[i] == self.eot).astype(np.int32)
|
| 71 |
+
seg[i] = np.cumsum(is_eot) - is_eot
|
| 72 |
+
return x, y, seg
|
| 73 |
+
|
| 74 |
+
def get_batch(self, step, micro, batch_size, rank, world, device="cuda"):
|
| 75 |
+
"""Same as get_numpy, as torch tensors on `device`."""
|
| 76 |
+
import torch
|
| 77 |
+
out = []
|
| 78 |
+
for a in self.get_numpy(step, micro, batch_size, rank, world):
|
| 79 |
+
t = torch.from_numpy(a)
|
| 80 |
+
if torch.device(device).type == "cuda":
|
| 81 |
+
t = t.pin_memory().to(device, non_blocking=True)
|
| 82 |
+
out.append(t)
|
| 83 |
+
return tuple(out)
|
ar/data/tokenizer.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import AutoTokenizer
|
| 2 |
+
|
| 3 |
+
# Qwen3's tokenizer: BPE, ~151936 vocab, already strong on English/code/math
|
| 4 |
+
QWEN_TOKENIZER = "Qwen/Qwen3-4B"
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Tokenizer:
|
| 8 |
+
"""Wraps Qwen3's pretrained tokenizer for the data pipeline."""
|
| 9 |
+
|
| 10 |
+
def __init__(self, name: str = QWEN_TOKENIZER):
|
| 11 |
+
self.tok = AutoTokenizer.from_pretrained(name)
|
| 12 |
+
# end-of-text id marks document boundaries when we pack tokens together
|
| 13 |
+
self.eot_id = self.tok.eos_token_id
|
| 14 |
+
|
| 15 |
+
def encode(self, text: str) -> list[int]:
|
| 16 |
+
# plain token ids, no special tokens added automatically
|
| 17 |
+
return self.tok.encode(text, add_special_tokens=False)
|
| 18 |
+
|
| 19 |
+
def decode(self, ids: list[int]) -> str:
|
| 20 |
+
return self.tok.decode(ids)
|
| 21 |
+
|
| 22 |
+
@property
|
| 23 |
+
def vocab_size(self) -> int:
|
| 24 |
+
return self.tok.vocab_size
|
ar/eval/__init__.py
ADDED
|
File without changes
|
ar/eval/batch_gen.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batched greedy generation for benchmarks (no KV cache: simple, not fast)."""
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from ar.model.mask import build_doc_block_mask
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@torch.no_grad()
|
| 8 |
+
def generate_batch(model, tok, prompts, seq_len, max_new, stop, device):
|
| 9 |
+
"""Greedy-decode a batch of prompts; each output is cut at its first stop string."""
|
| 10 |
+
B = len(prompts)
|
| 11 |
+
# fixed-size buffer: each row has its own prompt length and write position;
|
| 12 |
+
# the causal mask hides the placeholder slots to the right of each position
|
| 13 |
+
buf = torch.full((B, seq_len), tok.eot_id, dtype=torch.long, device=device)
|
| 14 |
+
pos = []
|
| 15 |
+
for b, p in enumerate(prompts):
|
| 16 |
+
x = tok.encode(p)[-(seq_len - max_new):] # keep the end if a prompt is too long
|
| 17 |
+
buf[b, :len(x)] = torch.tensor(x, device=device)
|
| 18 |
+
pos.append(len(x))
|
| 19 |
+
start = list(pos)
|
| 20 |
+
seg = torch.zeros(B, seq_len, dtype=torch.int32, device=device) # one doc per row
|
| 21 |
+
mask = build_doc_block_mask(seg, seq_len, device=device)
|
| 22 |
+
done, outs = [False] * B, [""] * B
|
| 23 |
+
rows = torch.arange(B, device=device)
|
| 24 |
+
|
| 25 |
+
for _ in range(max_new):
|
| 26 |
+
logits = model(buf, mask)
|
| 27 |
+
# each row's next token = most likely token at its own current position
|
| 28 |
+
idx = torch.tensor(pos, device=device) - 1
|
| 29 |
+
nxt = logits[rows, idx].argmax(-1).tolist()
|
| 30 |
+
for b in range(B):
|
| 31 |
+
if done[b]:
|
| 32 |
+
continue
|
| 33 |
+
if nxt[b] == tok.eot_id: # model ended the text
|
| 34 |
+
done[b] = True
|
| 35 |
+
continue
|
| 36 |
+
buf[b, pos[b]] = nxt[b]
|
| 37 |
+
pos[b] += 1
|
| 38 |
+
outs[b] = tok.decode(buf[b, start[b]:pos[b]].tolist())
|
| 39 |
+
if pos[b] >= seq_len or any(s in outs[b] for s in stop):
|
| 40 |
+
done[b] = True
|
| 41 |
+
if all(done):
|
| 42 |
+
break
|
| 43 |
+
|
| 44 |
+
# cut each output at its first stop string
|
| 45 |
+
for b in range(B):
|
| 46 |
+
hits = [outs[b].find(s) for s in stop if s in outs[b]]
|
| 47 |
+
outs[b] = outs[b][: min(hits)] if hits else outs[b]
|
| 48 |
+
return outs
|
ar/eval/export_ckpt.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert a sharded training checkpoint into one plain model file for eval.
|
| 2 |
+
|
| 3 |
+
Training saves model + optimizer split across all GPUs. Eval only needs the
|
| 4 |
+
model weights, in a single file that one GPU can load.
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.distributed.checkpoint as dcp
|
| 10 |
+
|
| 11 |
+
from ar.model.config import ARConfig
|
| 12 |
+
from ar.model.model import ARModel
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def main(ckpt_dir, out_path):
|
| 16 |
+
# build on meta then allocate on CPU: skips a slow 4B-param random init
|
| 17 |
+
with torch.device("meta"):
|
| 18 |
+
model = ARModel(ARConfig())
|
| 19 |
+
model.to_empty(device="cpu")
|
| 20 |
+
sd = model.state_dict()
|
| 21 |
+
|
| 22 |
+
# see which weights the checkpoint actually holds (its keys look like "model.<name>")
|
| 23 |
+
meta = dcp.FileSystemReader(ckpt_dir).read_metadata()
|
| 24 |
+
saved = {k[len("model."):] for k in meta.state_dict_metadata if k.startswith("model.")}
|
| 25 |
+
wanted = {k: v for k, v in sd.items() if k in saved}
|
| 26 |
+
missing = [k for k in sd if k not in saved]
|
| 27 |
+
print(f"loading {len(wanted)}/{len(sd)} tensors; not in checkpoint: {missing}")
|
| 28 |
+
|
| 29 |
+
# load ONLY the model part, filling the tensors in place (optimizer is skipped)
|
| 30 |
+
dcp.load(state_dict={"model": wanted}, checkpoint_id=ckpt_dir)
|
| 31 |
+
|
| 32 |
+
# bf16 halves the file (~8 GB); eval runs in bf16 anyway
|
| 33 |
+
out = {k: v.to(torch.bfloat16) for k, v in model.state_dict().items()}
|
| 34 |
+
torch.save(out, out_path)
|
| 35 |
+
print(f"saved {len(out)} tensors -> {out_path}")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
p = argparse.ArgumentParser()
|
| 40 |
+
p.add_argument("--ckpt", required=True)
|
| 41 |
+
p.add_argument("--out", required=True)
|
| 42 |
+
args = p.parse_args()
|
| 43 |
+
main(args.ckpt, args.out)
|
ar/eval/generate.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate text from an exported checkpoint (quick quality check)."""
|
| 2 |
+
import argparse
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from ar.model.config import ARConfig
|
| 7 |
+
from ar.model.model import ARModel
|
| 8 |
+
from ar.model.mask import build_doc_block_mask
|
| 9 |
+
from ar.model.rope import build_rope_cache
|
| 10 |
+
from ar.data.tokenizer import Tokenizer
|
| 11 |
+
|
| 12 |
+
SEQ = 256 # fixed length, so FlexAttention compiles once instead of for every new length
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def load_model(path, device):
|
| 16 |
+
cfg = ARConfig()
|
| 17 |
+
with torch.device(device):
|
| 18 |
+
model = ARModel(cfg) # real init also builds correct RoPE tables
|
| 19 |
+
model.load_state_dict(torch.load(path, map_location=device))
|
| 20 |
+
model = model.to(torch.bfloat16).eval()
|
| 21 |
+
return model
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@torch.no_grad()
|
| 25 |
+
def generate(model, tok, prompt, device, max_new=150, temperature=0.8, top_k=50):
|
| 26 |
+
ids = tok.encode(prompt)
|
| 27 |
+
n = len(ids)
|
| 28 |
+
# fixed-size buffer; slots after the current position are placeholders
|
| 29 |
+
# that the causal mask hides from earlier tokens
|
| 30 |
+
buf = torch.full((1, SEQ), tok.eot_id, dtype=torch.long, device=device)
|
| 31 |
+
buf[0, :n] = torch.tensor(ids, device=device)
|
| 32 |
+
seg = torch.zeros(1, SEQ, dtype=torch.int32, device=device) # one document
|
| 33 |
+
mask = build_doc_block_mask(seg, SEQ, device=device)
|
| 34 |
+
|
| 35 |
+
pos = n
|
| 36 |
+
for pos in range(n, min(SEQ, n + max_new)):
|
| 37 |
+
logits = model(buf, mask)[0, pos - 1].float() / temperature
|
| 38 |
+
# keep only the top_k most likely tokens, then sample one of them
|
| 39 |
+
kth = torch.topk(logits, top_k).values[-1]
|
| 40 |
+
logits[logits < kth] = -float("inf")
|
| 41 |
+
nxt = torch.multinomial(torch.softmax(logits, -1), 1)
|
| 42 |
+
buf[0, pos] = nxt
|
| 43 |
+
if nxt.item() == tok.eot_id: # model decided the text is over
|
| 44 |
+
break
|
| 45 |
+
return tok.decode(buf[0, : pos + 1].tolist())
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
p = argparse.ArgumentParser()
|
| 50 |
+
p.add_argument("--model", required=True)
|
| 51 |
+
args = p.parse_args()
|
| 52 |
+
|
| 53 |
+
device = "cuda"
|
| 54 |
+
tok = Tokenizer()
|
| 55 |
+
model = load_model(args.model, device)
|
| 56 |
+
torch.manual_seed(0)
|
| 57 |
+
|
| 58 |
+
prompts = [
|
| 59 |
+
"The capital of France is",
|
| 60 |
+
"Once upon a time, there was a little",
|
| 61 |
+
"def fibonacci(n):",
|
| 62 |
+
"Question: What is 12 + 7?\nAnswer:",
|
| 63 |
+
]
|
| 64 |
+
for pr in prompts:
|
| 65 |
+
print("=" * 60, flush=True)
|
| 66 |
+
print(generate(model, tok, pr, device), flush=True)
|
ar/eval/gsm8k.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GSM8K (grade-school math): 8-shot, step-by-step, greedy, exact-match accuracy."""
|
| 2 |
+
import argparse
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
|
| 7 |
+
from ar.data.tokenizer import Tokenizer
|
| 8 |
+
from ar.eval.batch_gen import generate_batch
|
| 9 |
+
from ar.eval.generate import load_model
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def clean_answer(ans):
|
| 13 |
+
# train answers look like "... <<3*4=12>>12 ... #### 12"; turn them into
|
| 14 |
+
# plain worked solutions that end with "The answer is 12."
|
| 15 |
+
ans = re.sub(r"<<.*?>>", "", ans)
|
| 16 |
+
body, final = ans.split("####")
|
| 17 |
+
return body.strip() + f"\nThe answer is {final.strip()}."
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def extract_number(text):
|
| 21 |
+
# prefer "The answer is X"; otherwise fall back to the last number written
|
| 22 |
+
m = re.search(r"The answer is\s*\$?(-?[\d,]*\.?\d+)", text)
|
| 23 |
+
nums = [m.group(1)] if m else re.findall(r"-?[\d,]*\.?\d+", text)
|
| 24 |
+
if not nums:
|
| 25 |
+
return None
|
| 26 |
+
try:
|
| 27 |
+
return float(nums[-1].replace(",", ""))
|
| 28 |
+
except ValueError:
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
p = argparse.ArgumentParser()
|
| 34 |
+
p.add_argument("--model", required=True)
|
| 35 |
+
p.add_argument("--n", type=int, default=250) # fixed subset -> comparable runs
|
| 36 |
+
p.add_argument("--batch", type=int, default=8)
|
| 37 |
+
args = p.parse_args()
|
| 38 |
+
|
| 39 |
+
device = "cuda"
|
| 40 |
+
tok = Tokenizer()
|
| 41 |
+
model = load_model(args.model, device)
|
| 42 |
+
|
| 43 |
+
train = load_dataset("openai/gsm8k", "main", split="train")
|
| 44 |
+
test = load_dataset("openai/gsm8k", "main", split="test").select(range(args.n))
|
| 45 |
+
shots = "".join(f"Question: {ex['question']}\nAnswer: {clean_answer(ex['answer'])}\n\n"
|
| 46 |
+
for ex in train.select(range(8)))
|
| 47 |
+
|
| 48 |
+
correct = 0
|
| 49 |
+
for i in range(0, len(test), args.batch):
|
| 50 |
+
chunk = test.select(range(i, min(i + args.batch, len(test))))
|
| 51 |
+
prompts = [shots + f"Question: {ex['question']}\nAnswer:" for ex in chunk]
|
| 52 |
+
outs = generate_batch(model, tok, prompts, seq_len=2048, max_new=256,
|
| 53 |
+
stop=["Question:"], device=device)
|
| 54 |
+
for ex, out in zip(chunk, outs):
|
| 55 |
+
gold = float(ex["answer"].split("####")[-1].strip().replace(",", ""))
|
| 56 |
+
pred = extract_number(out)
|
| 57 |
+
correct += pred is not None and abs(pred - gold) < 1e-6
|
| 58 |
+
done = min(i + args.batch, len(test))
|
| 59 |
+
print(f"[{done}/{len(test)}] accuracy so far: {100 * correct / done:.1f}%", flush=True)
|
| 60 |
+
if i == 0:
|
| 61 |
+
print("--- example output ---\n" + outs[0].strip() + "\n----------------------", flush=True)
|
| 62 |
+
|
| 63 |
+
print(f"GSM8K ({len(test)} questions, 8-shot): {100 * correct / len(test):.1f}%")
|
ar/eval/humaneval.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HumanEval (Python coding): complete each function, run its unit tests, pass@1 greedy."""
|
| 2 |
+
import argparse
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
import tempfile
|
| 7 |
+
|
| 8 |
+
from datasets import load_dataset
|
| 9 |
+
|
| 10 |
+
from ar.data.tokenizer import Tokenizer
|
| 11 |
+
from ar.eval.batch_gen import generate_batch
|
| 12 |
+
from ar.eval.generate import load_model
|
| 13 |
+
|
| 14 |
+
# a new top-level statement means the function body is finished
|
| 15 |
+
STOP = ["\ndef ", "\nclass ", "\nif __name__", "\nprint(", "\n#"]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def passes(program, timeout=10):
|
| 19 |
+
# run the model-written code in a separate process with a time limit,
|
| 20 |
+
# so a crash or infinite loop can't take down the evaluation
|
| 21 |
+
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
|
| 22 |
+
f.write(program)
|
| 23 |
+
path = f.name
|
| 24 |
+
try:
|
| 25 |
+
return subprocess.run([sys.executable, path], capture_output=True,
|
| 26 |
+
timeout=timeout).returncode == 0
|
| 27 |
+
except subprocess.TimeoutExpired:
|
| 28 |
+
return False
|
| 29 |
+
finally:
|
| 30 |
+
os.remove(path)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == "__main__":
|
| 34 |
+
p = argparse.ArgumentParser()
|
| 35 |
+
p.add_argument("--model", required=True)
|
| 36 |
+
p.add_argument("--batch", type=int, default=16)
|
| 37 |
+
args = p.parse_args()
|
| 38 |
+
|
| 39 |
+
device = "cuda"
|
| 40 |
+
tok = Tokenizer()
|
| 41 |
+
model = load_model(args.model, device)
|
| 42 |
+
ds = load_dataset("openai/openai_humaneval", split="test")
|
| 43 |
+
|
| 44 |
+
solved = 0
|
| 45 |
+
for i in range(0, len(ds), args.batch):
|
| 46 |
+
chunk = ds.select(range(i, min(i + args.batch, len(ds))))
|
| 47 |
+
outs = generate_batch(model, tok, [ex["prompt"] for ex in chunk], seq_len=1536,
|
| 48 |
+
max_new=384, stop=STOP, device=device)
|
| 49 |
+
for ex, completion in zip(chunk, outs):
|
| 50 |
+
program = (ex["prompt"] + completion + "\n\n" + ex["test"]
|
| 51 |
+
+ f"\n\ncheck({ex['entry_point']})\n")
|
| 52 |
+
solved += passes(program)
|
| 53 |
+
done = min(i + args.batch, len(ds))
|
| 54 |
+
print(f"[{done}/{len(ds)}] pass@1 so far: {100 * solved / done:.1f}%", flush=True)
|
| 55 |
+
if i == 0:
|
| 56 |
+
print("--- example completion ---\n" + chunk[0]["prompt"] + outs[0]
|
| 57 |
+
+ "\n--------------------------", flush=True)
|
| 58 |
+
|
| 59 |
+
print(f"HumanEval pass@1 (greedy): {100 * solved / len(ds):.1f}% ({solved}/{len(ds)})")
|
ar/eval/val_loss.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validation loss on held-out data the model never trained on."""
|
| 2 |
+
import argparse
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
from ar.data.tokenizer import Tokenizer
|
| 11 |
+
from ar.eval.generate import load_model
|
| 12 |
+
from ar.model.mask import build_doc_block_mask
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@torch.no_grad()
|
| 16 |
+
def val_loss(model, path, eot_id, device, seq_len=4096, max_windows=200):
|
| 17 |
+
data = np.memmap(path, dtype=np.uint32, mode="r")
|
| 18 |
+
n = min(max_windows, (len(data) - 1) // seq_len)
|
| 19 |
+
total = 0.0
|
| 20 |
+
for i in range(n):
|
| 21 |
+
# fixed, non-overlapping windows from the start -> same numbers every run,
|
| 22 |
+
# so scores from different checkpoints are directly comparable
|
| 23 |
+
chunk = data[i * seq_len : (i + 1) * seq_len + 1].astype(np.int64)
|
| 24 |
+
chunk = torch.from_numpy(chunk).to(device)
|
| 25 |
+
x, y = chunk[:-1][None], chunk[1:][None]
|
| 26 |
+
# same same-document masking as training
|
| 27 |
+
is_eot = (x == eot_id).int()
|
| 28 |
+
seg = (torch.cumsum(is_eot, dim=1) - is_eot).int()
|
| 29 |
+
mask = build_doc_block_mask(seg, seq_len, device=device)
|
| 30 |
+
logits = model(x, mask)
|
| 31 |
+
total += F.cross_entropy(logits.float().view(-1, logits.size(-1)), y.view(-1)).item()
|
| 32 |
+
return total / n, n * seq_len
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if __name__ == "__main__":
|
| 36 |
+
p = argparse.ArgumentParser()
|
| 37 |
+
p.add_argument("--model", required=True)
|
| 38 |
+
p.add_argument("--data", nargs="+", required=True)
|
| 39 |
+
args = p.parse_args()
|
| 40 |
+
|
| 41 |
+
device = "cuda"
|
| 42 |
+
tok = Tokenizer()
|
| 43 |
+
model = load_model(args.model, device)
|
| 44 |
+
for path in args.data:
|
| 45 |
+
if not os.path.exists(path):
|
| 46 |
+
print(f"{os.path.basename(path)}: not found, skipping", flush=True)
|
| 47 |
+
continue
|
| 48 |
+
loss, ntok = val_loss(model, path, tok.eot_id, device)
|
| 49 |
+
# perplexity = e^loss: roughly "how many tokens the model is torn between"
|
| 50 |
+
print(f"{os.path.basename(path)}: loss {loss:.4f} | ppl {math.exp(loss):.2f} "
|
| 51 |
+
f"| {ntok/1e6:.1f}M tokens", flush=True)
|
ar/model/__init__.py
ADDED
|
File without changes
|
ar/model/attention.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torch.nn.attention.flex_attention import flex_attention
|
| 4 |
+
|
| 5 |
+
from .rmsnorm import RMSNorm
|
| 6 |
+
from .rope import apply_rope
|
| 7 |
+
|
| 8 |
+
# compile FlexAttention once at import; without compile it falls back
|
| 9 |
+
# to a very slow reference kernel
|
| 10 |
+
flex_attention = torch.compile(flex_attention)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class GroupedQueryAttention(nn.Module):
|
| 14 |
+
"""Grouped-query attention with RoPE, QK-norm, and a caller-supplied mask.
|
| 15 |
+
|
| 16 |
+
Query heads are split into groups that each share one key/value head,
|
| 17 |
+
shrinking the KV cache with almost no loss in quality. The block_mask
|
| 18 |
+
is built outside the model (causal + same-document) and simply passed in.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def __init__(self, dim: int, n_heads: int, n_kv_heads: int, head_dim: int):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.n_heads = n_heads
|
| 24 |
+
self.n_kv_heads = n_kv_heads
|
| 25 |
+
self.head_dim = head_dim
|
| 26 |
+
|
| 27 |
+
# projections: Q is full width, K/V are narrower (fewer heads)
|
| 28 |
+
self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False)
|
| 29 |
+
self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
|
| 30 |
+
self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
|
| 31 |
+
self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)
|
| 32 |
+
|
| 33 |
+
# QK-norm: normalize each head's Q and K before attention (stability)
|
| 34 |
+
self.q_norm = RMSNorm(head_dim)
|
| 35 |
+
self.k_norm = RMSNorm(head_dim)
|
| 36 |
+
|
| 37 |
+
def forward(self, x, cos, sin, block_mask):
|
| 38 |
+
B, T, _ = x.shape
|
| 39 |
+
|
| 40 |
+
# project, then split into heads: (B, heads, T, head_dim)
|
| 41 |
+
q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
|
| 42 |
+
k = self.k_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 43 |
+
v = self.v_proj(x).view(B, T, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 44 |
+
|
| 45 |
+
# QK-norm, then rotate Q and K by their positions
|
| 46 |
+
q = apply_rope(self.q_norm(q), cos, sin)
|
| 47 |
+
k = apply_rope(self.k_norm(k), cos, sin)
|
| 48 |
+
|
| 49 |
+
# FlexAttention handles GQA internally; no KV expansion required,
|
| 50 |
+
# which saves memory vs the old repeat_interleave path
|
| 51 |
+
out = flex_attention(q, k, v, block_mask=block_mask, enable_gqa=True)
|
| 52 |
+
|
| 53 |
+
# merge heads back together and project out
|
| 54 |
+
out = out.transpose(1, 2).contiguous().view(B, T, -1)
|
| 55 |
+
return self.o_proj(out)
|
ar/model/block.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from .rmsnorm import RMSNorm
|
| 5 |
+
from .attention import GroupedQueryAttention
|
| 6 |
+
from .mlp import SwiGLU
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class DecoderBlock(nn.Module):
|
| 10 |
+
"""One transformer block: attention sub-layer, then MLP sub-layer.
|
| 11 |
+
|
| 12 |
+
Each sub-layer is pre-normed and wrapped in a residual (add-back) connection.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def __init__(self, dim, n_heads, n_kv_heads, head_dim, hidden_dim, eps=1e-6):
|
| 16 |
+
super().__init__()
|
| 17 |
+
# a norm before each sub-layer
|
| 18 |
+
self.attn_norm = RMSNorm(dim, eps)
|
| 19 |
+
self.mlp_norm = RMSNorm(dim, eps)
|
| 20 |
+
self.attn = GroupedQueryAttention(dim, n_heads, n_kv_heads, head_dim)
|
| 21 |
+
self.mlp = SwiGLU(dim, hidden_dim)
|
| 22 |
+
|
| 23 |
+
def forward(self, x, cos, sin, block_mask):
|
| 24 |
+
# attention sub-layer: normalize, attend, add the result back
|
| 25 |
+
x = x + self.attn(self.attn_norm(x), cos, sin, block_mask)
|
| 26 |
+
# mlp sub-layer: normalize, process per-token, add the result back
|
| 27 |
+
x = x + self.mlp(self.mlp_norm(x))
|
| 28 |
+
return x
|
ar/model/config.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@dataclass
|
| 5 |
+
class ARConfig:
|
| 6 |
+
"""All the numbers that define the AR model's shape.
|
| 7 |
+
|
| 8 |
+
Swap these to build a different-sized model with the same code
|
| 9 |
+
(e.g. a tiny version for debugging).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
vocab_size: int = 151936 # size of the tokenizer vocabulary
|
| 13 |
+
dim: int = 2560 # hidden size (width of the residual stream)
|
| 14 |
+
n_layers: int = 36 # number of decoder blocks stacked
|
| 15 |
+
n_heads: int = 32 # query heads
|
| 16 |
+
n_kv_heads: int = 8 # key/value heads (GQA: 32 queries share 8 kv)
|
| 17 |
+
head_dim: int = 128 # size of each attention head
|
| 18 |
+
hidden_dim: int = 9728 # inner width of the SwiGLU MLP
|
| 19 |
+
max_seq_len: int = 40960 # longest sequence the model supports
|
| 20 |
+
rope_theta: float = 1_000_000.0 # RoPE base frequency
|
| 21 |
+
rms_norm_eps: float = 1e-6 # RMSNorm epsilon
|
| 22 |
+
tie_embeddings: bool = True # share input embedding and output head weights
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# a very small variant for fast offline code testing (tiny numbers)
|
| 26 |
+
def tiny_config() -> ARConfig:
|
| 27 |
+
return ARConfig(
|
| 28 |
+
vocab_size=1000, dim=128, n_layers=2,
|
| 29 |
+
n_heads=4, n_kv_heads=2, head_dim=32,
|
| 30 |
+
hidden_dim=512, max_seq_len=256,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# a ~0.5B variant for validating the training loop on a single GPU
|
| 35 |
+
# (same architecture shape as the full model, just narrower and shallower)
|
| 36 |
+
def small_config() -> ARConfig:
|
| 37 |
+
return ARConfig(
|
| 38 |
+
vocab_size=151936, dim=1024, n_layers=24,
|
| 39 |
+
n_heads=16, n_kv_heads=4, head_dim=128, # keeps the 4:1 GQA ratio
|
| 40 |
+
hidden_dim=2816, max_seq_len=40960,
|
| 41 |
+
)
|
ar/model/mask.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch.nn.attention.flex_attention import create_block_mask
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def build_doc_block_mask(segment_ids: torch.Tensor, seq_len: int, device):
|
| 6 |
+
"""Build the FlexAttention block mask for causal + same-document attention.
|
| 7 |
+
|
| 8 |
+
segment_ids: (B, T) int32 tensor from the dataset.
|
| 9 |
+
A query at position q attends to a key at position kv only when
|
| 10 |
+
kv <= q (causal) AND both positions belong to the same packed document.
|
| 11 |
+
"""
|
| 12 |
+
B = segment_ids.shape[0]
|
| 13 |
+
|
| 14 |
+
def doc_mask_mod(b, h, q_idx, kv_idx):
|
| 15 |
+
causal = q_idx >= kv_idx
|
| 16 |
+
same_doc = segment_ids[b, q_idx] == segment_ids[b, kv_idx]
|
| 17 |
+
return causal & same_doc
|
| 18 |
+
|
| 19 |
+
# H=None means one mask is shared across all heads
|
| 20 |
+
return create_block_mask(
|
| 21 |
+
doc_mask_mod, B=B, H=None, Q_LEN=seq_len, KV_LEN=seq_len, device=device
|
| 22 |
+
)
|
ar/model/mlp.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class SwiGLU(nn.Module):
|
| 7 |
+
"""Gated MLP: one path (with SiLU) gates another, then projects back down."""
|
| 8 |
+
|
| 9 |
+
def __init__(self, dim: int, hidden_dim: int):
|
| 10 |
+
super().__init__()
|
| 11 |
+
# gate and up both widen dim -> hidden_dim; down narrows back
|
| 12 |
+
self.gate_proj = nn.Linear(dim, hidden_dim, bias=False)
|
| 13 |
+
self.up_proj = nn.Linear(dim, hidden_dim, bias=False)
|
| 14 |
+
self.down_proj = nn.Linear(hidden_dim, dim, bias=False)
|
| 15 |
+
|
| 16 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 17 |
+
# SiLU(gate) acts as a soft, per-element valve on the up path
|
| 18 |
+
gated = F.silu(self.gate_proj(x)) * self.up_proj(x)
|
| 19 |
+
return self.down_proj(gated)
|
ar/model/model.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from .config import ARConfig
|
| 5 |
+
from .rmsnorm import RMSNorm
|
| 6 |
+
from .block import DecoderBlock
|
| 7 |
+
from .rope import build_rope_cache
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ARModel(nn.Module):
|
| 11 |
+
"""Decoder-only transformer: token IDs in, next-token scores out."""
|
| 12 |
+
|
| 13 |
+
def __init__(self, cfg: ARConfig):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.cfg = cfg
|
| 16 |
+
|
| 17 |
+
# token embedding: maps each token ID to a dim-wide vector
|
| 18 |
+
self.embed = nn.Embedding(cfg.vocab_size, cfg.dim)
|
| 19 |
+
|
| 20 |
+
# the stack of identical decoder blocks
|
| 21 |
+
self.blocks = nn.ModuleList([
|
| 22 |
+
DecoderBlock(cfg.dim, cfg.n_heads, cfg.n_kv_heads,
|
| 23 |
+
cfg.head_dim, cfg.hidden_dim, cfg.rms_norm_eps)
|
| 24 |
+
for _ in range(cfg.n_layers)
|
| 25 |
+
])
|
| 26 |
+
|
| 27 |
+
self.final_norm = RMSNorm(cfg.dim, cfg.rms_norm_eps)
|
| 28 |
+
# output head: dim-wide vector -> score for every token in the vocab
|
| 29 |
+
self.lm_head = nn.Linear(cfg.dim, cfg.vocab_size, bias=False)
|
| 30 |
+
|
| 31 |
+
# tie weights: embedding table and output head share one matrix
|
| 32 |
+
if cfg.tie_embeddings:
|
| 33 |
+
self.lm_head.weight = self.embed.weight
|
| 34 |
+
|
| 35 |
+
# precompute RoPE tables once; reused by every block (not a parameter)
|
| 36 |
+
cos, sin = build_rope_cache(cfg.head_dim, cfg.max_seq_len, cfg.rope_theta)
|
| 37 |
+
self.register_buffer("rope_cos", cos, persistent=False)
|
| 38 |
+
self.register_buffer("rope_sin", sin, persistent=False)
|
| 39 |
+
|
| 40 |
+
# initialize all weights small; without this, 24 stacked layers make
|
| 41 |
+
# the output logits explode (std ~32 instead of ~1)
|
| 42 |
+
self.apply(self._init_weights)
|
| 43 |
+
# extra: scale down the two residual-path projections per block by
|
| 44 |
+
# 1/sqrt(2*n_layers) so the signal doesn't compound across depth
|
| 45 |
+
scale = (2 * cfg.n_layers) ** -0.5
|
| 46 |
+
for block in self.blocks:
|
| 47 |
+
torch.nn.init.normal_(block.attn.o_proj.weight, mean=0.0, std=0.02 * scale)
|
| 48 |
+
torch.nn.init.normal_(block.mlp.down_proj.weight, mean=0.0, std=0.02 * scale)
|
| 49 |
+
|
| 50 |
+
def _init_weights(self, module):
|
| 51 |
+
# small normal init for all linear and embedding weights
|
| 52 |
+
if isinstance(module, nn.Linear):
|
| 53 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 54 |
+
if module.bias is not None:
|
| 55 |
+
torch.nn.init.zeros_(module.bias)
|
| 56 |
+
elif isinstance(module, nn.Embedding):
|
| 57 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 58 |
+
|
| 59 |
+
def forward(self, token_ids: torch.Tensor, block_mask) -> torch.Tensor:
|
| 60 |
+
B, T = token_ids.shape
|
| 61 |
+
|
| 62 |
+
# look up embeddings, then slice the RoPE tables to this sequence length
|
| 63 |
+
x = self.embed(token_ids)
|
| 64 |
+
cos, sin = self.rope_cos[:T], self.rope_sin[:T]
|
| 65 |
+
|
| 66 |
+
# pass through every decoder block in turn
|
| 67 |
+
for block in self.blocks:
|
| 68 |
+
x = block(x, cos, sin, block_mask)
|
| 69 |
+
|
| 70 |
+
# final clean-up, then project to vocab-sized scores (logits)
|
| 71 |
+
x = self.final_norm(x)
|
| 72 |
+
return self.lm_head(x)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# def forward(self, token_ids: torch.Tensor) -> torch.Tensor:
|
| 77 |
+
# B, T = token_ids.shape
|
| 78 |
+
|
| 79 |
+
# # look up embeddings, then slice the RoPE tables to this sequence length
|
| 80 |
+
# x = self.embed(token_ids)
|
| 81 |
+
# cos, sin = self.rope_cos[:T], self.rope_sin[:T]
|
| 82 |
+
|
| 83 |
+
# # pass through every decoder block in turn
|
| 84 |
+
# for block in self.blocks:
|
| 85 |
+
# x = block(x, cos, sin)
|
| 86 |
+
|
| 87 |
+
# # final clean-up, then project to vocab-sized scores (logits)
|
| 88 |
+
# x = self.final_norm(x)
|
| 89 |
+
# return self.lm_head(x)
|
ar/model/rmsnorm.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class RMSNorm(nn.Module):
|
| 6 |
+
"""Root Mean Square normalization .
|
| 7 |
+
|
| 8 |
+
Rescales each token vector to a stable magnitude, then applies a
|
| 9 |
+
learned per-dimension gain. Cheaper than LayerNorm: no mean-centering.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 13 |
+
super().__init__()
|
| 14 |
+
# eps: tiny constant so we never divide by zero
|
| 15 |
+
self.eps = eps
|
| 16 |
+
# learned scale, one value per dimension; starts at 1 (no-op)
|
| 17 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 18 |
+
|
| 19 |
+
def _norm(self, x: torch.Tensor) -> torch.Tensor:
|
| 20 |
+
# rms = sqrt(mean(x^2)) computed over the last dim (the feature dim)
|
| 21 |
+
# x * 1/rms -> rescales the vector to unit root-mean-square
|
| 22 |
+
rms = torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
|
| 23 |
+
return x * rms
|
| 24 |
+
|
| 25 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 26 |
+
# normalize in float32 for numerical stability, then cast back
|
| 27 |
+
# (input is bf16 during training; squaring bf16 loses precision)
|
| 28 |
+
out = self._norm(x.float()).type_as(x)
|
| 29 |
+
# apply the learned per-dimension gain
|
| 30 |
+
return out * self.weight
|
ar/model/rope.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def build_rope_cache(head_dim: int, max_seq_len: int, theta: float = 1_000_000.0):
|
| 6 |
+
"""Precompute the cos/sin rotation tables used by RoPE.
|
| 7 |
+
|
| 8 |
+
Returns two tensors of shape (max_seq_len, head_dim), ready to index by position.
|
| 9 |
+
"""
|
| 10 |
+
# each of the head_dim/2 pairs gets its own rotation speed (fast -> slow)
|
| 11 |
+
idx = torch.arange(0, head_dim, 2, dtype=torch.float32)
|
| 12 |
+
inv_freq = 1.0 / (theta ** (idx / head_dim))
|
| 13 |
+
|
| 14 |
+
# outer product: rotation angle for every (position, pair) combination
|
| 15 |
+
pos = torch.arange(max_seq_len, dtype=torch.float32)
|
| 16 |
+
angles = torch.outer(pos, inv_freq) # (max_seq_len, head_dim/2)
|
| 17 |
+
|
| 18 |
+
# duplicate each angle so it lines up with both halves of the vector
|
| 19 |
+
angles = torch.cat([angles, angles], dim=-1) # (max_seq_len, head_dim)
|
| 20 |
+
return angles.cos(), angles.sin()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 24 |
+
# turns [x1, x2] into [-x2, x1] — the 90-degree partner needed for rotation
|
| 25 |
+
half = x.shape[-1] // 2
|
| 26 |
+
x1, x2 = x[..., :half], x[..., half:]
|
| 27 |
+
return torch.cat([-x2, x1], dim=-1)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
| 31 |
+
"""Rotate query or key vectors by their positions.
|
| 32 |
+
|
| 33 |
+
x: (batch, heads, seq_len, head_dim); cos/sin: (seq_len, head_dim).
|
| 34 |
+
"""
|
| 35 |
+
# broadcast cos/sin over batch and head dims
|
| 36 |
+
cos = cos[None, None, :, :]
|
| 37 |
+
sin = sin[None, None, :, :]
|
| 38 |
+
# the rotation identity: x*cos + rotate_half(x)*sin
|
| 39 |
+
return x * cos + _rotate_half(x) * sin
|
ar/train/__init__.py
ADDED
|
File without changes
|
ar/train/stage2.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage 2 settings, learning-rate schedule and checkpoint protection.
|
| 2 |
+
|
| 3 |
+
Pure Python (no torch), so every rule here can be unit-tested on a laptop.
|
| 4 |
+
Stage 2 is switched on only by environment variables (exported from run_args.sh);
|
| 5 |
+
when STAGE2_START is not set, everything behaves exactly like Stage 1.
|
| 6 |
+
"""
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
|
| 11 |
+
# end-of-text id of our tokenizer: the data files separate documents with it
|
| 12 |
+
EOT_ID = 151645
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclass
|
| 16 |
+
class Stage2Settings:
|
| 17 |
+
start: int # first Stage 2 step (Stage 1's last step is start - 1)
|
| 18 |
+
warmup: int # steps to climb from Stage 1's final LR to `peak`
|
| 19 |
+
peak: float
|
| 20 |
+
min_lr: float
|
| 21 |
+
bins: list # Stage 2 data files
|
| 22 |
+
weights: list # their mix weights (same order)
|
| 23 |
+
|
| 24 |
+
@staticmethod
|
| 25 |
+
def from_env():
|
| 26 |
+
"""Read Stage 2 settings from the environment; None means 'no Stage 2'."""
|
| 27 |
+
if not os.environ.get("STAGE2_START"):
|
| 28 |
+
return None
|
| 29 |
+
bins = os.environ["S2_BIN"].split()
|
| 30 |
+
weights = [float(w) for w in os.environ["S2_WEIGHTS"].split()]
|
| 31 |
+
assert len(bins) == len(weights) > 0, "S2_BIN and S2_WEIGHTS must have the same length"
|
| 32 |
+
assert all(w >= 0 for w in weights) and sum(weights) > 0, "bad S2_WEIGHTS"
|
| 33 |
+
s = Stage2Settings(
|
| 34 |
+
start=int(os.environ["STAGE2_START"]),
|
| 35 |
+
warmup=int(os.environ.get("STAGE2_WARMUP", "1000")),
|
| 36 |
+
peak=float(os.environ.get("STAGE2_PEAK", "1e-4")),
|
| 37 |
+
min_lr=float(os.environ.get("STAGE2_MIN", "1e-5")),
|
| 38 |
+
bins=bins,
|
| 39 |
+
weights=weights,
|
| 40 |
+
)
|
| 41 |
+
assert s.start > 0 and s.warmup > 0 and s.peak > s.min_lr > 0, "bad Stage 2 settings"
|
| 42 |
+
return s
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def stage1_lr(step, cfg):
|
| 46 |
+
"""Stage 1 schedule, unchanged: linear warmup, then cosine to min_lr at lr_horizon."""
|
| 47 |
+
if step < cfg.warmup_steps:
|
| 48 |
+
return cfg.peak_lr * (step + 1) / cfg.warmup_steps
|
| 49 |
+
horizon = getattr(cfg, "lr_horizon", cfg.max_steps)
|
| 50 |
+
progress = min(1.0, (step - cfg.warmup_steps) / max(1, horizon - cfg.warmup_steps))
|
| 51 |
+
return cfg.min_lr + 0.5 * (1 + math.cos(math.pi * progress)) * (cfg.peak_lr - cfg.min_lr)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def lr_at(step, cfg, s2=None):
|
| 55 |
+
"""Stage 1 schedule before s2.start; after it: warm up from Stage 1's final LR
|
| 56 |
+
to s2.peak, then cosine down to s2.min_lr at the last step (cfg.max_steps)."""
|
| 57 |
+
if s2 is None or step < s2.start:
|
| 58 |
+
return stage1_lr(step, cfg)
|
| 59 |
+
t = step - s2.start
|
| 60 |
+
base = stage1_lr(s2.start - 1, cfg) # where Stage 1 ended
|
| 61 |
+
if t < s2.warmup:
|
| 62 |
+
return base + (s2.peak - base) * (t + 1) / s2.warmup
|
| 63 |
+
span = max(1, cfg.max_steps - 1 - s2.start - s2.warmup)
|
| 64 |
+
progress = min(1.0, (t - s2.warmup) / span)
|
| 65 |
+
return s2.min_lr + 0.5 * (1 + math.cos(math.pi * progress)) * (s2.peak - s2.min_lr)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def protected_ckpts():
|
| 69 |
+
"""Checkpoint folder names that rotation must never delete (env PROTECT_CKPTS)."""
|
| 70 |
+
return set(os.environ.get("PROTECT_CKPTS", "").split())
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def ckpts_to_delete(entries, is_complete, keep, protect):
|
| 74 |
+
"""Which ckpt_<step> folders rotation removes: all half-written ones, plus complete
|
| 75 |
+
ones older than the newest `keep`. Protected names are never removed or counted."""
|
| 76 |
+
entries = [d for d in entries if d.startswith("ckpt_") and d not in protect]
|
| 77 |
+
good = sorted((d for d in entries if is_complete(d)), key=lambda d: int(d.split("_")[1]))
|
| 78 |
+
bad = [d for d in entries if not is_complete(d)]
|
| 79 |
+
return (good[:-keep] if keep > 0 else good) + bad
|
ar/train/train.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
import argparse
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
|
| 9 |
+
from ar.model.config import ARConfig, small_config, tiny_config
|
| 10 |
+
from ar.model.model import ARModel
|
| 11 |
+
from ar.data.dataset import BinDataset
|
| 12 |
+
from ar.train.train_config import TrainConfig
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def lr_at(step: int, cfg: TrainConfig) -> float:
|
| 16 |
+
"""Warmup then cosine decay: ramp up linearly, then ease down to min_lr."""
|
| 17 |
+
if step < cfg.warmup_steps:
|
| 18 |
+
return cfg.peak_lr * (step + 1) / cfg.warmup_steps
|
| 19 |
+
# cosine decay from peak_lr to min_lr over the remaining steps
|
| 20 |
+
progress = (step - cfg.warmup_steps) / max(1, cfg.max_steps - cfg.warmup_steps)
|
| 21 |
+
progress = min(1.0, progress)
|
| 22 |
+
coeff = 0.5 * (1.0 + math.cos(math.pi * progress))
|
| 23 |
+
return cfg.min_lr + coeff * (cfg.peak_lr - cfg.min_lr)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def train(bin_paths, weights, tcfg: TrainConfig, mcfg: ARConfig, device="cuda"):
|
| 27 |
+
torch.manual_seed(0)
|
| 28 |
+
model = ARModel(mcfg).to(device)
|
| 29 |
+
model.train()
|
| 30 |
+
|
| 31 |
+
data = BinDataset(bin_paths, tcfg.seq_len, weights)
|
| 32 |
+
|
| 33 |
+
# AdamW with the LLM-pretraining betas; fused=True is a faster CUDA path
|
| 34 |
+
opt = torch.optim.AdamW(
|
| 35 |
+
model.parameters(), lr=tcfg.peak_lr,
|
| 36 |
+
betas=tcfg.betas, weight_decay=tcfg.weight_decay, fused=True,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
os.makedirs(tcfg.ckpt_dir, exist_ok=True)
|
| 40 |
+
t0 = time.time()
|
| 41 |
+
|
| 42 |
+
for step in range(tcfg.max_steps):
|
| 43 |
+
# set this step's learning rate on the optimizer
|
| 44 |
+
lr = lr_at(step, tcfg)
|
| 45 |
+
for g in opt.param_groups:
|
| 46 |
+
g["lr"] = lr
|
| 47 |
+
|
| 48 |
+
x, y = data.get_batch(tcfg.batch_size, device)
|
| 49 |
+
|
| 50 |
+
# forward: logits are (B, T, vocab); cross-entropy wants (B*T, vocab)
|
| 51 |
+
logits = model(x)
|
| 52 |
+
loss = F.cross_entropy(
|
| 53 |
+
logits.view(-1, logits.size(-1)), y.view(-1)
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# backward: clear old grads, compute new ones, clip, then step
|
| 57 |
+
opt.zero_grad(set_to_none=True)
|
| 58 |
+
loss.backward()
|
| 59 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), tcfg.grad_clip)
|
| 60 |
+
opt.step()
|
| 61 |
+
|
| 62 |
+
if step % tcfg.log_every == 0:
|
| 63 |
+
dt = time.time() - t0
|
| 64 |
+
toks = (step + 1) * tcfg.batch_size * tcfg.seq_len
|
| 65 |
+
print(f"step {step:6d} | loss {loss.item():.4f} | lr {lr:.2e} "
|
| 66 |
+
f"| {toks/dt/1e3:.1f}k tok/s")
|
| 67 |
+
|
| 68 |
+
if step > 0 and step % tcfg.ckpt_every == 0:
|
| 69 |
+
path = os.path.join(tcfg.ckpt_dir, f"ar_step{step}.pt")
|
| 70 |
+
torch.save({"model": model.state_dict(), "step": step}, path)
|
| 71 |
+
print(f" saved {path}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if __name__ == "__main__":
|
| 75 |
+
p = argparse.ArgumentParser()
|
| 76 |
+
p.add_argument("--bin", nargs="+", required=True, help="one or more .bin paths")
|
| 77 |
+
p.add_argument("--weights", nargs="+", type=float, default=None)
|
| 78 |
+
p.add_argument("--max_steps", type=int, default=100)
|
| 79 |
+
p.add_argument("--batch_size", type=int, default=4)
|
| 80 |
+
p.add_argument("--seq_len", type=int, default=4096)
|
| 81 |
+
p.add_argument("--warmup_steps", type=int, default=2000)
|
| 82 |
+
p.add_argument("--model_size", choices=["small", "full", "tiny"], default="small")
|
| 83 |
+
args = p.parse_args()
|
| 84 |
+
|
| 85 |
+
tcfg = TrainConfig(max_steps=args.max_steps, batch_size=args.batch_size,
|
| 86 |
+
seq_len=args.seq_len, warmup_steps=args.warmup_steps)
|
| 87 |
+
mcfg = {"small": small_config, "full": ARConfig, "tiny": tiny_config}[args.model_size]()
|
| 88 |
+
train(args.bin, args.weights, tcfg, mcfg)
|
ar/train/train_config.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@dataclass
|
| 5 |
+
class TrainConfig:
|
| 6 |
+
"""Training hyperparameters (Qwen-style defaults for a ~4B model)."""
|
| 7 |
+
|
| 8 |
+
# data
|
| 9 |
+
seq_len: int = 4096
|
| 10 |
+
batch_size: int = 4 # sequences per step on one GPU (tune to fit memory)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# optimizer (AdamW)
|
| 14 |
+
peak_lr: float = 4e-4
|
| 15 |
+
min_lr: float = 4e-5
|
| 16 |
+
betas: tuple = (0.9, 0.95)
|
| 17 |
+
weight_decay: float = 0.1
|
| 18 |
+
grad_clip: float = 1.0
|
| 19 |
+
grad_accum: int = 1
|
| 20 |
+
|
| 21 |
+
# learning-rate schedule
|
| 22 |
+
warmup_steps: int = 2000
|
| 23 |
+
max_steps: int = 190_000
|
| 24 |
+
# # optimizer (AdamW)
|
| 25 |
+
# peak_lr: float = 3e-4
|
| 26 |
+
# min_lr: float = 3e-5
|
| 27 |
+
# betas: tuple = (0.9, 0.95) # 0.95 is the LLM-pretraining convention
|
| 28 |
+
# weight_decay: float = 0.1
|
| 29 |
+
# grad_clip: float = 1.0
|
| 30 |
+
|
| 31 |
+
# # learning-rate schedule
|
| 32 |
+
# warmup_steps: int = 2000
|
| 33 |
+
# max_steps: int = 100_000 # total training steps (set per run)
|
| 34 |
+
|
| 35 |
+
# logging / checkpointing
|
| 36 |
+
log_every: int = 10
|
| 37 |
+
ckpt_every: int = 2000
|
| 38 |
+
ckpt_dir: str = "/fsx/ajay-stu/ar-data/checkpoints"
|
| 39 |
+
lr_horizon: int = 186_000 # LR schedule spans this many steps
|
ar/train/train_fsdp.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Multi-GPU training with FSDP2, with weight checkpointing + resume.
|
| 2 |
+
|
| 3 |
+
Stage 2 is switched on by environment variables (see ar/train/stage2.py). Until step
|
| 4 |
+
STAGE2_START everything runs exactly as Stage 1; from that step on, training uses the
|
| 5 |
+
read-once loader on the Stage 2 files (with document masking), the Stage 2 LR schedule
|
| 6 |
+
and no weight decay on 1-D (normalization) weights. No restart is needed at the switch.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import shutil
|
| 11 |
+
import time
|
| 12 |
+
import argparse
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
import torch.distributed as dist
|
| 17 |
+
import torch.distributed.checkpoint as dcp
|
| 18 |
+
from torch.distributed.checkpoint.state_dict import get_state_dict, set_state_dict
|
| 19 |
+
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
|
| 20 |
+
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
|
| 21 |
+
checkpoint_wrapper,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
from ar.model.config import ARConfig, small_config, tiny_config
|
| 25 |
+
from ar.model.model import ARModel
|
| 26 |
+
from ar.model.mask import build_doc_block_mask
|
| 27 |
+
from ar.data.dataset import BinDataset
|
| 28 |
+
from ar.data.readonce import ReadOnceDataset
|
| 29 |
+
from ar.train.train_config import TrainConfig
|
| 30 |
+
from ar.train.stage2 import (
|
| 31 |
+
Stage2Settings, lr_at, protected_ckpts, ckpts_to_delete, EOT_ID,
|
| 32 |
+
)
|
| 33 |
+
from ar.model.rmsnorm import RMSNorm
|
| 34 |
+
from ar.model.rope import build_rope_cache
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def setup():
|
| 38 |
+
dist.init_process_group(backend="nccl")
|
| 39 |
+
rank = dist.get_rank()
|
| 40 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 41 |
+
torch.cuda.set_device(local_rank)
|
| 42 |
+
return rank, local_rank, dist.get_world_size()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _complete(ckpt_dir, d):
|
| 46 |
+
# a checkpoint writes .metadata last, so its presence means the save finished
|
| 47 |
+
return os.path.isfile(os.path.join(ckpt_dir, d, ".metadata"))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def find_latest_ckpt(ckpt_dir):
|
| 51 |
+
"""Return path to the newest COMPLETE ckpt_<step> folder, or None."""
|
| 52 |
+
if not os.path.isdir(ckpt_dir):
|
| 53 |
+
return None
|
| 54 |
+
entries = [d for d in os.listdir(ckpt_dir)
|
| 55 |
+
if d.startswith("ckpt_") and _complete(ckpt_dir, d)]
|
| 56 |
+
if not entries:
|
| 57 |
+
return None
|
| 58 |
+
entries.sort(key=lambda d: int(d.split("_")[1]))
|
| 59 |
+
return os.path.join(ckpt_dir, entries[-1])
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def rotate_ckpts(ckpt_dir, keep=2, is_main=False):
|
| 63 |
+
"""Keep the newest `keep` complete checkpoints; delete older ones and any half-written
|
| 64 |
+
leftovers. Folders named in PROTECT_CKPTS (e.g. the final Stage 1 one) are never touched."""
|
| 65 |
+
if not is_main or not os.path.isdir(ckpt_dir):
|
| 66 |
+
return
|
| 67 |
+
doomed = ckpts_to_delete(os.listdir(ckpt_dir), lambda d: _complete(ckpt_dir, d),
|
| 68 |
+
keep, protected_ckpts())
|
| 69 |
+
for old in doomed:
|
| 70 |
+
shutil.rmtree(os.path.join(ckpt_dir, old), ignore_errors=True)
|
| 71 |
+
print(f"[ckpt] removed {old}", flush=True)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def enough_disk(ckpt_dir, need_gb, device):
|
| 75 |
+
"""True if there's room for a checkpoint. Rank 0 decides and tells everyone,
|
| 76 |
+
so either all GPUs save or none do (a split decision would hang training)."""
|
| 77 |
+
ok = torch.tensor([int(shutil.disk_usage(ckpt_dir).free > need_gb * 1e9)], device=device)
|
| 78 |
+
dist.broadcast(ok, src=0)
|
| 79 |
+
return bool(ok.item())
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# a test run can point this elsewhere, so it never reacts to the real run's flag
|
| 83 |
+
RELOAD_FLAG = os.environ.get("RELOAD_FLAG", "/fsx/ajay-stu/AR/logs/RELOAD")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def reload_requested(device):
|
| 87 |
+
"""Rank 0 checks for the reload flag and tells everyone, so all GPUs agree."""
|
| 88 |
+
flag = torch.tensor([int(os.path.exists(RELOAD_FLAG))], device=device)
|
| 89 |
+
dist.broadcast(flag, src=0)
|
| 90 |
+
return bool(flag.item())
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def save_ckpt(model, opt, step, ckpt_dir, is_main):
|
| 94 |
+
"""Save FSDP-sharded model + optimizer + step atomically across all ranks."""
|
| 95 |
+
path = os.path.join(ckpt_dir, f"ckpt_{step}")
|
| 96 |
+
# each rank writes its shards; DCP handles coordination
|
| 97 |
+
model_sd, opt_sd = get_state_dict(model, opt)
|
| 98 |
+
state = {"model": model_sd, "opt": opt_sd, "step": step}
|
| 99 |
+
dcp.save(state_dict=state, checkpoint_id=path)
|
| 100 |
+
dist.barrier()
|
| 101 |
+
if is_main:
|
| 102 |
+
print(f"[ckpt] saved step {step} -> {path}", flush=True)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def load_ckpt(model, opt, ckpt_path, is_main):
|
| 106 |
+
"""Load a DCP checkpoint into the FSDP model/optimizer. Returns start_step."""
|
| 107 |
+
model_sd, opt_sd = get_state_dict(model, opt)
|
| 108 |
+
state = {"model": model_sd, "opt": opt_sd, "step": 0}
|
| 109 |
+
dcp.load(state_dict=state, checkpoint_id=ckpt_path)
|
| 110 |
+
set_state_dict(model, opt, model_state_dict=state["model"],
|
| 111 |
+
optim_state_dict=state["opt"])
|
| 112 |
+
start_step = int(state["step"])
|
| 113 |
+
if is_main:
|
| 114 |
+
print(f"[ckpt] resumed from {ckpt_path} at step {start_step}", flush=True)
|
| 115 |
+
return start_step
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@torch.no_grad()
|
| 119 |
+
def init_weights(model, mcfg, device):
|
| 120 |
+
"""Re-fill every weight AND buffer after to_empty() (its memory is blank)."""
|
| 121 |
+
resid_std = 0.02 * (2 * mcfg.n_layers) ** -0.5
|
| 122 |
+
for name, m in model.named_modules():
|
| 123 |
+
if isinstance(m, torch.nn.Linear):
|
| 124 |
+
# residual-path outputs start smaller so the signal doesn't grow with depth
|
| 125 |
+
std = resid_std if name.endswith(("o_proj", "down_proj")) else 0.02
|
| 126 |
+
torch.nn.init.normal_(m.weight, mean=0.0, std=std)
|
| 127 |
+
elif isinstance(m, torch.nn.Embedding):
|
| 128 |
+
torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
|
| 129 |
+
elif isinstance(m, RMSNorm):
|
| 130 |
+
for p in m.parameters():
|
| 131 |
+
torch.nn.init.ones_(p) # norms must start at 1
|
| 132 |
+
# RoPE tables are buffers, not weights, so recompute them for real
|
| 133 |
+
cos, sin = build_rope_cache(mcfg.head_dim, mcfg.max_seq_len, mcfg.rope_theta)
|
| 134 |
+
model.rope_cos.copy_(cos.to(device))
|
| 135 |
+
model.rope_sin.copy_(sin.to(device))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def train(bin_paths, weights, tcfg, mcfg):
|
| 139 |
+
rank, local_rank, world = setup()
|
| 140 |
+
is_main = rank == 0
|
| 141 |
+
device = torch.device("cuda", local_rank)
|
| 142 |
+
s2 = Stage2Settings.from_env() # None = plain Stage 1, exactly as before
|
| 143 |
+
if is_main and s2 is not None:
|
| 144 |
+
print(f"[stage2] switch at step {s2.start}: {len(s2.bins)} files, LR "
|
| 145 |
+
f"{s2.peak:g} -> {s2.min_lr:g} until step {tcfg.max_steps}", flush=True)
|
| 146 |
+
|
| 147 |
+
mp_policy = MixedPrecisionPolicy(
|
| 148 |
+
param_dtype=torch.bfloat16,
|
| 149 |
+
reduce_dtype=torch.float32,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
with torch.device("meta"):
|
| 153 |
+
model = ARModel(mcfg)
|
| 154 |
+
|
| 155 |
+
for i, block in enumerate(model.blocks):
|
| 156 |
+
model.blocks[i] = checkpoint_wrapper(block)
|
| 157 |
+
|
| 158 |
+
for block in model.blocks:
|
| 159 |
+
fully_shard(block, mp_policy=mp_policy)
|
| 160 |
+
fully_shard(model, mp_policy=mp_policy)
|
| 161 |
+
model.to_empty(device=device)
|
| 162 |
+
model.train()
|
| 163 |
+
|
| 164 |
+
# re-fill all weights and buffers (to_empty leaves memory blank)
|
| 165 |
+
init_weights(model, mcfg, device)
|
| 166 |
+
|
| 167 |
+
opt = torch.optim.AdamW(model.parameters(), lr=tcfg.peak_lr,
|
| 168 |
+
betas=tcfg.betas, weight_decay=tcfg.weight_decay)
|
| 169 |
+
# Stage 2 decays only matrices (embeddings, linears); 1-D norm gains are left alone
|
| 170 |
+
decay_params = [p for p in model.parameters() if p.ndim >= 2]
|
| 171 |
+
|
| 172 |
+
# resume from latest checkpoint if one exists
|
| 173 |
+
os.makedirs(tcfg.ckpt_dir, exist_ok=True)
|
| 174 |
+
start_step = 0
|
| 175 |
+
latest = find_latest_ckpt(tcfg.ckpt_dir)
|
| 176 |
+
if latest is not None:
|
| 177 |
+
start_step = load_ckpt(model, opt, latest, is_main) + 1
|
| 178 |
+
|
| 179 |
+
data1 = data2 = None # loaders are built when first needed
|
| 180 |
+
t0 = time.time()
|
| 181 |
+
|
| 182 |
+
for step in range(start_step, tcfg.max_steps):
|
| 183 |
+
in_s2 = s2 is not None and step >= s2.start
|
| 184 |
+
if in_s2 and data2 is None:
|
| 185 |
+
data2 = ReadOnceDataset(s2.bins, tcfg.seq_len, s2.weights,
|
| 186 |
+
s2.start, tcfg.max_steps, EOT_ID)
|
| 187 |
+
if is_main:
|
| 188 |
+
print(f"[stage2] read-once loader ready at step {step}", flush=True)
|
| 189 |
+
if not in_s2 and data1 is None:
|
| 190 |
+
data1 = BinDataset(bin_paths, tcfg.seq_len, weights) # Stage 1 loader, unchanged
|
| 191 |
+
|
| 192 |
+
lr = lr_at(step, tcfg, s2)
|
| 193 |
+
for g in opt.param_groups:
|
| 194 |
+
g["lr"] = lr
|
| 195 |
+
if in_s2:
|
| 196 |
+
g["weight_decay"] = 0.0 # Stage 2: decay is applied by hand below
|
| 197 |
+
|
| 198 |
+
# gradient accumulation: several micro-batches add up their gradients
|
| 199 |
+
# before one weight update, so fewer GPUs can reproduce the same step
|
| 200 |
+
opt.zero_grad(set_to_none=True)
|
| 201 |
+
loss_sum = 0.0
|
| 202 |
+
for micro in range(tcfg.grad_accum):
|
| 203 |
+
if in_s2:
|
| 204 |
+
x, y, segment_ids = data2.get_batch(step, micro, tcfg.batch_size, rank, world, device)
|
| 205 |
+
else:
|
| 206 |
+
x, y, segment_ids = data1.get_batch(tcfg.batch_size, device)
|
| 207 |
+
block_mask = build_doc_block_mask(segment_ids, tcfg.seq_len, device=device)
|
| 208 |
+
logits = model(x, block_mask)
|
| 209 |
+
# loss in fp32: bf16 scores over a 151,936-token vocab are too coarse
|
| 210 |
+
loss = F.cross_entropy(logits.float().view(-1, logits.size(-1)), y.view(-1))
|
| 211 |
+
# divide so the summed gradient equals the average over all micro-batches
|
| 212 |
+
(loss / tcfg.grad_accum).backward()
|
| 213 |
+
loss_sum += loss.item() / tcfg.grad_accum
|
| 214 |
+
|
| 215 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), tcfg.grad_clip)
|
| 216 |
+
if in_s2 and tcfg.weight_decay > 0:
|
| 217 |
+
# same decoupled decay AdamW would apply, but on matrices only
|
| 218 |
+
with torch.no_grad():
|
| 219 |
+
for p in decay_params:
|
| 220 |
+
p.mul_(1.0 - lr * tcfg.weight_decay)
|
| 221 |
+
opt.step()
|
| 222 |
+
|
| 223 |
+
if step % tcfg.log_every == 0:
|
| 224 |
+
# every rank joins: average loss over all GPUs, and the full gradient norm
|
| 225 |
+
avg = torch.tensor([loss_sum], device=device)
|
| 226 |
+
dist.all_reduce(avg)
|
| 227 |
+
gn = grad_norm.full_tensor() if hasattr(grad_norm, "full_tensor") else grad_norm
|
| 228 |
+
if is_main:
|
| 229 |
+
dt = time.time() - t0
|
| 230 |
+
toks = ((step - start_step + 1) * tcfg.batch_size * tcfg.seq_len
|
| 231 |
+
* world * tcfg.grad_accum)
|
| 232 |
+
print(f"step {step:6d} | loss {avg.item() / world:.4f} | lr {lr:.2e} "
|
| 233 |
+
f"| {toks/dt/1e3:.1f}k tok/s (all GPUs) | gnorm {gn.item():.3f}", flush=True)
|
| 234 |
+
|
| 235 |
+
# save checkpoint every ckpt_every steps (and at the very end)
|
| 236 |
+
if (step + 1) % tcfg.ckpt_every == 0 or step == tcfg.max_steps - 1:
|
| 237 |
+
if enough_disk(tcfg.ckpt_dir, 150, device):
|
| 238 |
+
save_ckpt(model, opt, step, tcfg.ckpt_dir, is_main)
|
| 239 |
+
rotate_ckpts(tcfg.ckpt_dir, is_main=is_main, # keep 1 checkpoint when disk is tight
|
| 240 |
+
keep=(2 if shutil.disk_usage(tcfg.ckpt_dir).free > 400e9 else 1))
|
| 241 |
+
# hot reload: stop right after a save when asked, so no work is lost
|
| 242 |
+
if reload_requested(device):
|
| 243 |
+
if is_main:
|
| 244 |
+
print(f"[reload] stopping after step {step} to apply new settings", flush=True)
|
| 245 |
+
break
|
| 246 |
+
elif is_main:
|
| 247 |
+
print(f"[ckpt] WARNING: disk nearly full, skipped save at step {step}", flush=True)
|
| 248 |
+
dist.destroy_process_group()
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
if __name__ == "__main__":
|
| 252 |
+
p = argparse.ArgumentParser()
|
| 253 |
+
p.add_argument("--bin", nargs="+", required=True)
|
| 254 |
+
p.add_argument("--weights", nargs="+", type=float, default=None)
|
| 255 |
+
p.add_argument("--max_steps", type=int, default=100)
|
| 256 |
+
p.add_argument("--batch_size", type=int, default=1)
|
| 257 |
+
p.add_argument("--seq_len", type=int, default=2048)
|
| 258 |
+
p.add_argument("--warmup_steps", type=int, default=20)
|
| 259 |
+
p.add_argument("--peak_lr", type=float, default=None)
|
| 260 |
+
p.add_argument("--ckpt_every", type=int, default=None)
|
| 261 |
+
p.add_argument("--ckpt_dir", type=str, default=None)
|
| 262 |
+
p.add_argument("--model_size", choices=["small", "full", "tiny"], default="full")
|
| 263 |
+
p.add_argument("--grad_accum", type=int, default=1)
|
| 264 |
+
p.add_argument("--lr_horizon", type=int, default=None)
|
| 265 |
+
p.add_argument("--log_every", type=int, default=None)
|
| 266 |
+
args = p.parse_args()
|
| 267 |
+
|
| 268 |
+
tcfg_kwargs = dict(max_steps=args.max_steps, batch_size=args.batch_size,
|
| 269 |
+
seq_len=args.seq_len, warmup_steps=args.warmup_steps)
|
| 270 |
+
tcfg_kwargs["grad_accum"] = args.grad_accum
|
| 271 |
+
if args.lr_horizon is not None:
|
| 272 |
+
tcfg_kwargs["lr_horizon"] = args.lr_horizon
|
| 273 |
+
if args.peak_lr is not None:
|
| 274 |
+
tcfg_kwargs["peak_lr"] = args.peak_lr
|
| 275 |
+
tcfg_kwargs["min_lr"] = args.peak_lr * 0.1
|
| 276 |
+
if args.ckpt_every is not None:
|
| 277 |
+
tcfg_kwargs["ckpt_every"] = args.ckpt_every
|
| 278 |
+
if args.ckpt_dir is not None:
|
| 279 |
+
tcfg_kwargs["ckpt_dir"] = args.ckpt_dir
|
| 280 |
+
if args.log_every is not None:
|
| 281 |
+
tcfg_kwargs["log_every"] = args.log_every
|
| 282 |
+
tcfg = TrainConfig(**tcfg_kwargs)
|
| 283 |
+
mcfg = {"small": small_config, "full": ARConfig, "tiny": tiny_config}[args.model_size]()
|
| 284 |
+
train(args.bin, args.weights, tcfg, mcfg)
|
autoreload.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# While a memory leak is suspected: ask training to restart (after a checkpoint, same nodes)
|
| 3 |
+
# every 6 hours, which frees the memory the training programs have built up.
|
| 4 |
+
# Start: nohup ./autoreload.sh >> logs/autoreload.log 2>&1 & Stop: pkill -f autoreload.sh
|
| 5 |
+
cd /fsx/ajay-stu/AR
|
| 6 |
+
while true; do
|
| 7 |
+
sleep $((6 * 3600))
|
| 8 |
+
touch logs/RELOAD && echo "$(date -u) RELOAD requested (memory reset)"
|
| 9 |
+
done
|
cleanup.sh
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Frees disk space after pretraining. Shows what it would remove; deletes only with --go.
|
| 3 |
+
# NEVER touches: the two final models (stage1_final, stage2_final), the token data (bin/, stage2/),
|
| 4 |
+
# the held-out sets, the code, or anything outside /fsx/ajay-stu/ar-data.
|
| 5 |
+
# Usage: ./cleanup.sh (dry run, shows sizes)
|
| 6 |
+
# ./cleanup.sh --go (actually delete)
|
| 7 |
+
set -uo pipefail
|
| 8 |
+
D=${D:-/fsx/ajay-stu/ar-data}
|
| 9 |
+
GO=${1:-}
|
| 10 |
+
KEEP1=ckpt_571999 # final Stage 1 (also kept in stage1_final)
|
| 11 |
+
KEEP2=ckpt_619699 # final Stage 2 (also kept in stage2_final)
|
| 12 |
+
|
| 13 |
+
# refuse to delete while training is running
|
| 14 |
+
if squeue -u "${USER:-$(id -un)}" -h -n ar-real 2>/dev/null | grep -q .; then
|
| 15 |
+
echo "STOP: a training job is still running"; exit 1
|
| 16 |
+
fi
|
| 17 |
+
|
| 18 |
+
# build the list: training checkpoints except the two finals, and eval exports
|
| 19 |
+
targets=()
|
| 20 |
+
for p in "$D"/checkpoints/ckpt_*; do
|
| 21 |
+
b=$(basename "$p")
|
| 22 |
+
[ -d "$p" ] && [ "$b" != "$KEEP1" ] && [ "$b" != "$KEEP2" ] && targets+=("$p")
|
| 23 |
+
done
|
| 24 |
+
for p in "$D"/eval/*.pt; do [ -f "$p" ] && targets+=("$p"); done
|
| 25 |
+
|
| 26 |
+
if [ ${#targets[@]} -eq 0 ]; then
|
| 27 |
+
echo "nothing to clean"; df -h /fsx | tail -1; exit 0
|
| 28 |
+
fi
|
| 29 |
+
|
| 30 |
+
# show each item with its real disk use (hard-linked copies count as 0 here)
|
| 31 |
+
echo "would remove:"
|
| 32 |
+
du -shc --apparent-size "${targets[@]}" 2>/dev/null | tail -1 | sed 's/^/ apparent total: /'
|
| 33 |
+
for p in "${targets[@]}"; do printf " %-8s %s\n" "$(du -sh "$p" 2>/dev/null | cut -f1)" "$p"; done
|
| 34 |
+
echo "keeping: $D/stage1_final $D/stage2_final $D/bin $D/stage2 $D/heldout"
|
| 35 |
+
|
| 36 |
+
if [ "$GO" != "--go" ]; then
|
| 37 |
+
echo; echo "DRY RUN - nothing deleted. Run './cleanup.sh --go' to delete."; exit 0
|
| 38 |
+
fi
|
| 39 |
+
|
| 40 |
+
# safety: the two final models must exist before anything is removed
|
| 41 |
+
for f in "$D/stage1_final/model_stage1_final.pt" "$D/stage2_final/model_stage2_final.pt" \
|
| 42 |
+
"$D/stage1_final/$KEEP1/.metadata" "$D/stage2_final/$KEEP2/.metadata"; do
|
| 43 |
+
[ -e "$f" ] || { echo "STOP: $f is missing - nothing deleted"; exit 1; }
|
| 44 |
+
done
|
| 45 |
+
echo "final models verified"
|
| 46 |
+
for p in "${targets[@]}"; do rm -rf "$p" && echo "removed $p"; done
|
| 47 |
+
df -h /fsx | tail -1
|
dataeval.sbatch
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
#SBATCH --job-name=ar-dataval
|
| 3 |
+
#SBATCH --partition=dev
|
| 4 |
+
#SBATCH --nodes=1
|
| 5 |
+
#SBATCH --ntasks-per-node=1
|
| 6 |
+
#SBATCH --cpus-per-task=32
|
| 7 |
+
#SBATCH --output=dataval_%j.log
|
| 8 |
+
|
| 9 |
+
set -euo pipefail
|
| 10 |
+
|
| 11 |
+
cd /fsx/ajay-stu/AR
|
| 12 |
+
source .venv/bin/activate
|
| 13 |
+
|
| 14 |
+
OUT=/fsx/ajay-stu/ar-data/bin-val
|
| 15 |
+
|
| 16 |
+
echo "=== fineweb ==="
|
| 17 |
+
python -m ar.data.prepare_data --source fineweb --target_tokens 1000000000 --out_dir $OUT
|
| 18 |
+
echo "=== stack ==="
|
| 19 |
+
python -m ar.data.prepare_data --source stack --target_tokens 1000000000 --out_dir $OUT
|
| 20 |
+
echo "=== finemath ==="
|
| 21 |
+
python -m ar.data.prepare_data --source finemath --target_tokens 1000000000 --out_dir $OUT
|
| 22 |
+
|
| 23 |
+
echo "=== sizes ==="
|
| 24 |
+
ls -la $OUT
|
diskwatch.sh
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Logs free space on /fsx every 5 minutes; readings below LOW_GB are marked LOW.
|
| 3 |
+
# Start: nohup ./diskwatch.sh >> logs/disk.log 2>&1 & Stop: pkill -f diskwatch.sh
|
| 4 |
+
cd /fsx/ajay-stu/AR
|
| 5 |
+
LOW_GB=300
|
| 6 |
+
while true; do
|
| 7 |
+
free=$(df -BG --output=avail /fsx | tail -1 | tr -dc '0-9') # free space in GB
|
| 8 |
+
tag=""; [ "$free" -lt $LOW_GB ] && tag=" <-- LOW"
|
| 9 |
+
echo "$(date -u '+%m-%d %H:%M') UTC free=${free}G$tag"
|
| 10 |
+
sleep 300
|
| 11 |
+
done
|
eval_here.sh
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Run all evals on THIS node, on one GPU nobody is using (for an interactive session on a compute node).
|
| 3 |
+
# Usage: ./eval_here.sh [model.pt] (default: export the newest complete checkpoint first)
|
| 4 |
+
set -uo pipefail
|
| 5 |
+
cd /fsx/ajay-stu/AR
|
| 6 |
+
source .venv/bin/activate
|
| 7 |
+
export PYTHONPATH=$PWD HF_DATASETS_OFFLINE=1
|
| 8 |
+
H=$(hostname)
|
| 9 |
+
|
| 10 |
+
# 1) never on our own training nodes (their GPUs are fully used by training)
|
| 11 |
+
TRAIN=$(scontrol show hostnames $(squeue -u $USER -n ar-real -h -o %N | head -1) 2>/dev/null)
|
| 12 |
+
echo "$TRAIN" | grep -qx "$H" && { echo "STOP: $H is one of our training nodes"; exit 1; }
|
| 13 |
+
|
| 14 |
+
# 2) one free GPU (inside a Slurm session, use the GPU Slurm gave us)
|
| 15 |
+
if [ -z "${CUDA_VISIBLE_DEVICES:-}" ]; then
|
| 16 |
+
G=$(nvidia-smi --query-gpu=index,memory.used --format=csv,noheader,nounits | awk -F', ' '$2 < 2000 {print $1; exit}')
|
| 17 |
+
[ -z "$G" ] && { echo "no free GPU on $H"; exit 1; }
|
| 18 |
+
export CUDA_VISIBLE_DEVICES=$G
|
| 19 |
+
fi
|
| 20 |
+
used=$(nvidia-smi -i ${CUDA_VISIBLE_DEVICES%%,*} --query-gpu=memory.used --format=csv,noheader,nounits)
|
| 21 |
+
[ "$used" -ge 2000 ] && { echo "GPU $CUDA_VISIBLE_DEVICES already in use ($used MiB)"; exit 1; }
|
| 22 |
+
echo "=== on $H, GPU $CUDA_VISIBLE_DEVICES ==="
|
| 23 |
+
|
| 24 |
+
# 3) model: the given file, or export the newest complete checkpoint once (~5 min, CPU)
|
| 25 |
+
C=/fsx/ajay-stu/ar-data/checkpoints
|
| 26 |
+
if [ -n "${1:-}" ]; then
|
| 27 |
+
M=$1
|
| 28 |
+
else
|
| 29 |
+
CK=$(for d in $C/ckpt_*; do if [ -f $d/.metadata ]; then echo $d; fi; done | sort -t_ -k2 -n | tail -1)
|
| 30 |
+
M=/fsx/ajay-stu/ar-data/eval/model_$(basename $CK).pt
|
| 31 |
+
[ -f $M ] || python -m ar.eval.export_ckpt --ckpt $CK --out $M || { echo "export failed"; exit 1; }
|
| 32 |
+
fi
|
| 33 |
+
echo "=== evaluating $(basename $M) $(date -u) ==="
|
| 34 |
+
|
| 35 |
+
# 4) all evals; keep the score lines
|
| 36 |
+
python -m ar.eval.val_loss --model $M --data /fsx/ajay-stu/ar-data/heldout/stack_python.bin /fsx/ajay-stu/ar-data/heldout/fineweb.bin
|
| 37 |
+
python -m ar.eval.humaneval --model $M | tail -1
|
| 38 |
+
python -m ar.eval.gsm8k --model $M | tail -1
|
| 39 |
+
echo "=== done $(date -u) ==="
|
eval_latest.sh
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Export the newest COMPLETE checkpoint, then run all evals on one GPU of a FULLY FREE node.
|
| 3 |
+
# (On this cluster "1 GPU anywhere" often lands on GPUs someone else is already using.)
|
| 4 |
+
# Run: nohup ./eval_latest.sh > logs/eval_$(date +%m%d_%H%M).log 2>&1 &
|
| 5 |
+
# Optional: MODEL=<existing export .pt> to skip the export step
|
| 6 |
+
set -uo pipefail
|
| 7 |
+
cd /fsx/ajay-stu/AR
|
| 8 |
+
source .venv/bin/activate
|
| 9 |
+
export PYTHONPATH=$PWD:${PYTHONPATH:-}
|
| 10 |
+
export HF_DATASETS_OFFLINE=1 # benchmarks are already saved; some nodes have no internet
|
| 11 |
+
C=/fsx/ajay-stu/ar-data/checkpoints
|
| 12 |
+
EXC="ip-10-0-136-14,ip-10-0-136-94,ip-10-0-136-253,ip-10-0-138-178,ip-10-0-139-113,ip-10-0-140-247"
|
| 13 |
+
SKIP=$( { echo $EXC | tr ',' '\n'; cat logs/bad_nodes.txt logs/bad_nodes_perm.txt 2>/dev/null; } | sort -u )
|
| 14 |
+
|
| 15 |
+
# 1) which model: the given export, or the newest complete checkpoint (exported once)
|
| 16 |
+
if [ -n "${MODEL:-}" ]; then
|
| 17 |
+
M=$MODEL
|
| 18 |
+
else
|
| 19 |
+
CK=$(for d in $C/ckpt_*; do if [ -f $d/.metadata ]; then echo $d; fi; done | sort -t_ -k2 -n | tail -1)
|
| 20 |
+
M=/fsx/ajay-stu/ar-data/eval/model_$(basename $CK).pt
|
| 21 |
+
mkdir -p /fsx/ajay-stu/ar-data/eval
|
| 22 |
+
[ -f $M ] || srun -p dev -N1 -n1 --gpus=0 --cpus-per-task=16 --exclude=$EXC \
|
| 23 |
+
python -m ar.eval.export_ckpt --ckpt $CK --out $M || { echo "export failed"; exit 1; }
|
| 24 |
+
fi
|
| 25 |
+
ls -lh $M || exit 1
|
| 26 |
+
echo "=== evaluating $(basename $M) $(date -u) ==="
|
| 27 |
+
|
| 28 |
+
# 2) candidates: Slurm-idle nodes with all 8 GPUs empty, minus colleague and bad nodes
|
| 29 |
+
CANDS=$(./find_nodes.sh | grep -vxF -f <(echo "$SKIP") | head -10)
|
| 30 |
+
[ -z "$CANDS" ] && { echo "no fully free node right now, try again later"; exit 1; }
|
| 31 |
+
echo "candidate nodes: $(echo $CANDS)"
|
| 32 |
+
|
| 33 |
+
# 3) try them one by one until we get a GPU that is really free
|
| 34 |
+
rc=1
|
| 35 |
+
for NODE in $CANDS; do
|
| 36 |
+
srun -p dev -N1 -n1 -w $NODE --gpus=1 --cpus-per-task=8 --immediate=120 bash -c '
|
| 37 |
+
used=$(nvidia-smi -i ${CUDA_VISIBLE_DEVICES:-0} --query-gpu=memory.used --format=csv,noheader,nounits)
|
| 38 |
+
if [ "$used" -ge 2000 ]; then echo "GPU already in use ($used MiB) on $(hostname), trying the next node"; exit 3; fi
|
| 39 |
+
echo "=== on $(hostname), GPU ${CUDA_VISIBLE_DEVICES:-0} ==="
|
| 40 |
+
python -m ar.eval.val_loss --model '"$M"' --data /fsx/ajay-stu/ar-data/heldout/stack_python.bin /fsx/ajay-stu/ar-data/heldout/fineweb.bin
|
| 41 |
+
python -m ar.eval.humaneval --model '"$M"' | tail -1
|
| 42 |
+
python -m ar.eval.gsm8k --model '"$M"' | tail -1
|
| 43 |
+
'
|
| 44 |
+
rc=$?
|
| 45 |
+
[ $rc -eq 0 ] && break
|
| 46 |
+
done
|
| 47 |
+
echo "=== done (exit $rc) $(date -u) ==="
|
find_nodes.sh
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Prints nodes that are Slurm-idle AND have all 8 GPUs free, one hostname per line.
|
| 3 |
+
cd /fsx/ajay-stu/AR
|
| 4 |
+
/usr/bin/python3 /fsx/ajay-stu/gpu_check.py 2>/dev/null | grep -F "8/8" | grep -F "Users: []" \
|
| 5 |
+
| awk '{print $1}' | sed 's/\./-/g; s/^/ip-/' | sort -u > logs/gpufree.txt
|
| 6 |
+
# -N = one line per node (without it sinfo groups names like ip-10-0-192-[64,124])
|
| 7 |
+
sinfo -p dev -h -N -o "%N %t" | awk '$2=="idle"{print $1}' | sort -u > logs/idle.txt
|
| 8 |
+
comm -12 logs/gpufree.txt logs/idle.txt
|
finish_fw.sh
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# One-time: wait for the 4 English tokenizing jobs, check the grown files, then re-balance
|
| 3 |
+
# the English weights by file size and RELOAD, so training uses the new data.
|
| 4 |
+
# Run: nohup ./finish_fw.sh > logs/finish_fw.log 2>&1 &
|
| 5 |
+
cd /fsx/ajay-stu/AR
|
| 6 |
+
source .venv/bin/activate
|
| 7 |
+
JOBS="39801,39802,39805,39806"
|
| 8 |
+
|
| 9 |
+
# 1) wait (max 12 h) until all 4 jobs have left the queue
|
| 10 |
+
for i in $(seq 144); do
|
| 11 |
+
n=$(squeue -h -j $JOBS 2>/dev/null | wc -l)
|
| 12 |
+
[ "$n" -eq 0 ] && break
|
| 13 |
+
sleep 300
|
| 14 |
+
done
|
| 15 |
+
[ "$n" -ne 0 ] && { echo "$(date -u) jobs still running after 12 h, nothing changed"; exit 1; }
|
| 16 |
+
|
| 17 |
+
# 2) each job must have ended normally (not crashed, not stopped by the disk guard)
|
| 18 |
+
for j in ${JOBS//,/ }; do
|
| 19 |
+
grep -q "^\[done\]" logs/tok_ar-tok_$j.out || { echo "$(date -u) job $j did not finish normally, nothing changed"; exit 1; }
|
| 20 |
+
done
|
| 21 |
+
echo "$(date -u) all 4 jobs finished"
|
| 22 |
+
|
| 23 |
+
# 3) check the files: full documents, ~20B tokens, new part is not a repeat of the start
|
| 24 |
+
python - <<'PY' || { echo "$(date -u) file check FAILED, nothing changed"; exit 1; }
|
| 25 |
+
import re, sys
|
| 26 |
+
import numpy as np
|
| 27 |
+
EOT = 151645
|
| 28 |
+
log = open("logs/resume_tok.log").read()
|
| 29 |
+
ok = True
|
| 30 |
+
for g in ("003", "004", "005", "006"):
|
| 31 |
+
p = f"/fsx/ajay-stu/ar-data/bin/fw{g}/fineweb.bin"
|
| 32 |
+
old = int(re.search(rf"fw{g}: have (\d+)", log).group(1)) # tokens before resuming
|
| 33 |
+
a = np.memmap(p, dtype=np.uint32, mode="r")
|
| 34 |
+
repeat = bool(np.array_equal(a[:2048], a[old:old + 2048])) # a failed skip restarts at doc 1
|
| 35 |
+
good = bool(a[-1] == EOT and a[old - 1] == EOT and not repeat and len(a) >= 19.9e9)
|
| 36 |
+
print(f"fw{g}: {len(a)/1e9:.2f}B tokens, old part {old/1e9:.2f}B, repeats start: {repeat}, ok: {good}")
|
| 37 |
+
ok = ok and good
|
| 38 |
+
sys.exit(0 if ok else 1)
|
| 39 |
+
PY
|
| 40 |
+
|
| 41 |
+
# 4) re-balance the English weights by file size (English total stays the same)
|
| 42 |
+
cp run_args.sh run_args.sh.bak_fw20
|
| 43 |
+
python - <<'PY' || { echo "$(date -u) weight update FAILED, restored"; cp run_args.sh.bak_fw20 run_args.sh; exit 1; }
|
| 44 |
+
import os, re, pathlib
|
| 45 |
+
p = pathlib.Path("run_args.sh")
|
| 46 |
+
s = p.read_text()
|
| 47 |
+
bins = re.search(r'^BIN="([^"]*)"', s, re.M).group(1).split()
|
| 48 |
+
w = re.search(r'^WEIGHTS="([^"]*)"', s, re.M).group(1).split()
|
| 49 |
+
assert len(bins) == len(w) == 16, f"expected 16/16, got {len(bins)}/{len(w)}"
|
| 50 |
+
eng = [k for k, b in enumerate(bins) if b.endswith("/fineweb.bin")]
|
| 51 |
+
assert len(eng) == 5, f"expected 5 English files, got {len(eng)}"
|
| 52 |
+
share = sum(float(w[k]) for k in eng)
|
| 53 |
+
size = {k: os.path.getsize(bins[k]) for k in eng}
|
| 54 |
+
for k in eng:
|
| 55 |
+
w[k] = f"{share * size[k] / sum(size.values()):.6f}"
|
| 56 |
+
s = re.sub(r'^WEIGHTS="[^"]*"', lambda m: 'WEIGHTS="' + " ".join(w) + '"', s, count=1, flags=re.M)
|
| 57 |
+
p.write_text(s)
|
| 58 |
+
for k in eng:
|
| 59 |
+
print(f"{float(w[k]):.4f} {bins[k].split('/ar-data/')[-1]}")
|
| 60 |
+
print(f"English total: {sum(float(w[k]) for k in eng):.4f}")
|
| 61 |
+
PY
|
| 62 |
+
|
| 63 |
+
# 5) apply after the next checkpoint (same nodes); undo the edit if any check fails
|
| 64 |
+
if bash -n run_args.sh && bash -c 'source run_args.sh; for f in $BIN; do [ -f "$f" ] || exit 1; done'; then
|
| 65 |
+
touch logs/RELOAD && echo "$(date -u) RELOAD set: training switches after the next checkpoint"
|
| 66 |
+
else
|
| 67 |
+
cp run_args.sh.bak_fw20 run_args.sh; echo "$(date -u) run_args check failed, restored"; exit 1
|
| 68 |
+
fi
|
memtrace.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Every minute for 1 hour: RssAnon (GB) of our biggest training program on this node, with the step.
|
| 3 |
+
# Run on a training node: nohup ./memtrace.sh <jobid> > logs/mem_trace.log 2>&1 &
|
| 4 |
+
cd /fsx/ajay-stu/AR
|
| 5 |
+
J=$1
|
| 6 |
+
# pid= prints no header; tr removes the spaces ps puts in front of the number
|
| 7 |
+
P=$(ps -u ajay-stu -o pid= --sort=-rss | head -1 | tr -d ' ')
|
| 8 |
+
for i in $(seq 60); do
|
| 9 |
+
a=$(awk '/RssAnon/ {printf "%.1f", $2 / 1048576}' /proc/$P/status 2>/dev/null)
|
| 10 |
+
s=$(grep "^step" logs/real_$J.log | tail -1 | awk '{print $2}')
|
| 11 |
+
echo "$(date -u +%H:%M) step $s RssAnon ${a:-gone} GB"
|
| 12 |
+
sleep 60
|
| 13 |
+
done
|
new_data.sh
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# One-time: fresh data for the longer Stage 1 (~300B tokens).
|
| 3 |
+
# English: fineweb-edu groups 007-009 -> new files fw007-fw009 (20B each)
|
| 4 |
+
# Code: 5 languages continue after the documents already used (appended)
|
| 5 |
+
# Math: finemath-3plus continues after the documents already used (appended)
|
| 6 |
+
# Run: nohup ./new_data.sh > logs/new_data.log 2>&1 &
|
| 7 |
+
cd /fsx/ajay-stu/AR
|
| 8 |
+
source .venv/bin/activate
|
| 9 |
+
D=/fsx/ajay-stu/ar-data/bin
|
| 10 |
+
P=sample/350BT
|
| 11 |
+
|
| 12 |
+
# 1) files we append to must end on a full document; if not, add one end-of-text id
|
| 13 |
+
# (adding is safe while training reads the file; cutting it would not be)
|
| 14 |
+
python - <<'PY'
|
| 15 |
+
import numpy as np
|
| 16 |
+
EOT = 151645
|
| 17 |
+
for name in ["stack_python", "stack_javascript", "stack_java", "stack_cpp", "stack_typescript", "finemath3"]:
|
| 18 |
+
p = f"/fsx/ajay-stu/ar-data/bin/{name}.bin"
|
| 19 |
+
last = int(np.memmap(p, dtype=np.uint32, mode="r")[-1])
|
| 20 |
+
if last != EOT:
|
| 21 |
+
with open(p, "ab") as f:
|
| 22 |
+
np.array([EOT], dtype=np.uint32).tofile(f)
|
| 23 |
+
print(f"{name}: added end-of-text after a half-written document")
|
| 24 |
+
else:
|
| 25 |
+
print(f"{name}: ends on a full document")
|
| 26 |
+
PY
|
| 27 |
+
|
| 28 |
+
# 2) the Python job crashed before printing its skip value: count its documents,
|
| 29 |
+
# plus 5% for the ~1% the code filter dropped, so the new part never overlaps
|
| 30 |
+
K=$(python -c "
|
| 31 |
+
import numpy as np
|
| 32 |
+
a = np.memmap('$D/stack_python.bin', dtype=np.uint32, mode='r'); n = 500_000_000
|
| 33 |
+
print(sum(int((a[i:i + n] == 151645).sum()) for i in range(0, len(a), n)))")
|
| 34 |
+
PYSKIP=$(( 20000 + K * 105 / 100 ))
|
| 35 |
+
echo "$(date -u) stack_python: $K documents in file, skip $PYSKIP"
|
| 36 |
+
|
| 37 |
+
# $1 source $2 out dir $3 tokens to add $4 docs to skip $5 data files (optional)
|
| 38 |
+
sub() {
|
| 39 |
+
[ -z "$4" ] && { echo "$(date -u) $1: no skip value, NOT submitted"; return; }
|
| 40 |
+
echo "$(date -u) $1 -> $2: add $3 tokens, skip $4 ${5:+files $5}"
|
| 41 |
+
sbatch --export="ALL,SOURCE=$1,TARGET=$3,OUT_DIR=$2,SKIP_DOCS=$4,DATA_FILES=${5:-}" tokenize.sbatch
|
| 42 |
+
sleep 300 # Hugging Face rate limit
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
for g in 007 008 009; do sub fineweb $D/fw$g 20000000000 0 "$P/${g}_*.parquet"; done
|
| 46 |
+
sub stack_python $D 10000000000 "$PYSKIP"
|
| 47 |
+
sub stack_javascript $D 4000000000 3917625
|
| 48 |
+
sub stack_java $D 4000000000 3062240
|
| 49 |
+
sub stack_cpp $D 3000000000 978851
|
| 50 |
+
sub stack_typescript $D 2000000000 3330360
|
| 51 |
+
sub finemath3 $D 16000000000 4601977
|
| 52 |
+
echo "$(date -u) all 9 jobs submitted"
|
nodecheck.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# One-line health report of THIS node (run inside a short Slurm job on that node).
|
| 3 |
+
gpus=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | wc -l)
|
| 4 |
+
gused=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | awk '{s+=$1} END {print s+0}')
|
| 5 |
+
ram=$(free -g | awk '/Mem:/ {print $7}')
|
| 6 |
+
swap=$(free -g | awk '/Swap:/ {print $3}')
|
| 7 |
+
load=$(cut -d' ' -f1 /proc/loadavg)
|
| 8 |
+
# real people (uid >= 1000) other than us with processes on this node
|
| 9 |
+
others=$(ps -eo uid=,user= | awk '$1 >= 1000 && $1 != 65534 {print $2}' | sort -u | grep -vx ajay-stu | wc -l)
|
| 10 |
+
# read 512 MB from /fsx at a random spot
|
| 11 |
+
mbs=$(dd if=/fsx/ajay-stu/ar-data/bin/finemath.bin of=/dev/null bs=1M count=512 skip=$((RANDOM % 30000)) 2>&1 \
|
| 12 |
+
| awk '/copied/ {v=$(NF-1); if ($NF=="GB/s") v*=1000; print int(v)}')
|
| 13 |
+
echo "$(hostname) $gpus $gused $ram ${swap:-0} $load $others ${mbs:-0}"
|
preflight.sh
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Runs inside a job: fail if any node's GPUs are already in use by someone else.
|
| 3 |
+
srun --ntasks-per-node=1 bash -c '
|
| 4 |
+
u=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
| 5 |
+
echo "preflight $(hostname) gpu_used=${u}MiB"
|
| 6 |
+
[ "$u" -lt 2000 ]
|
| 7 |
+
'
|
redo_english.sh
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# One-time: after training reloads without the copy files, delete the bad files and
|
| 3 |
+
# re-tokenize real English (groups 003-006), the held-out set (016) and Stage 2 hq (010-012).
|
| 4 |
+
# Run: nohup ./redo_english.sh > logs/redo_english.log 2>&1 &
|
| 5 |
+
cd /fsx/ajay-stu/AR
|
| 6 |
+
D=/fsx/ajay-stu/ar-data
|
| 7 |
+
|
| 8 |
+
# 1) wait (max 90 min) until training is stepping again after the reload
|
| 9 |
+
for i in $(seq 90); do
|
| 10 |
+
J=$(squeue -u $USER -h -n ar-real -t RUNNING -o %i | head -1)
|
| 11 |
+
if [ -n "$J" ] && { [ "$J" != 39648 ] || \
|
| 12 |
+
awk '/=== reload requested/{r=1} r && /^step/{s=1} END{exit !s}' logs/real_$J.log; }; then
|
| 13 |
+
break
|
| 14 |
+
fi
|
| 15 |
+
[ $i -eq 90 ] && { echo "$(date -u) reload not seen after 90 min, nothing deleted"; exit 1; }
|
| 16 |
+
sleep 60
|
| 17 |
+
done
|
| 18 |
+
echo "$(date -u) training restarted on the new settings (job $J)"
|
| 19 |
+
|
| 20 |
+
# 2) safety: training must no longer list any copy file
|
| 21 |
+
if grep '^BIN=' run_args.sh | grep -q '/fw00'; then
|
| 22 |
+
echo "BIN still lists fw00x files, nothing deleted"; exit 1
|
| 23 |
+
fi
|
| 24 |
+
|
| 25 |
+
# 3) delete the bad files (explicit paths only)
|
| 26 |
+
ls -l $D/bin/fw00{3,4,5,6}/fineweb.bin $D/stage2/hq01{0,1,2}/fineweb_hq.bin $D/heldout/fineweb.bin
|
| 27 |
+
rm -f $D/bin/fw00{3,4,5,6}/fineweb.bin $D/stage2/hq01{0,1,2}/fineweb_hq.bin $D/heldout/fineweb.bin
|
| 28 |
+
echo "$(date -u) deleted; free now: $(df -h /fsx | tail -1)"
|
| 29 |
+
|
| 30 |
+
# 4) submit the real jobs, 5 min apart (Hugging Face rate limit)
|
| 31 |
+
sub() { sbatch --export="ALL,$1" tokenize.sbatch; sleep 300; }
|
| 32 |
+
sub "SOURCE=fineweb,TARGET=20000000,OUT_DIR=$D/heldout,DATA_FILES=sample/350BT/016_00001.parquet"
|
| 33 |
+
for g in 003 004 005 006; do
|
| 34 |
+
sub "SOURCE=fineweb,TARGET=20000000000,OUT_DIR=$D/bin/fw$g,DATA_FILES=sample/350BT/${g}_*.parquet"
|
| 35 |
+
done
|
| 36 |
+
for g in 010 011 012; do
|
| 37 |
+
sub "SOURCE=fineweb_hq,TARGET=2000000000,OUT_DIR=$D/stage2/hq$g,DATA_FILES=sample/350BT/${g}_*.parquet"
|
| 38 |
+
done
|
| 39 |
+
echo "$(date -u) all 8 jobs submitted"
|
resume_tok.sh
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# One-time: resume the tokenizing jobs that stopped when the disk filled up.
|
| 3 |
+
# Each job skips the documents already written (--skip_docs) and adds only what is missing.
|
| 4 |
+
# Run: nohup ./resume_tok.sh > logs/resume_tok.log 2>&1 &
|
| 5 |
+
cd /fsx/ajay-stu/AR
|
| 6 |
+
source .venv/bin/activate
|
| 7 |
+
D=/fsx/ajay-stu/ar-data
|
| 8 |
+
|
| 9 |
+
# documents already written = the skip value printed by the stopped job
|
| 10 |
+
skip_from_log() { grep -oP "skip_docs \K[0-9]+" logs/tok_ar-tok_$1.out | tail -1; }
|
| 11 |
+
|
| 12 |
+
# fw003 crashed before printing it, so count its documents (end-of-text ids) instead
|
| 13 |
+
count_docs() {
|
| 14 |
+
python -c "
|
| 15 |
+
import numpy as np
|
| 16 |
+
a = np.memmap('$1', dtype=np.uint32, mode='r'); n = 500_000_000
|
| 17 |
+
print(sum(int((a[i:i + n] == 151645).sum()) for i in range(0, len(a), n)))"
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
# $1 source $2 out dir $3 data files $4 skip $5 total tokens wanted in the file
|
| 21 |
+
sub() {
|
| 22 |
+
local have left
|
| 23 |
+
have=$(( $(stat -c %s "$2/$1.bin") / 4 )); left=$(( $5 - have ))
|
| 24 |
+
if [ -z "$4" ] || [ "$4" -le 0 ]; then echo "$(date -u) $2: no skip value, NOT resumed"; return; fi
|
| 25 |
+
if [ "$left" -le 0 ]; then echo "$(date -u) $2: already complete"; return; fi
|
| 26 |
+
echo "$(date -u) $2: have $have, adding $left, skip $4"
|
| 27 |
+
sbatch --export="ALL,SOURCE=$1,TARGET=$left,OUT_DIR=$2,DATA_FILES=$3,SKIP_DOCS=$4" tokenize.sbatch
|
| 28 |
+
sleep 300 # Hugging Face rate limit
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
P=sample/350BT
|
| 32 |
+
sub fineweb $D/bin/fw003 "$P/003_*.parquet" "$(count_docs $D/bin/fw003/fineweb.bin)" 20000000000
|
| 33 |
+
sub fineweb $D/bin/fw004 "$P/004_*.parquet" "$(skip_from_log 39671)" 20000000000
|
| 34 |
+
sub fineweb $D/bin/fw005 "$P/005_*.parquet" "$(skip_from_log 39672)" 20000000000
|
| 35 |
+
sub fineweb $D/bin/fw006 "$P/006_*.parquet" "$(skip_from_log 39673)" 20000000000
|
| 36 |
+
sub fineweb_hq $D/stage2/hq010 "$P/010_*.parquet" "$(skip_from_log 39674)" 2000000000
|
| 37 |
+
sub fineweb_hq $D/stage2/hq011 "$P/011_*.parquet" "$(skip_from_log 39675)" 2000000000
|
| 38 |
+
sub fineweb_hq $D/stage2/hq012 "$P/012_*.parquet" "$(skip_from_log 39676)" 2000000000
|
| 39 |
+
echo "$(date -u) done submitting"
|
run_args.sh
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Training settings, re-read at every (re)start of the training loop.
|
| 2 |
+
# To change them without giving up the nodes: edit this file, then `touch logs/RELOAD`.
|
| 3 |
+
BIN="/fsx/ajay-stu/ar-data/bin/fineweb.bin /fsx/ajay-stu/ar-data/bin/fw003/fineweb.bin /fsx/ajay-stu/ar-data/bin/fw004/fineweb.bin /fsx/ajay-stu/ar-data/bin/fw005/fineweb.bin /fsx/ajay-stu/ar-data/bin/fw006/fineweb.bin /fsx/ajay-stu/ar-data/bin/fw007/fineweb.bin /fsx/ajay-stu/ar-data/bin/fw008/fineweb.bin /fsx/ajay-stu/ar-data/bin/fw009/fineweb.bin /fsx/ajay-stu/ar-data/bin/stack_python.bin /fsx/ajay-stu/ar-data/bin/stack_javascript.bin /fsx/ajay-stu/ar-data/bin/stack_java.bin /fsx/ajay-stu/ar-data/bin/stack_cpp.bin /fsx/ajay-stu/ar-data/bin/stack_typescript.bin /fsx/ajay-stu/ar-data/bin/stack_go.bin /fsx/ajay-stu/ar-data/bin/stack_rust.bin /fsx/ajay-stu/ar-data/bin/stack_shell.bin /fsx/ajay-stu/ar-data/bin/stack_sql.bin /fsx/ajay-stu/ar-data/bin/finemath.bin /fsx/ajay-stu/ar-data/bin/finemath3.bin"
|
| 4 |
+
WEIGHTS="0.174428 0.067939 0.067939 0.067939 0.067939 0.067939 0.067939 0.067939 0.070791 0.033565 0.033565 0.023975 0.019180 0.004795 0.004795 0.004539 0.004795 0.044444 0.105556"
|
| 5 |
+
STOP_AT=619700
|
| 6 |
+
LR_HORIZON=572000
|
| 7 |
+
PEAK_LR=3e-4
|
| 8 |
+
# >>> stage2 (written by s2_prepare.py): Stage 2 switches on by itself at step 572,000
|
| 9 |
+
export STAGE2_START=572000 STAGE2_WARMUP=1000 STAGE2_PEAK=1e-4 STAGE2_MIN=1e-5
|
| 10 |
+
export PROTECT_CKPTS="ckpt_571999"
|
| 11 |
+
export S2_BIN="/fsx/ajay-stu/ar-data/stage2/hq010/fineweb_hq.bin /fsx/ajay-stu/ar-data/stage2/hq011/fineweb_hq.bin /fsx/ajay-stu/ar-data/stage2/hq012/fineweb_hq.bin /fsx/ajay-stu/ar-data/stage2/cosmopedia.bin /fsx/ajay-stu/ar-data/bin/stack_python.bin /fsx/ajay-stu/ar-data/bin/stack_javascript.bin /fsx/ajay-stu/ar-data/bin/stack_java.bin /fsx/ajay-stu/ar-data/bin/stack_cpp.bin /fsx/ajay-stu/ar-data/bin/stack_typescript.bin /fsx/ajay-stu/ar-data/bin/stack_go.bin /fsx/ajay-stu/ar-data/bin/stack_rust.bin /fsx/ajay-stu/ar-data/bin/stack_shell.bin /fsx/ajay-stu/ar-data/bin/stack_sql.bin /fsx/ajay-stu/ar-data/bin/finemath.bin /fsx/ajay-stu/ar-data/stage2/infiwebmath.bin /fsx/ajay-stu/ar-data/bin/finemath3.bin"
|
| 12 |
+
export S2_WEIGHTS="0.066667 0.066667 0.066667 0.100000 0.106186 0.050347 0.050347 0.035962 0.028770 0.007192 0.007192 0.006809 0.007192 0.160000 0.120000 0.120000"
|
| 13 |
+
# <<< stage2
|
sanity_4node.sbatch
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
#SBATCH --job-name=ar-sanity-4node
|
| 3 |
+
#SBATCH --partition=dev
|
| 4 |
+
#SBATCH --nodes=4
|
| 5 |
+
#SBATCH --nodelist=ip-10-0-154-148,ip-10-0-184-219,ip-10-0-233-76,ip-10-0-245-227
|
| 6 |
+
#SBATCH --ntasks-per-node=1
|
| 7 |
+
#SBATCH --gres=gpu:8
|
| 8 |
+
#SBATCH --cpus-per-task=96
|
| 9 |
+
#SBATCH --exclusive
|
| 10 |
+
#SBATCH --output=sanity_4node_%j.log
|
| 11 |
+
|
| 12 |
+
set -euo pipefail
|
| 13 |
+
|
| 14 |
+
cd /fsx/ajay-stu/AR
|
| 15 |
+
source .venv/bin/activate
|
| 16 |
+
|
| 17 |
+
export MASTER_ADDR=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n1)
|
| 18 |
+
export MASTER_PORT=29517
|
| 19 |
+
|
| 20 |
+
export FI_PROVIDER=efa
|
| 21 |
+
export NCCL_PROTO=simple
|
| 22 |
+
export NCCL_DEBUG=INFO
|
| 23 |
+
export NCCL_SOCKET_IFNAME=enp73s0
|
| 24 |
+
export NCCL_IB_DISABLE=0
|
| 25 |
+
export FI_EFA_USE_DEVICE_RDMA=1
|
| 26 |
+
export LD_LIBRARY_PATH=/fsx/ajay-stu/AR/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib:$LD_LIBRARY_PATH
|
| 27 |
+
export LD_LIBRARY_PATH=/fsx/ajay-stu/AR/.venv/lib/python3.10/site-packages/nvidia/cudnn/lib:$LD_LIBRARY_PATH
|
| 28 |
+
|
| 29 |
+
echo "MASTER_ADDR=$MASTER_ADDR NODES=$SLURM_NNODES job=$SLURM_JOB_ID"
|
| 30 |
+
|
| 31 |
+
srun bash -c '
|
| 32 |
+
torchrun \
|
| 33 |
+
--nnodes=4 \
|
| 34 |
+
--nproc_per_node=8 \
|
| 35 |
+
--node_rank=$SLURM_NODEID \
|
| 36 |
+
--rdzv_id=$SLURM_JOB_ID \
|
| 37 |
+
--rdzv_backend=c10d \
|
| 38 |
+
--rdzv_endpoint=$MASTER_ADDR:$MASTER_PORT \
|
| 39 |
+
-m ar.train.train_fsdp \
|
| 40 |
+
--bin /fsx/ajay-stu/ar-data/bin/fineweb.bin \
|
| 41 |
+
--model_size full \
|
| 42 |
+
--max_steps 20 \
|
| 43 |
+
--batch_size 1 \
|
| 44 |
+
--seq_len 2048 \
|
| 45 |
+
--warmup_steps 5
|
| 46 |
+
'
|
save_final.sh
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Waits for a final checkpoint, then:
|
| 3 |
+
# 1) keeps it forever as a hard-link copy (no extra disk space; survives deletion of the original)
|
| 4 |
+
# 2) exports a weights-only bf16 file (~8 GB) for downloading to a PC, plus its md5 fingerprint
|
| 5 |
+
# Settings (environment): NAME = checkpoint folder, OUT = target folder, FILE = export file name,
|
| 6 |
+
# MAXSTEP (optional) = warn and stop if training passes this step without the checkpoint.
|
| 7 |
+
# Example, final Stage 2 model (login node):
|
| 8 |
+
# NAME=ckpt_619699 OUT=/fsx/ajay-stu/ar-data/stage2_final FILE=model_stage2_final.pt \
|
| 9 |
+
# nohup ./save_final.sh > logs/save_stage2.log 2>&1 &
|
| 10 |
+
set -uo pipefail
|
| 11 |
+
AR=${AR:-/fsx/ajay-stu/AR}
|
| 12 |
+
CKDIR=${CKDIR:-/fsx/ajay-stu/ar-data/checkpoints}
|
| 13 |
+
: "${NAME:?set NAME, e.g. ckpt_619699}" "${OUT:?set OUT, the target folder}" "${FILE:?set FILE, e.g. model_stage2_final.pt}"
|
| 14 |
+
MAXSTEP=${MAXSTEP:-0}
|
| 15 |
+
EXC="ip-10-0-136-14,ip-10-0-136-94,ip-10-0-136-253,ip-10-0-138-178,ip-10-0-139-113,ip-10-0-140-247"
|
| 16 |
+
cd "$AR" || exit 1
|
| 17 |
+
[ -f .venv/bin/activate ] && source .venv/bin/activate
|
| 18 |
+
export PYTHONPATH=$PWD
|
| 19 |
+
|
| 20 |
+
# latest training step from the running job's log (empty if no job is running)
|
| 21 |
+
latest_step() {
|
| 22 |
+
local j
|
| 23 |
+
j=$(squeue -u "${USER:-$(id -un)}" -h -n ar-real -t RUNNING -o %i 2>/dev/null | head -1)
|
| 24 |
+
[ -n "$j" ] && grep "^step" "logs/real_$j.log" 2>/dev/null | tail -1 | awk '{print $2}' || true
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
# 1) wait until the checkpoint is completely written (.metadata is written last)
|
| 28 |
+
echo "$(date -u) waiting for $CKDIR/$NAME"
|
| 29 |
+
until [ -f "$CKDIR/$NAME/.metadata" ]; do
|
| 30 |
+
s=$(latest_step)
|
| 31 |
+
if [ "$MAXSTEP" -gt 0 ] && [ "${s:-0}" -gt "$MAXSTEP" ]; then
|
| 32 |
+
echo "$(date -u) WARNING: training is at step $s but $NAME was never saved (disk full?)"
|
| 33 |
+
exit 1
|
| 34 |
+
fi
|
| 35 |
+
sleep "${POLL:-300}"
|
| 36 |
+
done
|
| 37 |
+
sleep "${SETTLE:-60}" # let the last file writes settle
|
| 38 |
+
echo "$(date -u) found complete $NAME"
|
| 39 |
+
|
| 40 |
+
# 2) permanent hard-link copy
|
| 41 |
+
mkdir -p "$OUT"
|
| 42 |
+
[ -d "$OUT/$NAME" ] || cp -al "$CKDIR/$NAME" "$OUT/$NAME" || { echo "hard-link copy failed"; exit 1; }
|
| 43 |
+
echo "$(date -u) permanent copy: $OUT/$NAME ($(ls "$OUT/$NAME" | wc -l) files)"
|
| 44 |
+
|
| 45 |
+
# 3) weights-only bf16 export for the PC (CPU job, ~5 min) and its fingerprint
|
| 46 |
+
M=$OUT/$FILE
|
| 47 |
+
if [ ! -f "$M" ]; then
|
| 48 |
+
srun -p dev -N1 -n1 --gpus=0 --cpus-per-task=16 --exclude=$EXC \
|
| 49 |
+
python -m ar.eval.export_ckpt --ckpt "$OUT/$NAME" --out "$M" || { echo "export failed"; exit 1; }
|
| 50 |
+
fi
|
| 51 |
+
( cd "$OUT" && md5sum "$FILE" > "${FILE%.pt}.md5" )
|
| 52 |
+
ls -lh "$M"
|
| 53 |
+
cat "$OUT/${FILE%.pt}.md5"
|
| 54 |
+
echo "$(date -u) DONE: $FILE saved"
|
save_stage1.sh
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Waits for the final Stage 1 checkpoint (ckpt_571999), then:
|
| 3 |
+
# 1) keeps it forever as a hard-link copy (no extra disk space; survives deletion of the original)
|
| 4 |
+
# 2) exports a weights-only bf16 file (~8 GB) for downloading to a PC, plus its md5 fingerprint
|
| 5 |
+
# Warns and stops if training gets past step 572,100 without that checkpoint (e.g. disk was full).
|
| 6 |
+
# Run once on the login node: nohup ./save_stage1.sh > logs/save_stage1.log 2>&1 &
|
| 7 |
+
set -uo pipefail
|
| 8 |
+
AR=${AR:-/fsx/ajay-stu/AR}
|
| 9 |
+
CKDIR=${CKDIR:-/fsx/ajay-stu/ar-data/checkpoints}
|
| 10 |
+
OUT=${OUT:-/fsx/ajay-stu/ar-data/stage1_final}
|
| 11 |
+
NAME=ckpt_571999
|
| 12 |
+
EXC="ip-10-0-136-14,ip-10-0-136-94,ip-10-0-136-253,ip-10-0-138-178,ip-10-0-139-113,ip-10-0-140-247"
|
| 13 |
+
cd "$AR" || exit 1
|
| 14 |
+
[ -f .venv/bin/activate ] && source .venv/bin/activate
|
| 15 |
+
export PYTHONPATH=$PWD
|
| 16 |
+
|
| 17 |
+
# latest training step from the running job's log (0 if unknown)
|
| 18 |
+
latest_step() {
|
| 19 |
+
local j
|
| 20 |
+
j=$(squeue -u "${USER:-$(id -un)}" -h -n ar-real -t RUNNING -o %i 2>/dev/null | head -1)
|
| 21 |
+
[ -n "$j" ] && grep "^step" "logs/real_$j.log" 2>/dev/null | tail -1 | awk '{print $2}' || true
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# 1) wait until the checkpoint is completely written (.metadata is written last)
|
| 25 |
+
echo "$(date -u) waiting for $CKDIR/$NAME"
|
| 26 |
+
until [ -f "$CKDIR/$NAME/.metadata" ]; do
|
| 27 |
+
s=$(latest_step)
|
| 28 |
+
if [ "${s:-0}" -gt 572100 ]; then
|
| 29 |
+
echo "$(date -u) WARNING: training is at step $s but $NAME was never saved (disk full at step 571,999?)"
|
| 30 |
+
exit 1
|
| 31 |
+
fi
|
| 32 |
+
sleep "${POLL:-300}"
|
| 33 |
+
done
|
| 34 |
+
sleep "${SETTLE:-60}" # let the last file writes settle
|
| 35 |
+
echo "$(date -u) found complete $NAME"
|
| 36 |
+
|
| 37 |
+
# 2) permanent hard-link copy
|
| 38 |
+
mkdir -p "$OUT"
|
| 39 |
+
[ -d "$OUT/$NAME" ] || cp -al "$CKDIR/$NAME" "$OUT/$NAME" || { echo "hard-link copy failed"; exit 1; }
|
| 40 |
+
echo "$(date -u) permanent copy: $OUT/$NAME ($(ls "$OUT/$NAME" | wc -l) files)"
|
| 41 |
+
|
| 42 |
+
# 3) weights-only bf16 export for the PC (CPU job, ~5 min) and its fingerprint
|
| 43 |
+
M=$OUT/model_stage1_final.pt
|
| 44 |
+
if [ ! -f "$M" ]; then
|
| 45 |
+
srun -p dev -N1 -n1 --gpus=0 --cpus-per-task=16 --exclude=$EXC \
|
| 46 |
+
python -m ar.eval.export_ckpt --ckpt "$OUT/$NAME" --out "$M" || { echo "export failed"; exit 1; }
|
| 47 |
+
fi
|
| 48 |
+
( cd "$OUT" && md5sum model_stage1_final.pt > model_stage1_final.md5 )
|
| 49 |
+
ls -lh "$M"
|
| 50 |
+
cat "$OUT/model_stage1_final.md5"
|
| 51 |
+
echo "$(date -u) DONE: Stage 1 final model saved"
|
status.sh
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# One-screen status: progress, speed, ETA, loss, checkpoints, disk, helper scripts.
|
| 3 |
+
cd /fsx/ajay-stu/AR
|
| 4 |
+
STOP=$(grep -oP '^STOP_AT=\K[0-9]+' run_args.sh)
|
| 5 |
+
J=$(squeue -u $USER -h -n ar-real -t RUNNING -o %i | head -1)
|
| 6 |
+
if [ -z "$J" ]; then
|
| 7 |
+
echo "NO training job running"; squeue -u $USER -o "%.8i %.8T %.4D %.10M %j"
|
| 8 |
+
else
|
| 9 |
+
NN=$(squeue -j $J -h -o %D)
|
| 10 |
+
L=$(grep "^step" logs/real_$J.log 2>/dev/null | tail -1)
|
| 11 |
+
if [ -z "$L" ]; then
|
| 12 |
+
echo "job $J on $NN nodes | starting up: loading checkpoint / compiling (first step in ~3-5 min)"
|
| 13 |
+
else
|
| 14 |
+
# tokens per step depend on node count (same table as the job script)
|
| 15 |
+
case $NN in 3|6) TPSTEP=393216;; 5) TPSTEP=327680;; 7) TPSTEP=458752;; *) TPSTEP=524288;; esac
|
| 16 |
+
S=$(echo "$L" | awk '{print $2}')
|
| 17 |
+
TPS=$(echo "$L" | awk '{gsub("k", "", $10); print $10 * 1000}')
|
| 18 |
+
SEC=$(awk -v l=$((STOP - S)) -v t=$TPSTEP -v r=$TPS 'BEGIN {printf "%d", (r > 0) ? l * t / r : 0}')
|
| 19 |
+
echo "job $J on $NN nodes | $L"
|
| 20 |
+
awk -v s=$S -v stop=$STOP -v sec=$SEC 'BEGIN {
|
| 21 |
+
printf "progress: %d / %d (%.1f%%) left: %d steps, ~%.1f days\n", s, stop, 100*s/stop, stop-s, sec/86400 }'
|
| 22 |
+
echo "finish ETA: $(date -u -d "+$SEC sec" '+%a %d %b %H:%M UTC') ($(TZ=Asia/Kolkata date -d "+$SEC sec" '+%H:%M IST'))"
|
| 23 |
+
grep "^step" logs/real_$J.log | tail -100 | awk '{s+=$5} END {printf "avg loss (last 100 prints): %.3f\n", s/NR}'
|
| 24 |
+
fi
|
| 25 |
+
echo "last checkpoint: $(grep -E '^\[ckpt\]' logs/real_$J.log 2>/dev/null | tail -1)"
|
| 26 |
+
fi
|
| 27 |
+
# disk now, lowest in the last 24 h, and helper scripts
|
| 28 |
+
echo "disk now: $(tail -1 logs/disk.log)"
|
| 29 |
+
echo "lowest 24h: $(grep free= logs/disk.log | tail -288 | sort -t= -k2 -n | head -1)"
|
| 30 |
+
pgrep -f watchdog.sh >/dev/null && echo "watchdog: running" || echo "watchdog: NOT running"
|
| 31 |
+
pgrep -f diskwatch.sh >/dev/null && echo "diskwatch: running" || echo "diskwatch: NOT running"
|
| 32 |
+
pgrep -f autoreload.sh >/dev/null && echo "autoreload: running" || echo "autoreload: NOT running"
|
| 33 |
+
echo "tokenizing jobs: $(squeue -u $USER -h -n ar-tok | wc -l)"
|
swap.sh
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# wait for the next checkpoint save, then restart training on the new data mix
|
| 3 |
+
J=39291
|
| 4 |
+
N=$(grep -c "\[ckpt\] saved" logs/real_$J.log)
|
| 5 |
+
while [ "$(grep -c "\[ckpt\] saved" logs/real_$J.log)" -eq "$N" ]; do sleep 30; done
|
| 6 |
+
grep "\[ckpt\] saved" logs/real_$J.log | tail -1
|
| 7 |
+
sleep 30 # let the old-checkpoint cleanup finish
|
| 8 |
+
scancel $J
|
| 9 |
+
sleep 60 # let Slurm release the nodes
|
| 10 |
+
sbatch --nodelist=ip-10-0-224-196,ip-10-0-227-25,ip-10-0-228-101,ip-10-0-228-213 train_real.sbatch
|
swap2.sh
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# One-time switch to the new loop job + Stage 1 extension to 200B tokens.
|
| 3 |
+
cd /fsx/ajay-stu/AR
|
| 4 |
+
source .venv/bin/activate
|
| 5 |
+
|
| 6 |
+
# 1) wait for the 4 tokenizing jobs, then check the files
|
| 7 |
+
while [ -n "$(squeue -u $USER -h -n ar-tok)" ]; do sleep 300; done
|
| 8 |
+
for g in 003 004 005 006; do
|
| 9 |
+
[ -s /fsx/ajay-stu/ar-data/bin/fw$g/fineweb.bin ] || { echo "$(date) fw$g missing, aborting"; exit 1; }
|
| 10 |
+
done
|
| 11 |
+
echo "$(date) new data ready"
|
| 12 |
+
|
| 13 |
+
# 2) new settings: 200B tokens (end step 381,000) + new data mix
|
| 14 |
+
python - << 'PY'
|
| 15 |
+
import glob, os
|
| 16 |
+
d = "/fsx/ajay-stu/ar-data/bin/"
|
| 17 |
+
eng = [d + "fineweb.bin"] + sorted(glob.glob(d + "fw*/fineweb.bin"))
|
| 18 |
+
code = [f"{d}stack_{l}.bin" for l in
|
| 19 |
+
["python", "javascript", "java", "cpp", "typescript", "go", "rust", "shell", "sql"]]
|
| 20 |
+
math = [d + "finemath.bin", d + "finemath3.bin"]
|
| 21 |
+
def split(files, share):
|
| 22 |
+
s = [os.path.getsize(f) for f in files]
|
| 23 |
+
return [round(share * x / sum(s), 4) for x in s]
|
| 24 |
+
files = eng + code + math
|
| 25 |
+
w = split(eng, 0.65) + split(code, 0.20) + [0.09, 0.06]
|
| 26 |
+
out = []
|
| 27 |
+
for l in open("run_args.sh").read().splitlines():
|
| 28 |
+
if l.startswith("BIN="): l = 'BIN="' + " ".join(files) + '"'
|
| 29 |
+
elif l.startswith("WEIGHTS="): l = 'WEIGHTS="' + " ".join(map(str, w)) + '"'
|
| 30 |
+
elif l.startswith("STOP_AT="): l = "STOP_AT=381000"
|
| 31 |
+
elif l.startswith("LR_HORIZON="): l = "LR_HORIZON=381000"
|
| 32 |
+
out.append(l)
|
| 33 |
+
open("run_args.sh", "w").write("\n".join(out) + "\n")
|
| 34 |
+
print("settings updated:", len(files), "files, stop at 381000")
|
| 35 |
+
PY
|
| 36 |
+
sed -i 's/ckpt_185999/ckpt_380999/' watchdog.sh # watchdog's new "finished" marker
|
| 37 |
+
|
| 38 |
+
# 3) pause the watchdog so it can't launch a duplicate during the switch
|
| 39 |
+
pkill -f watchdog.sh
|
| 40 |
+
J=$(squeue -u $USER -h -n ar-real -o %i | head -1)
|
| 41 |
+
if [ -z "$J" ]; then
|
| 42 |
+
echo "$(date) training not running; watchdog will start the new job"
|
| 43 |
+
nohup ./watchdog.sh >> logs/watchdog.log 2>&1 &
|
| 44 |
+
exit 0
|
| 45 |
+
fi
|
| 46 |
+
NODES=$(squeue -j $J -h -o %N)
|
| 47 |
+
|
| 48 |
+
# 4) after a checkpoint, switch only if no waiting job could take our nodes (max ~6 tries)
|
| 49 |
+
tries=0
|
| 50 |
+
while true; do
|
| 51 |
+
N=$(grep -c "\[ckpt\] saved" logs/real_$J.log)
|
| 52 |
+
while [ "$(grep -c "\[ckpt\] saved" logs/real_$J.log)" -eq "$N" ]; do
|
| 53 |
+
[ -z "$(squeue -j $J -h 2>/dev/null)" ] && break 2 # old job died meanwhile
|
| 54 |
+
sleep 30
|
| 55 |
+
done
|
| 56 |
+
tries=$((tries + 1))
|
| 57 |
+
risky=$(squeue -p dev -t PD -h -o "%u %D" | awk -v me=$USER '$1 != me && $2 <= 4' | wc -l)
|
| 58 |
+
if [ "$risky" -eq 0 ] || [ $tries -ge 6 ]; then break; fi
|
| 59 |
+
echo "$(date) $risky waiting jobs could take our nodes; trying at the next checkpoint"
|
| 60 |
+
done
|
| 61 |
+
sleep 30
|
| 62 |
+
scancel $J 2>/dev/null
|
| 63 |
+
sleep 20
|
| 64 |
+
sbatch --nodelist=$NODES train_real.sbatch
|
| 65 |
+
echo "$(date) switched: old job $J stopped, new loop job submitted on $NODES"
|
| 66 |
+
nohup ./watchdog.sh >> logs/watchdog.log 2>&1 &
|