fhyfhy's picture
Add code, tokenizer and README
23c39b5 verified
|
Raw History Blame Contribute Delete
16.3 kB
# HRM-Text on the CW-DFW cluster — training & evaluation guide
Everything here runs from `/lustre/fsw/portfolios/nemotron/users/hengyuf/HRM-Text`
inside the `hrm-text.sqsh` container (pyxis/enroot). All scripts live in `slurm/`.
```bash
cd /lustre/fsw/portfolios/nemotron/users/hengyuf/HRM-Text
export $(grep '^WANDB_API_KEY=' /lustre/fsw/portfolios/nemotron/users/hengyuf/.env)
```
> Use `export $(grep '^WANDB_API_KEY=' …)` — **not** `head -1 .env`. The file is
> `KEY=VALUE`, so taking the whole line makes the key literally
> `WANDB_API_KEY=wandb_v1_…` and rank 0 dies with an AuthenticationError,
> which kills the whole 32-GPU job.
---
## 1. Quick start
```bash
# Train (4 nodes, chained 4-hour jobs, auto-resume between them)
ARCH_NET=hrm RUN_NAME=my-run N_JOBS=12 NODES=4 PARTITION=batch TIME=04:00:00 \
./slurm/submit_chain.sh
# Held-out eval loss for every epoch checkpoint (2 nodes, ~4 min)
CKPT=checkpoints/HRM-Text/my-run sbatch --export=ALL slurm/eval_loss.sbatch
# Benchmark suite for one epoch (1 node x 8 GPUs, ~15 min)
CKPT=checkpoints/HRM-Text/my-run CKPT_EPOCH=4 sbatch --export=ALL slurm/eval_bench.sbatch
# Figures
/lustre/fsw/portfolios/nemotron/users/hengyuf/RL/.venv/bin/python slurm/plot_trajectories.py
```
## 2. Assets
| What | Path |
| --- | --- |
| Container image | `hrm_env/hrm-text.sqsh` (23 GB, from `sapientai/hrm-text:latest`) |
| Training data (sampled + compacted, 83 GB) | `hrm_data/sampled_ep4_seed0` |
| Held-out eval split (40 MB, 20.8M tokens) | `hrm_data/eval_split_ep4s0_seed1000` |
| Smoke-test data (273 MB) | `hrm_data/sampled_smoke_ep4_seed0` |
| Full tokenized corpus (683 GB, for re-sampling) | `hrm_data/data_tokenized_bpe_65k` |
| Checkpoints | `checkpoints/HRM-Text/<RUN_NAME>/` |
| Logs | `slurm/logs/` |
| Figures | `plots/` |
---
## 3. Training
### 3.1 `slurm/train.sbatch` — one job
Reproduces the reference L run
(`arch/size@arch=L lr=2.5e-4 global_batch_size=172032`, everything else from
`config/cfg_pretrain.yaml`). Node count and partition are free; they never
change the hyperparameters.
```bash
sbatch --nodes=4 --partition=backfill --time=20:00:00 slurm/train.sbatch
RUN_NAME=x ARCH_NET=transformer sbatch --export=ALL --nodes=2 slurm/train.sbatch
```
| Variable | Default | Meaning |
| --- | --- | --- |
| `ARCH_NET` | `hrm` | architecture, see §3.4 |
| `ARCH_SIZE` | `L` | `B` / `L` / `XL` / `XXL` / `XXL_wide` |
| `LR` | `2.5e-4` | peak LR (reference value for L) |
| `GLOBAL_BATCH_SIZE` | `172032` | **tokens** per optimizer step |
| `EPOCHS` | `4` | must match the number of `epoch_*` dirs in `SAMPLED_SRC` |
| `SEED` | `0` | |
| `RUN_NAME` | `<net>-<nodes>n-job<id>` | names the checkpoint dir **and** the wandb run |
| `PROJECT_NAME` | `HRM-Text` | wandb project |
| `CHECKPOINT_PATH` | `checkpoints/$PROJECT_NAME/$RUN_NAME` | |
| `SAMPLED_SRC` | `hrm_data/sampled_ep4_seed0` | training data; point at the smoke set for a dry run |
| `STEP_CKPT_INTERVAL` | `5000` | rolling mid-epoch checkpoint every N steps (`0` disables) |
| `EVAL_DATA_SRC` | — | optional: held-out split evaluated on the LIVE weights during training; `eval/*` metrics go to the SAME wandb run as training (raw weights, not EMA; the split is re-read as `epoch_0` every pass, so batches are bit-identical across steps) |
| `EVAL_INTERVAL` | `1000` | steps between in-training evals (needs `EVAL_DATA_SRC`) |
| `RESUME_AUTO` | `1` | auto-resume from the newest checkpoint in `CHECKPOINT_PATH` |
| `EXTRA_ARGS` | — | extra hydra overrides, e.g. `"arch.cot_decode_topk=32"` |
| `GPUS_PER_NODE` | `8` | |
| `SQSH` | `hrm_env/hrm-text.sqsh` | container image |
Hydra note: keys that do **not** exist in `cfg_pretrain.yaml` need a `+`
prefix (`+resume_from=…`); keys under `arch` are set as `arch.<key>=…`.
The job prints a banner with the resolved settings — check `W&B: mode=online`
there to confirm the key made it through.
### 3.2 `slurm/submit_chain.sh` — chained jobs (the normal way to train)
Submits N jobs each depending on the previous with `afterany`, so training
survives wall-clock limits. Every job auto-resumes from the newest checkpoint;
jobs that find training already finished exit in ~10 s.
```bash
RUN_NAME=my-run N_JOBS=12 NODES=4 PARTITION=batch TIME=04:00:00 ./slurm/submit_chain.sh
```
| Variable | Default | Notes |
| --- | --- | --- |
| `RUN_NAME` | **required** | the fixed name is what links the chain to one checkpoint dir |
| `N_JOBS` | 4 | budget generously; extra segments are free |
| `NODES` | 4 | must stay the same across the whole chain |
| `PARTITION` | `batch` | `batch` = 4 h, `batch_long` = 8 h, `backfill` = 7 d |
| `TIME` | `04:00:00` | |
Everything from §3.1 passes through (`ARCH_NET`, `EXTRA_ARGS`, `WANDB_API_KEY`, …).
Sizing: at 4 nodes an epoch is ~3.5 h (HRM), ~2 h (transformer), ~6 h (UT /
loop_cot). Each 4-hour segment nets ~3.3 h of training after container start
and `torch.compile`. `N_JOBS = ceil(total_hours / 3.3) + 2` is a safe rule.
### 3.3 Resume semantics
Two granularities, both automatic (`RESUME_AUTO=1`):
* **epoch** — `fsdp2_epoch_N`, written at every epoch end.
* **step** — `fsdp2_step_S`, rolling every `STEP_CKPT_INTERVAL` steps, only the
newest kept, deleted once an epoch checkpoint lands.
On start the script picks the newest **complete** checkpoint (DCP writes
`.metadata` last, so a half-written one is ignored) and restores the step
counter (LR schedule continues), the per-rank carry, and the data position —
the multipack sampler is deterministic, so replaying and skipping the
already-seen batches reproduces the uninterrupted data order bit-for-bit.
Guards: the run refuses to start if the checkpoint's `world_size` or
architecture differ from the current job.
### 3.4 Architectures (`ARCH_NET`)
All are 694.7M parameters at size `L` and share the same PrefixLM/FA3
attention, RMSNorm, SwiGLU and init — so any difference is architectural.
| `ARCH_NET` | Model | Notes |
| --- | --- | --- |
| `hrm` | HRM-Text | 24 layers split into H(12)+L(12), H_cycles=2 × L_cycles=3, BP warmup 2→5 |
| `hrm_fullbp` | HRM-Text, full-BP tail | same model as `hrm`, only the warmup schedule differs: `bp_schedule=[2,3,4,5,8]` — same 20% window, the four partial phases shrink to w/4 each and a terminal FULL-backprop phase (bp_steps=8 = 2 H + 6 L segments) holds for the last 80% of training. When resuming, keep `ARCH_NET=hrm_fullbp`: the arch guard cannot tell it apart from `hrm` (same model class) |
| `transformer` | plain 24-layer transformer | no recurrence |
| `ut` | Universal Transformer | one 24-layer stack × 4 cycles, `z←core(z+x)`, BP warmup 2→4 |
| `looped_tf` | looped transformer | `z←core(z)`, z₀ = token embeddings, no re-injection |
| `loop_cot` | soft-CoT loop **(v1, mis-wired readout — do not use)** | kept only to reproduce the earlier runs |
| `loop_cot_v2` | soft-CoT loop, fixed | `z ← core(z + α·decode(z) + x)`; see §3.5 |
| `trm`, `trm_match_recurrence`, `rins` | other baselines | from upstream |
**Node-count constraint** (all architectures): the multipack sampler needs
`GLOBAL_BATCH_SIZE / (NODES×8) ≥ 4096`, and the division must be exact. With
the reference 172032 that allows **1, 2, 3 or 4 nodes only**. The script
validates this and refuses to start otherwise.
### 3.5 `loop_cot_v2` options
`z ← core(z + α·decoded(z) + β·x)` where
`decoded(z) = Σ_v softmax(top-k(z·W_out))_v · scale·W_in[v]` — read out through
`lm_head`, written back through the input embedding.
| Key (`arch.*`) | Default | Meaning |
| --- | --- | --- |
| `cycles` | 4 | loop count |
| `cot_decode_readout` | `lm_head` (`embed` in v1) | which matrix produces the logits |
| `cot_decode_topk` | 128 | 0 = full vocab; cost ≈ +9 % (k=16) … +19 % (k=128) … +34 % (k=256) |
| `cot_alpha_fixed_per_cycle` | `[0.0,null,null,null]` | per cycle: constant, or `null` = learned gate. `0.0` also skips that cycle's decode |
| `cot_alpha_per_cycle_params` | `true` | each learned cycle gets its own gate vector |
| `cot_alpha_activate_after_warmup` | `true` | α ≡ 0 until BP warmup ends, then gates switch on at `cot_alpha_init` |
| `cot_alpha_init` | 0.5 | |
| `cot_beta_fixed` | 1.0 | constant β (1.0 = UT-style hard injection); `null` = learned gate |
| `cot_gate_mode` | `dynamic` | per-token sigmoid gate; `scalar` = one learned scalar |
---
## 4. Evaluation
### 4.1 Held-out eval loss — `slurm/eval_loss.sbatch`
Scores **every** epoch checkpoint of a run on the held-out split, with both raw
and EMA weights, in one 2-node job (~1 min/epoch).
```bash
CKPT=checkpoints/HRM-Text/my-run sbatch --export=ALL slurm/eval_loss.sbatch
CKPT=… EVAL_DATA=/lustre/…/other_split sbatch --export=ALL --nodes=4 slurm/eval_loss.sbatch
```
Metrics (identical definition to the `train/*` metrics in wandb, so the curves
are directly comparable):
* `loss` — mean cross-entropy per **supervised** token. With `target_only=true`
only response tokens count; the whole instruction (BOQ, condition tag,
question, EOQ) and padding are masked out.
* `accuracy` — greedy top-1 hit rate on those tokens.
* `exact_accuracy` — fraction of samples whose response is correct at **every**
token.
* `cot_stats` (loop_cot only) — per cycle: the L2 norms of the three input
channels (`z`, `α·decoded`, `β·x`) and the mean gate values.
* `alpha_hist` (loop_cot only) — 50-bin per-token histogram of α over the whole
eval set.
Results are merged into `<CKPT>/eval_loss.json`, keyed by epoch.
### 4.2 Benchmarks
Ten benchmarks: GSM8k, MATH, AIME, DROP, MMLU, MMLU-Pro, ARC, HellaSwag,
Winogrande, BoolQ. GSM8k/MATH are **zero-shot CoT** (`condition="synth,cot"`);
the rest are few-shot with `condition="direct"`. Prompts are sharded across the
8 GPUs and scored by the upstream code, so results match the single-GPU path.
```bash
# non-blocking (preferred)
CKPT=checkpoints/HRM-Text/my-run CKPT_EPOCH=4 sbatch --export=ALL slurm/eval_bench.sbatch
# blocking / interactive
./slurm/eval.sh checkpoints/HRM-Text/my-run # newest epoch
CKPT_EPOCH=2 ./slurm/eval.sh checkpoints/HRM-Text/my-run
RUN_ONLY=[GSM8k,MATH] ./slurm/eval.sh checkpoints/HRM-Text/my-run
GPUS=1 EXTRA="generation_config.batch_size=16" ./slurm/eval.sh … # OOM fallback
```
| Variable | Default | Both scripts |
| --- | --- | --- |
| `CKPT_EPOCH` | newest | which epoch to score |
| `RUN_ONLY` | all | e.g. `[GSM8k,MATH]` |
| `GPUS` | 8 | |
| `EXTRA` | — | extra OmegaConf overrides |
| `PARTITION` / `TIME` | `interactive` / `4:00:00` | `eval.sh` only |
Results are merged into `<CKPT>/benchmark_results.json`, keyed by epoch. EMA
weights are used automatically when present.
Runtime: ~15 min for the full suite on 8 GPUs.
### 4.3 Figures
```bash
PY=/lustre/fsw/portfolios/nemotron/users/hengyuf/RL/.venv/bin/python
$PY slurm/plot_trajectories.py # 8 benchmark PNGs + eval-loss + 2x4 panel
$PY slurm/plot_alpha_hist.py <run> [raw|ema] # per-token alpha distribution
```
To add a run to the figures, append `(label, run_dir, color)` to `SERIES` in
`slurm/plot_trajectories.py` (colors come from a CVD-validated palette; keep
the order fixed so a run never changes color).
---
## 5. Data pipeline (already done; here for reproduction)
The corpus is 178.6B tokens, far too large to materialize per node, so the
sampled epochs are **compacted**: only the token spans the 4 epochs actually
reference are kept (22.7 %) and the indices are remapped. The training stream
is bit-identical to running upstream's sampler on every node.
```bash
# 1. cleaned corpus (350 GB) — to node-local disk, not lustre
hf download sapientinc/HRM-Text-data-io-cleaned-20260515 --repo-type dataset \
--local-dir /tmp/hengyuf/hrm_cleaned --max-workers 8
# 2. tokenize — use THIS, not data_io's Rust tool (which is file-parallel only:
# its 16.9 GB parquet takes 12 h single-threaded; this takes ~1 h total)
python slurm/py_tokenize.py /tmp/hengyuf/hrm_cleaned/{data,data_clustered} \
-t <data_io>/trained_tokenizers/bpe/tokenizer.json \
-o /tmp/hengyuf/data_tokenized_bpe_65k --workers 8 --rayon-threads 16
# 3. sample + compact (RNG call-for-call identical to data_io/sample_tokenized.py)
python slurm/sample_and_compact.py \
tokenized_path=/tmp/hengyuf/data_tokenized_bpe_65k \
output_path=/tmp/hengyuf/sampled_compact \
prefix_config_path=<data_io>/prefix_config.yaml epochs=4 seed=0
# 4. held-out eval split, sampled from the 77 % the training epochs never touch
python slurm/make_eval_split.py tokenized_path=… output_path=… \
prefix_config_path=… epochs=4 seed=0 eval_seed=1000
```
`train.sbatch` then just copies `SAMPLED_SRC` into each node's `/dev/shm`
(a few minutes; skipped when the node already has it).
---
## 6. Utilities
| Script | Purpose |
| --- | --- |
| `slurm/test_decode.py` | fp64 reference check of loop_cot's decode (algorithm exactness, bf16 error decomposition) |
| `slurm/bench_decode_overhead.sbatch` | sweeps `cot_decode_topk` and measures the training-step overhead |
| `slurm/watch_and_eval.sh <run>` | polls for new epoch checkpoints and submits both evals. **Unreliable on the login node** — long-running processes get reaped, even with `setsid`. Verify with `pgrep -af "^/bin/bash \./slurm/watch_and_eval"`; prefer evaluating manually. |
| `slurm/prefix_config_smoke.yaml` | 20 rows/task sampling config for smoke tests |
Smoke test before any long run (2 nodes, ~10 min, exercises compile, the BP
warmup transition, checkpointing and resume):
```bash
ARCH_NET=<net> SAMPLED_SRC=$BASE/hrm_data/sampled_smoke_ep4_seed0 \
RUN_NAME=smoke-x PROJECT_NAME=HRM-Text-smoke STEP_CKPT_INTERVAL=0 \
sbatch --export=ALL --partition=interactive --nodes=2 --time=0:45:00 slurm/train.sbatch
```
---
## 7. Cluster gotchas (all hard-won; don't "simplify" these away)
1. **`NVIDIA_VISIBLE_DEVICES=all` must be set outside `srun`.** enroot injects
the GPU driver when the container is *created*; exporting it inside the
container is too late and you get "no NVIDIA driver".
2. **`HF_HOME` must be re-exported inside the container.** A cluster enroot hook
overwrites it with a root-owned path at creation time.
3. **`interactive` allows at most 2 nodes per user**; `batch` is 4 h.
4. **Don't use `[ cond ] && cmd` as the last statement under `set -e`** — a false
condition returns 1 and silently kills the script (this once made five jobs
die with empty logs).
5. **vllm in the image is broken** (built against CUDA 13, image ships 12.8).
`evaluation/engines.py` imports it lazily so the HRM path is unaffected.
6. **lustre quota is shared** across `nemotron_agents_dev`
(`lfs quota -h -p 10581 /lustre/fsw`). Keep bulk intermediates on node-local
`/tmp` or `/raid`.
7. **enroot import needs `no_proxy='*'`** — the cluster's container-cache proxy
presents a self-signed certificate.
8. **`hf download` with many workers stalls**; use `--max-workers 8` and expect
to restart (it resumes).
---
## 8. Experiment status
Reproduction of the reference L run is complete — epoch 4 lands within 0.5 pp
of the published numbers on average:
| Benchmark | our HRM ep4 | published | Δ |
| --- | ---: | ---: | ---: |
| GSM8k | 79.0 | 77.6 | +1.4 |
| MATH | 51.0 | 51.2 | −0.2 |
| DROP | 78.5 | 78.6 | −0.1 |
| MMLU | 56.7 | 56.6 | +0.1 |
| ARC-C | 75.2 | 75.9 | −0.7 |
| HellaSwag | 53.1 | 52.7 | +0.4 |
| Winogrande | 66.5 | 67.6 | −1.1 |
| BoolQ | 85.2 | 85.0 | +0.2 |
Ablations at equal parameters (694.7M), identical data order and identical
hyperparameters — final eval loss (EMA), lower is better:
| Run | ep1 | ep2 | ep3 | ep4 |
| --- | ---: | ---: | ---: | ---: |
| `transformer` | 1.4145 | 1.3305 | 1.2963 | 1.2781 |
| `hrm` | 1.3629 | 1.2569 | 1.2216 | 1.2033 |
| `ut` | 1.3277 | 1.2394 | 1.2096 | **1.1931** |
| `loop_cot_v2` | **1.3256** | **1.2316** | — | — |
| `loop_cot_b1` (mis-wired) | 1.3520 | 1.2680 | 1.2325 | 1.2140 |
| `loop_cot_a011` (mis-wired, α≡1) | 1.4482 | 1.3386 | — | — |
Takeaways so far: recurrence is what matters (all looped variants ≫
`transformer`); HRM's H/L split buys nothing over a plain shared-weight loop
(`ut` ≈ `hrm`); and the soft-CoT channel only helps once it reads out through
`lm_head` (`loop_cot_v2` > `ut` > `loop_cot_b1`).