File size: 13,466 Bytes
23c39b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/bin/bash
#SBATCH --job-name=hrm-text-L
#SBATCH --account=nemotron_agents_dev
#SBATCH --partition=backfill
#SBATCH --nodes=2
#SBATCH --ntasks-per-node=1
#SBATCH --gpus-per-node=8
#SBATCH --mem=0
#SBATCH --exclusive
#SBATCH --time=36:00:00
#SBATCH --output=/lustre/fsw/portfolios/nemotron/users/hengyuf/HRM-Text/slurm/logs/%x_%j.out

# =============================================================================
# HRM-Text L (0.6B) multi-node pretraining launcher.
#
# Reproduces the reference L run:
#   torchrun --nproc_per_node=8 pretrain.py arch/size@arch=L lr=2.5e-4 global_batch_size=172032
#
# Node count / partition are free to change at submit time and DO NOT affect
# training hyperparameters (global batch size is in tokens and stays fixed;
# LR schedule and total steps depend only on data + epochs + global batch).
#
# Data: SAMPLED_SRC points to a pre-sampled+compacted dataset on lustre
# (produced once by slurm/sample_and_compact.py from the tokenized corpus,
# identical training stream to running data_io/sample_tokenized.py on each
# node — see slurm/README.md). Step 1 just copies it into /dev/shm.
#
# Usage:
#   sbatch slurm/train.sbatch                                    # 2 nodes, backfill
#   sbatch --nodes=4 --partition=backfill --time=1-12:00:00 slurm/train.sbatch
#   RUN_NAME=myrun EXTRA_ARGS="+lr_min_ratio=1.0" sbatch --export=ALL slurm/train.sbatch
#   (EXTRA_ARGS are hydra overrides; keys NOT present in cfg_pretrain.yaml
#    need a '+' prefix.)
#
# HARD CONSTRAINT (multipack sampler): per-rank token budget
#   global_batch_size / (nodes*8) must be >= max sequence length (4096),
#   and global_batch_size must divide evenly by nodes*8.
#   => With global_batch_size=172032 (= 2^13*3*7): valid node counts are
#      1, 2, 3, 4. More nodes CANNOT keep the reference hyperparameters
#      (e.g. 8 nodes -> 2688 tokens/rank < 4096).
#   This script validates and refuses to start if violated.
#
# NOTE: mid-run resume is NOT supported by pretrain.py (optimizer/data state
# restart from step 0). Budget wall-time for the full run: ~50h on 1 node,
# ~26h on 2 nodes, ~14h on 4 nodes.
# =============================================================================

set -euo pipefail

# ---------------- Paths (override via env) ----------------
BASE=${BASE:-/lustre/fsw/portfolios/nemotron/users/hengyuf}
HRM_DIR=${HRM_DIR:-$BASE/HRM-Text}
SAMPLED_SRC=${SAMPLED_SRC:-$BASE/hrm_data/sampled_ep4_seed0}
SQSH=${SQSH:-$BASE/hrm_env/hrm-text.sqsh}
SAMPLED_PATH=${SAMPLED_PATH:-/dev/shm/sampled}
LOG_DIR=$HRM_DIR/slurm/logs

# ---------------- Reference L hyperparameters ----------------
# Keep these fixed when scaling node count. Everything else about the
# schedule (epochs=4, lr_min_ratio=1.0, warmup=2000, wd=0.1, betas, EMA)
# comes from config/cfg_pretrain.yaml and is identical to the reference.
ARCH_NET=${ARCH_NET:-hrm}                        # hrm | hrm_fullbp | transformer | ut | looped_tf | loop_cot | loop_cot_v2 | trm | rins
ARCH_SIZE=${ARCH_SIZE:-L}
LR=${LR:-2.5e-4}
GLOBAL_BATCH_SIZE=${GLOBAL_BATCH_SIZE:-172032}   # tokens per optimizer step
EPOCHS=${EPOCHS:-4}                              # must match SAMPLED_SRC epochs
SEED=${SEED:-0}
EXTRA_ARGS=${EXTRA_ARGS:-}                       # extra hydra overrides for pretrain.py
STEP_CKPT_INTERVAL=${STEP_CKPT_INTERVAL:-5000}   # rolling mid-epoch ckpt every N steps (0 disables)

# ---------------- In-training eval (optional) ----------------
# EVAL_DATA_SRC: held-out split evaluated on the LIVE weights every
# EVAL_INTERVAL steps; eval/loss etc. land in the SAME wandb run as the
# train metrics. Read straight from lustre (tiny, mmap) — no /dev/shm copy.
EVAL_DATA_SRC=${EVAL_DATA_SRC:-}
EVAL_INTERVAL=${EVAL_INTERVAL:-1000}

# ---------------- Run naming ----------------
GPUS_PER_NODE=${GPUS_PER_NODE:-8}
PROJECT_NAME=${PROJECT_NAME:-HRM-Text}
RUN_NAME=${RUN_NAME:-${ARCH_NET}-${ARCH_SIZE}-${SLURM_JOB_NUM_NODES}n-job${SLURM_JOB_ID}}
CHECKPOINT_PATH=${CHECKPOINT_PATH:-$HRM_DIR/checkpoints/$PROJECT_NAME/$RUN_NAME}

# ---------------- W&B ----------------
# Provide WANDB_API_KEY in the submission environment for online logging;
# otherwise the run logs offline to $HRM_DIR/wandb (sync later with `wandb sync`).
if [ -z "${WANDB_API_KEY:-}" ]; then
    export WANDB_MODE=offline
fi

# ---------------- Validation ----------------
WORLD_SIZE=$((SLURM_JOB_NUM_NODES * GPUS_PER_NODE))

if [ ! -f "$SAMPLED_SRC/metadata.json" ] || [ ! -f "$SAMPLED_SRC/tokens.npy" ]; then
    echo "FATAL: sampled dataset not found at $SAMPLED_SRC" >&2
    exit 1
fi
MAX_SEQ_LEN=$(python3 -c "import json;print(json.load(open('$SAMPLED_SRC/metadata.json'))['max_seq_len']-1)")
N_EPOCH_DIRS=$(ls -d "$SAMPLED_SRC"/epoch_* 2>/dev/null | wc -l)
if [ "$N_EPOCH_DIRS" -ne "$EPOCHS" ]; then
    echo "FATAL: SAMPLED_SRC has $N_EPOCH_DIRS epoch dirs but EPOCHS=$EPOCHS" >&2
    exit 1
fi
if (( GLOBAL_BATCH_SIZE % WORLD_SIZE != 0 )); then
    echo "FATAL: global_batch_size=$GLOBAL_BATCH_SIZE not divisible by world_size=$WORLD_SIZE" >&2
    exit 1
fi
LOCAL_BATCH=$((GLOBAL_BATCH_SIZE / WORLD_SIZE))
if (( LOCAL_BATCH < MAX_SEQ_LEN )); then
    echo "FATAL: per-rank token budget $LOCAL_BATCH < max_seq_len $MAX_SEQ_LEN." >&2
    echo "       The multipack sampler cannot pack max-length sequences; the training epoch" >&2
    echo "       would terminate almost immediately. With gbs=$GLOBAL_BATCH_SIZE valid node counts are 1,2,3,4." >&2
    exit 1
fi
if [ ! -f "$SQSH" ]; then
    echo "FATAL: container image not found at $SQSH" >&2
    exit 1
fi

mkdir -p "$LOG_DIR" "$CHECKPOINT_PATH"

# ---------------- Auto-resume (RESUME_AUTO=0 disables) ----------------
# If $CHECKPOINT_PATH already holds completed epochs for this RUN_NAME,
# continue from the latest VALID one (dcp writes .metadata last, so its
# presence marks a complete checkpoint). Enables chained dependent jobs:
# each job picks up where the previous one stopped. Requires same NODES.
RESUME_ARGS=""
if [ "${RESUME_AUTO:-1}" = "1" ]; then
    # NOTE: plain if/then (no `[ ] && cmd`) — a fresh run has no checkpoints,
    # and a trailing failed `&&` would silently kill the script under set -e.
    LAST=""
    for d in "$CHECKPOINT_PATH"/fsdp2_epoch_*/; do
        if [ -f "$d/.metadata" ]; then
            E=$(basename "$d" | sed 's/fsdp2_epoch_//')
            if [ -z "$LAST" ] || [ "$E" -gt "$LAST" ]; then LAST=$E; fi
        fi
    done
    # Rolling mid-epoch (step) checkpoints — newest complete one
    SLAST=""
    for d in "$CHECKPOINT_PATH"/fsdp2_step_*/; do
        if [ -f "$d/.metadata" ]; then
            S=$(basename "$d" | sed 's/fsdp2_step_//')
            if [ -z "$SLAST" ] || [ "$S" -gt "$SLAST" ]; then SLAST=$S; fi
        fi
    done
    if [ -n "${LAST:-}" ] && [ "$LAST" -ge "$EPOCHS" ]; then
        echo "Training already complete (epoch $LAST/$EPOCHS in $CHECKPOINT_PATH). Nothing to do."
        exit 0
    fi
    # Prefer the step checkpoint if it is inside an epoch AFTER the last
    # completed epoch checkpoint (i.e. it represents newer progress).
    SEPOCH=0; SWS=0
    if [ -n "${SLAST:-}" ] && [ -f "$CHECKPOINT_PATH/train_state_step_$SLAST.json" ]; then
        SEPOCH=$(python3 -c "import json;d=json.load(open('$CHECKPOINT_PATH/train_state_step_$SLAST.json'));print(d.get('epoch',0))" 2>/dev/null || echo 0)
        SWS=$(python3 -c "import json;d=json.load(open('$CHECKPOINT_PATH/train_state_step_$SLAST.json'));print(d.get('world_size',0))" 2>/dev/null || echo 0)
    fi
    # Architecture guard: refuse to resume a checkpoint trained with a
    # different arch (e.g. forgetting ARCH_NET=ut when continuing a UT run).
    if [ -f "$CHECKPOINT_PATH/all_config.yaml" ] && { [ -n "${LAST:-}" ] || [ -n "${SLAST:-}" ]; }; then
        CKPT_NET=$(grep -m1 "name: baselines" "$CHECKPOINT_PATH/all_config.yaml" | sed -E 's/.*baselines\.([a-z_0-9]+)@.*/\1/')
        WANT_NET=$(grep -m1 "^name: baselines" "config/arch/net/$ARCH_NET.yaml" | sed -E 's/.*baselines\.([a-z_0-9]+)@.*/\1/')
        if [ -n "$CKPT_NET" ] && [ -n "$WANT_NET" ] && [ "$CKPT_NET" != "$WANT_NET" ]; then
            echo "FATAL: checkpoint in $CHECKPOINT_PATH was trained with arch '$CKPT_NET'," >&2
            echo "       but this job requests ARCH_NET=$ARCH_NET ('$WANT_NET'). Refusing to resume." >&2
            exit 1
        fi
    fi
    if [ "$SEPOCH" -gt "${LAST:-0}" ]; then
        if [ "$SWS" != "0" ] && [ "$SWS" != "$WORLD_SIZE" ]; then
            echo "FATAL: step checkpoint was trained with world_size=$SWS, this job has $WORLD_SIZE." >&2
            exit 1
        fi
        echo "Auto-resume: continuing mid-epoch from step $SLAST (epoch $SEPOCH) in $CHECKPOINT_PATH"
        RESUME_ARGS="+resume_from='$CHECKPOINT_PATH' +resume_step=$SLAST +resume_continue=true"
    elif [ -n "${LAST:-}" ]; then
        CKPT_WS=$(python3 -c "import json;print(json.load(open('$CHECKPOINT_PATH/train_state_epoch_$LAST.json')).get('world_size',0))" 2>/dev/null || echo 0)
        if [ "$CKPT_WS" != "0" ] && [ "$CKPT_WS" != "$WORLD_SIZE" ]; then
            echo "FATAL: checkpoint was trained with world_size=$CKPT_WS, this job has $WORLD_SIZE." >&2
            echo "       resume_continue requires the same node count as the original run." >&2
            exit 1
        fi
        echo "Auto-resume: continuing from epoch $LAST in $CHECKPOINT_PATH"
        RESUME_ARGS="+resume_from='$CHECKPOINT_PATH' +resume_epoch=$LAST +resume_continue=true"
    fi
fi
if [ "$STEP_CKPT_INTERVAL" != "0" ]; then
    RESUME_ARGS="$RESUME_ARGS +checkpoint_step_interval=$STEP_CKPT_INTERVAL"
fi
if [ -n "$EVAL_DATA_SRC" ]; then
    if [ ! -f "$EVAL_DATA_SRC/metadata.json" ]; then
        echo "FATAL: EVAL_DATA_SRC set but no metadata.json at $EVAL_DATA_SRC" >&2
        exit 1
    fi
    RESUME_ARGS="$RESUME_ARGS +eval_data_path='$EVAL_DATA_SRC' +eval_interval=$EVAL_INTERVAL"
fi

# This cluster's job steps don't inject GPUs into pyxis containers on their
# own; the job is --exclusive with all 8 GPUs, so expose them all.
export NVIDIA_VISIBLE_DEVICES=${NVIDIA_VISIBLE_DEVICES:-all}

MASTER_ADDR=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n1)
MASTER_PORT=$((20000 + SLURM_JOB_ID % 10000))

echo "=============================================================="
echo " Job            : $SLURM_JOB_ID ($SLURM_JOB_NUM_NODES nodes x $GPUS_PER_NODE GPUs, world=$WORLD_SIZE)"
echo " Nodes          : $SLURM_JOB_NODELIST (master $MASTER_ADDR:$MASTER_PORT)"
echo " Arch           : $ARCH_NET/$ARCH_SIZE   lr=$LR   gbs=$GLOBAL_BATCH_SIZE tok ($LOCAL_BATCH tok/rank)   epochs=$EPOCHS"
echo " Sampled data   : $SAMPLED_SRC -> $SAMPLED_PATH"
echo " Checkpoints    : $CHECKPOINT_PATH"
echo " W&B            : mode=${WANDB_MODE:-online} project=$PROJECT_NAME run=$RUN_NAME"
echo " Extra args     : $EXTRA_ARGS"
echo "=============================================================="

MOUNTS=/lustre:/lustre,/dev/shm:/dev/shm

# ---------------- Step 1: stage sampled data into /dev/shm on every node ----
# The sampled dataset is identical for all nodes (deterministic, generated
# once). A stamp keyed on the source fingerprint lets warm nodes skip the copy.
STAMP="src=$SAMPLED_SRC meta=$(md5sum "$SAMPLED_SRC/metadata.json" | cut -d' ' -f1) tokens=$(stat -c '%s %Y' "$SAMPLED_SRC/tokens.npy")"
SRC_BYTES=$(du -sb "$SAMPLED_SRC" | cut -f1)

srun --ntasks-per-node=1 \
     --container-image="$SQSH" --container-name=hrm \
     --container-mounts="$MOUNTS" \
     bash -c "
set -euo pipefail
if [ -f '$SAMPLED_PATH/.stamp' ] && [ \"\$(cat '$SAMPLED_PATH/.stamp')\" = '$STAMP' ]; then
    echo \"[\$(hostname)] sampled data up-to-date, skipping copy\"
    exit 0
fi
rm -rf '$SAMPLED_PATH'
SHM_AVAIL=\$(df --output=avail -B1 /dev/shm | tail -1)
NEED=\$(( $SRC_BYTES * 11 / 10 ))
if [ \"\$SHM_AVAIL\" -lt \"\$NEED\" ]; then
    echo \"[\$(hostname)] FATAL: /dev/shm has \$SHM_AVAIL bytes free, need ~\$NEED\" >&2
    exit 1
fi
echo \"[\$(hostname)] copying $SAMPLED_SRC -> $SAMPLED_PATH (\$(( $SRC_BYTES / 1000000000 )) GB)\"
cp -r '$SAMPLED_SRC' '$SAMPLED_PATH'
echo '$STAMP' > '$SAMPLED_PATH/.stamp'
echo \"[\$(hostname)] staging done\"
"

# ---------------- Step 2: multi-node torchrun ----------------
# NOTE: seed/project_name/run_name/checkpoint_path are not keys in
# cfg_pretrain.yaml, so they need hydra's '+' prefix (append).
srun --ntasks-per-node=1 --kill-on-bad-exit=1 \
     --container-name=hrm \
     --container-mounts="$MOUNTS" \
     --container-workdir="$HRM_DIR" \
     bash -c "
set -euo pipefail
export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1
export TORCHINDUCTOR_CACHE_DIR=/dev/shm/inductor_cache TRITON_CACHE_DIR=/dev/shm/triton_cache
# W&B staging/cache default to \$HOME inside the container (tiny node-local
# overlay that can be full) — keep them in /dev/shm instead.
export WANDB_CACHE_DIR=/dev/shm/wandb_cache WANDB_DATA_DIR=/dev/shm/wandb_data
mkdir -p /dev/shm/wandb_cache /dev/shm/wandb_data
torchrun \
    --nnodes=$SLURM_JOB_NUM_NODES \
    --nproc_per_node=$GPUS_PER_NODE \
    --node_rank=\$SLURM_NODEID \
    --rdzv_backend=c10d \
    --rdzv_endpoint=$MASTER_ADDR:$MASTER_PORT \
    --rdzv_id=$SLURM_JOB_ID \
    pretrain.py \
    arch/net@arch=$ARCH_NET \
    arch/size@arch=$ARCH_SIZE \
    lr=$LR \
    global_batch_size=$GLOBAL_BATCH_SIZE \
    epochs=$EPOCHS \
    data.path='$SAMPLED_PATH' \
    +seed=$SEED \
    +project_name='$PROJECT_NAME' \
    +run_name='$RUN_NAME' \
    +checkpoint_path='$CHECKPOINT_PATH' \
    $RESUME_ARGS \
    $EXTRA_ARGS
"