File size: 13,713 Bytes
8567b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/bin/bash

#SBATCH --job-name=run_sft
#SBATCH --mail-user=josuetf@umich.edu
#SBATCH --mail-type=ALL
#SBATCH --output=/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen/slurm/%x_%j.out
#SBATCH --partition=spgpu
#SBATCH --time=14-0:00:00
#SBATCH --gpus=2
#SBATCH --cpus-per-gpu=2
#SBATCH --mem-per-gpu=48GB
#SBATCH --account=chaijy2
# Account chaijy2 cap: gpu=20, cpu=80, mem=960G (shared across the account).
# Every spgpu node has 8x A40 (46GB). Training is data-parallel (DDP): every GPU
# holds a full 4-bit copy of the model and trains on a different data shard.
# COMMAND: sbatch run_sft.sh        (override knobs as VAR=… sbatch run_sft.sh)
# ============================================================================
# Supervised fine-tuning (QLoRA, 4-bit + LoRA) of Qwen3.5-27B on the pre-filtered
# playpen SFT data (scaling_LLM_search_methods/playpen-sft-data/sft-filtered).
#
# This mirrors the TRAINING half of run_prm.sh: detect whatever topology Slurm
# granted (1 node or many), hold the effective batch constant across any GPU
# count by auto-deriving grad-accum, and launch the trainer as DDP via torchrun
# (multi-node spans nodes with srun+torchrun; single-node uses torchrun
# --standalone; a lone GPU uses plain python).
#
# Data route (DATA_ROUTE): which filtered split to train on. Both were verified
# equal to their filter predicate and pre-split train/dev with no task leakage:
#   positive_score -> outcome != 'aborted' AND Main Score > 0   (19,143 train)
#   non_aborted    -> outcome != 'aborted'                      (24,711 train)
#
# RESUME: re-run with RESUME=1 to continue from the latest epoch checkpoint in
# the output dir (save_strategy='epoch'). Safe on a fresh run (trains from
# scratch if no checkpoint exists).
# ============================================================================

set -euo pipefail

WORKDIR="/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen"
CONDA_ENV="playpen"
# Model to fine-tune. Override LEARNER + HF_BASE to train a different one.
#   default:  Qwen3.5-27B in 4-bit QLoRA.
#   bf16 2B:  LEARNER=Qwen3.5-2B-Instruct-bf16 \
#             HF_BASE=/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-2B \
#             PRECISION=bf16 TRAIN_BATCH_SIZE=8 sbatch --gpus=1 run_sft.sh
# (Keep batch modest even for small models: the causal-LM loss materializes a
#  full-vocab logits tensor [batch x seq x ~152k], which dominates memory and
#  scales with batch regardless of model size — batch 16 OOMs a 46GB A40.)
LEARNER="${LEARNER:-Qwen3.5-27B-Instruct-4bit}"
HF_BASE="${HF_BASE:-/nfs/turbo/coe-chaijy-unreplicated/pre-trained-weights/Qwen3.5-27B}"
# Weights precision: 4bit (QLoRA, for big models on 46GB cards) or bf16 (no
# quantization + LoRA; right for small models like the 2B that fit comfortably).
PRECISION="${PRECISION:-4bit}"

# Which filtered route to train on (positive_score | non_aborted).
DATA_ROUTE="${DATA_ROUTE:-positive_score}"
DATA_DIR="${DATA_DIR:-/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/scaling_LLM_search_methods/playpen-sft-data/sft-filtered/${DATA_ROUTE}}"

# Output tag: keeps THIS run's adapter in its own dir so a prior run is untouched.
RUN_TAG="${RUN_TAG:-${DATA_ROUTE}}"
RUN_NAME="${LEARNER}-${RUN_TAG}"          # e.g. Qwen3.5-27B-Instruct-4bit-positive_score
MODEL_OUT="${MODEL_OUT:-models/sft/${RUN_NAME}}"

# Training knobs.
MAX_LENGTH="${MAX_LENGTH:-1024}"          # tokens/example; longer convos truncated
# Run UNTIL CONVERGENCE: evaluate every epoch and early-stop when the val loss
# stops improving for EARLY_STOPPING_PATIENCE epochs; the best epoch is kept.
# MAX_EPOCHS is just a backstop cap — training almost always stops well before it.
MAX_EPOCHS="${MAX_EPOCHS:-50}"
EARLY_STOPPING_PATIENCE="${EARLY_STOPPING_PATIENCE:-5}"
LEARNING_RATE="${LEARNING_RATE:-2e-4}"    # standard QLoRA LR
# Per-device train batch. 4 fits a 27B 4-bit + LoRA on a 46GB A40 at max-length
# 1024 (the full-vocab logits for causal-LM loss are the memory driver; batch 8
# OOMs). grad-accum is AUTO-derived after topology detection so the effective
# batch stays constant (TRAIN_EFFECTIVE_BATCH) for any GPU/node count.
TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-4}"
TRAIN_GRAD_ACCUM="${TRAIN_GRAD_ACCUM:-}"
TRAIN_EFFECTIVE_BATCH="${TRAIN_EFFECTIVE_BATCH:-128}"

# Weights & Biases logging. WANDB=0 disables it (report_to=none). WANDB_PROJECT
# groups runs; WANDB_RUN_NAME defaults to the run tag + job id. If no API key /
# credentials are found we drop to OFFLINE mode (logs to ./wandb, sync later with
# `wandb sync`) so a multi-day job never blocks or dies on a missing login.
WANDB="${WANDB:-1}"
WANDB_PROJECT="${WANDB_PROJECT:-playpen-sft}"
WANDB_RUN_NAME="${WANDB_RUN_NAME:-${RUN_NAME}-${SLURM_JOB_ID:-local}}"

cd "$WORKDIR"
mkdir -p logs slurm

# Activate conda
source "$(conda info --base)/etc/profile.d/conda.sh"
conda activate "$CONDA_ENV"

# Ignore ~/.local user-site packages. A stale/broken `wandb` lives there and
# user-site SHADOWS the conda env on sys.path, so without this every rank imports
# that broken wandb when TRL calls is_wandb_available() and dies with the
# protobuf "Descriptors cannot be created directly" error. Everything the trainer
# needs (torch/trl/transformers/peft/datasets/wandb) is in the env, so excluding
# user-site is safe and uses the env's healthy wandb 0.28.0.
export PYTHONNOUSERSITE=1

# --- W&B preflight: decide report backend + mode before launching ---------
REPORT_TO="none"
if [ "$WANDB" = "1" ]; then
    if python -c "import wandb" 2>/dev/null; then
        REPORT_TO="wandb"
        export WANDB_PROJECT
        [ -n "${WANDB_ENTITY:-}" ] && export WANDB_ENTITY
        # Pick a mode: honor an explicit WANDB_MODE; else online only if creds
        # exist (env key or ~/.netrc), otherwise offline so it can't block.
        if [ -z "${WANDB_MODE:-}" ]; then
            if [ -n "${WANDB_API_KEY:-}" ] || grep -q 'api.wandb.ai' "${HOME}/.netrc" 2>/dev/null; then
                export WANDB_MODE=online
            else
                export WANDB_MODE=offline
                echo "NOTE: no W&B credentials found -> WANDB_MODE=offline (logs to ./wandb;"
                echo "      run 'wandb login' then 'wandb sync wandb/offline-run-*' to upload)."
            fi
        else
            export WANDB_MODE
        fi
        echo "W&B:       project=$WANDB_PROJECT  run=$WANDB_RUN_NAME  mode=$WANDB_MODE"
    else
        echo "NOTE: WANDB=1 but the 'wandb' package isn't importable -> logging disabled."
    fi
fi

# Curb CUDA reserved-pool fragmentation so the high-water mark tracks live usage.
export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"

# ------------------------------------------------------------------
# Cluster topology — adapt to WHATEVER Slurm granted (1 node or many). DDP fans
# out over $WORLD_GPUS = $NNODES x $GPUS_PER_NODE. Multi-node reaches other nodes
# via srun (bash `&` can't); single node keeps the local fan-out. Outside Slurm
# -> 1 local node. (Same derivation as run_prm.sh.)
# ------------------------------------------------------------------
if [ -n "${SLURM_JOB_ID:-}" ]; then
    NNODES="${SLURM_NNODES:-1}"
    # Derive the TOTAL GPU count from scontrol (AllocTRES gres/gpu=N), not
    # SLURM_GPUS_ON_NODE — with `--gpus=N` (a per-JOB total) the latter is
    # unreliable (often 1), which silently under-uses GPUs and shrinks the
    # effective batch.
    total_gpus="$(scontrol show job "$SLURM_JOB_ID" 2>/dev/null \
                   | grep -oE 'gres/gpu=[0-9]+' | head -1 | grep -oE '[0-9]+')"
    [ -n "$total_gpus" ] || total_gpus="${SLURM_GPUS:-}"
    total_gpus="${total_gpus##*:}"   # "a40:8" -> "8"
    case "$total_gpus" in ''|*[!0-9]*) total_gpus=$(( ${SLURM_GPUS_ON_NODE:-$(nvidia-smi -L 2>/dev/null | wc -l)} * NNODES )) ;; esac
    GPUS_PER_NODE=$(( total_gpus / NNODES ))
    HEAD_NODE="$(scontrol show hostnames "${SLURM_JOB_NODELIST:-}" 2>/dev/null | head -1)"
else
    NNODES=1
    GPUS_PER_NODE="$(nvidia-smi -L 2>/dev/null | wc -l)"
    HEAD_NODE="$(hostname)"
fi
case "$GPUS_PER_NODE" in ''|*[!0-9]*) GPUS_PER_NODE=1 ;; esac
[ "$GPUS_PER_NODE" -ge 1 ] || GPUS_PER_NODE=1
[ -n "$HEAD_NODE" ] || HEAD_NODE="$(hostname)"
WORLD_GPUS=$(( NNODES * GPUS_PER_NODE ))
RDZV_PORT="${RDZV_PORT:-29501}"
if [ "$NNODES" -gt 1 ]; then MULTINODE=1; else MULTINODE=0; fi

# Multi-node: probe each node's ACTUAL allocated GPU count (same srun pattern the
# training launch uses) and sum them for the AUTHORITATIVE world size. This makes
# UNEVEN splits correct even when the total isn't divisible by NNODES (e.g. 5+3,
# or 5+2=7): the even-split GPUS_PER_NODE above would otherwise mis-derive
# WORLD_GPUS and skew the effective batch. torchrun still uses each node's own
# local count ($lg) below, so the per-node nproc is always exact.
if [ "$MULTINODE" -eq 1 ]; then
    _probe="$(srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
                 bash -c 'nvidia-smi -L 2>/dev/null | wc -l' 2>/dev/null || true)"
    _acc=0
    while read -r _cnt; do
        case "${_cnt:-}" in ''|*[!0-9]*) continue ;; esac
        _acc=$(( _acc + _cnt ))
    done <<< "$_probe"
    [ "$_acc" -ge 1 ] && WORLD_GPUS="$_acc"   # authoritative total across uneven nodes
fi

# Hold the effective batch constant across any GPU count:
#   effective = per_device_batch * WORLD_GPUS * grad_accum
if [ -z "$TRAIN_GRAD_ACCUM" ]; then
    TRAIN_GRAD_ACCUM=$(( TRAIN_EFFECTIVE_BATCH / (TRAIN_BATCH_SIZE * WORLD_GPUS) ))
    [ "$TRAIN_GRAD_ACCUM" -ge 1 ] || TRAIN_GRAD_ACCUM=1
fi

echo "=============================="
echo "Job ID:    ${SLURM_JOB_ID:-<direct>}"
echo "Node:      ${SLURMD_NODENAME:-$(hostname)}"
echo "GPUs:"
nvidia-smi --query-gpu=index,name,memory.total,memory.used,memory.free --format=csv
echo "Topology:  ${NNODES} node(s) x ${GPUS_PER_NODE} GPU = ${WORLD_GPUS} GPUs  (multinode=${MULTINODE}, head=${HEAD_NODE})"
echo "Data:      $DATA_DIR  (route=$DATA_ROUTE)"
echo "Model:     $LEARNER  ($PRECISION)  <- $HF_BASE"
echo "Output:    $MODEL_OUT"
echo "Train:     per_device=${TRAIN_BATCH_SIZE} x world=${WORLD_GPUS} x grad_accum=${TRAIN_GRAD_ACCUM} = $(( TRAIN_BATCH_SIZE * WORLD_GPUS * TRAIN_GRAD_ACCUM )) effective batch"
echo "           max_length=${MAX_LENGTH}  max_epochs=${MAX_EPOCHS} (early-stop patience=${EARLY_STOPPING_PATIENCE})  lr=${LEARNING_RATE}"
echo "Started:   $(date)"
echo "=============================="

[ -d "$DATA_DIR/train" ] || { echo "ERROR: no train/ split at $DATA_DIR"; exit 1; }

# ------------------------------------------------------------------
# SFT training — DATA-PARALLEL (DDP) across the WHOLE allocation. Every GPU holds
# a full 4-bit copy and trains on a different data shard. Effective batch is held
# at TRAIN_EFFECTIVE_BATCH by the auto-derived grad_accum, so the optimization is
# identical no matter how many GPUs/nodes Slurm granted.
# ------------------------------------------------------------------
train_args=(
    --data-dir "$DATA_DIR"
    --model "$HF_BASE"
    --output "$MODEL_OUT"
    --per-device-batch-size "$TRAIN_BATCH_SIZE"
    --gradient-accumulation-steps "$TRAIN_GRAD_ACCUM"
    --max-length "$MAX_LENGTH"
    --max-epochs "$MAX_EPOCHS"
    --early-stopping-patience "$EARLY_STOPPING_PATIENCE"
    --learning-rate "$LEARNING_RATE"
    --report-to "$REPORT_TO"
    --run-name "$WANDB_RUN_NAME"
)
# bf16 precision -> load unquantized + LoRA (no 4-bit). Right for small models.
[ "$PRECISION" = "bf16" ] && train_args+=(--no-4bit)
# Fast smoke test: LIMIT_TRAIN_SAMPLES=256 MAX_EPOCHS=1 sbatch --gpus=1 ... run_sft.sh
[ -n "${LIMIT_TRAIN_SAMPLES:-}" ] && train_args+=(--limit-train-samples "$LIMIT_TRAIN_SAMPLES")
[ "${RESUME:-0}" = "1" ] && train_args+=(--resume)

echo ""
echo "=== SFT Training: QLoRA (4-bit + LoRA) as DDP across $WORLD_GPUS GPU(s) on $NNODES node(s) ==="
# Per-RUN log so concurrent SFT runs (e.g. 27B + 2B) don't clobber each other's
# output. sft_progress.sh finds it from this run's Output dir.
TRAIN_LOG="logs/sft_${RUN_NAME}.log"
echo "Train log: $TRAIN_LOG"
train_fail=0
if [ "$MULTINODE" -eq 1 ]; then
    # One agent per node (srun -> 1 task/node, --gpu-bind=none so the task sees
    # ALL that node's GPUs). Each node runs torchrun with ITS OWN local GPU count
    # (nvidia-smi), so an uneven split (e.g. 5+3) still rendezvous-sums to the
    # global world size. Training args after `-c bash` arrive as "$@".
    srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
        bash -c 'lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
                 exec torchrun --nnodes='"$NNODES"' --nproc-per-node="$lg" \
                      --rdzv-backend=c10d --rdzv-id='"$SLURM_JOB_ID"' \
                      --rdzv-endpoint='"$HEAD_NODE:$RDZV_PORT"' \
                      examples/trl/sft_train_from_filtered.py "$@"' \
        bash "${train_args[@]}" \
        > "$TRAIN_LOG" 2>&1 || train_fail=1
elif [ "$WORLD_GPUS" -gt 1 ]; then
    # Single node, multiple GPUs: standalone DDP.
    torchrun --standalone --nnodes=1 --nproc-per-node="$GPUS_PER_NODE" \
             examples/trl/sft_train_from_filtered.py "${train_args[@]}" \
        > "$TRAIN_LOG" 2>&1 || train_fail=1
else
    python examples/trl/sft_train_from_filtered.py "${train_args[@]}" \
        > "$TRAIN_LOG" 2>&1 || train_fail=1
fi

if [ "$train_fail" -ne 0 ]; then
    echo "  SFT training: FAILED (see $TRAIN_LOG)"
    tail -n 30 "$TRAIN_LOG" 2>/dev/null | sed 's/^/    /' || true
    exit 1
fi

echo "  SFT training: OK"
echo ""
echo "Training finished at: $(date)"
echo "Adapter saved to:     $MODEL_OUT"
echo "=============================="
echo "Done: $(date)"
echo "=============================="