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