File size: 11,805 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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | #!/usr/bin/env bash
#SBATCH --job-name=27b_prm_eval
#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=3-0:00:00
#SBATCH --gpus=8
#SBATCH --cpus-per-gpu=4
#SBATCH --mem-per-gpu=48GB
#SBATCH --account=chaijy2
# Produces the same clemscore + statscore as `playpen eval --suite all` for two models:
# - Baseline: Qwen3.5-27B-Instruct-4bit (greedy, no PRM)
# - Guided: Qwen3.5-27B-sft-ep1-4bit + PRM (best-of-N)
#
# GPU layout (dynamic — handles any node count and uneven GPU splits):
# Phase 1 (all GPUs in parallel across all nodes):
# Global shards 0 .. HALF-1: baseline (first half of GPUs)
# Global shards HALF .. WORLD_GPUS-1: guided (second half of GPUs)
# Phase 2 (2 GPUs on head node, after Phase 1):
# GPU 0: static eval for baseline
# GPU 1: static eval for guided
# Phase 3 (CPU): merge shards, score, compute clemscore via clemeval, print comparison
set -euo pipefail
WORKDIR="/nfs/turbo/coe-chaijy-unreplicated/josuetf/LMPlayschool/playpen"
CONDA_ENV="playpen"
export BASE_MODEL="${BASE_MODEL:-Qwen3.5-27B-Instruct-4bit}"
export GUIDED_MODEL="${GUIDED_MODEL:-Qwen3.5-27B-sft-ep1-4bit}"
export PRM_PATH="${PRM_PATH:-models/prm/Qwen3.5-27B-sft-ep1-4bit-1024-full/bench}"
export N_CANDIDATES="${N_CANDIDATES:-4}"
export RESULTS_DIR="${RESULTS_DIR:-eval-results-27b-cmp}"
# Separate shard dirs per side to avoid shard-dir naming conflicts.
# prm_eval.py redirects each shard to {RESULTS_DIR}_shard{N}/{RESULTS_DIR}/
export BASE_RESULTS_DIR="${RESULTS_DIR}-base"
export GUIDED_RESULTS_DIR="${RESULTS_DIR}-guided"
cd "$WORKDIR"
mkdir -p slurm logs
source "$(conda info --base)/etc/profile.d/conda.sh"
conda activate "$CONDA_ENV"
export PYTHONNOUSERSITE=1
export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}"
# -----------------------------------------------------------------------
# Topology detection — works for single-node and multi-node allocations
# with uniform or uneven GPU counts per node.
# -----------------------------------------------------------------------
if [ -n "${SLURM_JOB_ID:-}" ]; then
NNODES="${SLURM_NNODES:-1}"
# Try scontrol first; fall back to SLURM_GPUS env vars
total_gpus=""
if command -v scontrol &>/dev/null; then
total_gpus="$(scontrol show job "$SLURM_JOB_ID" 2>/dev/null \
| grep -oE 'gres/gpu=[0-9]+' | head -1 \
| grep -oE '[0-9]+' || true)"
fi
[ -z "$total_gpus" ] && total_gpus="${SLURM_GPUS:-}"
total_gpus="${total_gpus##*:}" # strip optional "type:" prefix
case "$total_gpus" in
''|*[!0-9]*) total_gpus=$(( ${SLURM_GPUS_ON_NODE:-$(nvidia-smi -L 2>/dev/null | wc -l)} * NNODES )) ;;
esac
else
NNODES=1
total_gpus=$(nvidia-smi -L 2>/dev/null | wc -l)
fi
[ "${total_gpus:-0}" -ge 1 ] || total_gpus=1
GPUS_PER_NODE=$(( total_gpus / NNODES ))
[ "$GPUS_PER_NODE" -ge 1 ] || GPUS_PER_NODE=1
# Probe actual GPU count on each node (handles uneven configs: e.g. 3+5).
# NODE_OFFSETS is a space-separated list: offset[i] = sum of GPUs on nodes 0..(i-1).
NODE_OFFSETS=""
WORLD_GPUS=0
if [ "$NNODES" -gt 1 ]; then
_probe="$(srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
bash -c 'echo "$SLURM_NODEID $(nvidia-smi -L 2>/dev/null | wc -l)"' \
2>/dev/null | sort -n || true)"
_acc=0
while read -r _nid _cnt; do
[ -n "${_cnt:-}" ] || continue
NODE_OFFSETS="$NODE_OFFSETS $_acc"
_acc=$(( _acc + _cnt ))
done <<< "$_probe"
WORLD_GPUS="$_acc"
NODE_OFFSETS="${NODE_OFFSETS# }"
fi
# Single-node fallback (or if probe returned nothing)
if [ -z "$NODE_OFFSETS" ] || [ "$WORLD_GPUS" -lt 1 ]; then
_acc=0
for (( _n=0; _n<NNODES; _n++ )); do
NODE_OFFSETS="$NODE_OFFSETS $_acc"
_acc=$(( _acc + GPUS_PER_NODE ))
done
WORLD_GPUS=$(( NNODES * GPUS_PER_NODE ))
NODE_OFFSETS="${NODE_OFFSETS# }"
fi
# Split global GPU IDs: first half → baseline, second half → guided
HALF=$(( WORLD_GPUS / 2 ))
[ "$HALF" -ge 1 ] || { echo "ERROR: need at least 2 GPUs total (got $WORLD_GPUS)"; exit 1; }
BASE_SHARDS=$HALF
GUIDED_SHARDS=$(( WORLD_GPUS - HALF ))
export NODE_OFFSETS WORLD_GPUS HALF BASE_SHARDS GUIDED_SHARDS WORKDIR
echo "=============================="
echo "Job ID: ${SLURM_JOB_ID:-<direct>}"
echo "Nodes: $NNODES ($WORLD_GPUS total GPUs)"
echo "Offsets: $NODE_OFFSETS"
echo "Baseline: $BASE_MODEL ($BASE_SHARDS shards, global IDs 0..$((HALF-1)))"
echo "Guided: $GUIDED_MODEL + PRM ($GUIDED_SHARDS shards, global IDs $HALF..$((WORLD_GPUS-1)))"
echo "PRM: $PRM_PATH (n-candidates=$N_CANDIDATES, max-tokens=2048)"
echo "Base dir: $BASE_RESULTS_DIR"
echo "Guided dir:$GUIDED_RESULTS_DIR"
echo "Started: $(date)"
echo "=============================="
# -----------------------------------------------------------------------
# Phase 1: Clem gameplay — all GPUs across all nodes in parallel.
# One srun task per node; each task splits its local GPUs between baseline
# (global shard IDs 0..HALF-1) and guided (global shard IDs HALF..WORLD-1).
# -----------------------------------------------------------------------
echo ""
echo "=== Phase 1: Clem gameplay ($WORLD_GPUS GPU(s) across $NNODES node(s)) ==="
fail=0
srun --ntasks="$NNODES" --ntasks-per-node=1 --gpu-bind=none \
bash -c '
cd "$WORKDIR"
lg=$(nvidia-smi -L 2>/dev/null | wc -l); [ "$lg" -ge 1 ] || lg=1
off=$(echo "$NODE_OFFSETS" | cut -d" " -f$((SLURM_NODEID+1))); [ -n "$off" ] || off=0
pids=()
for (( g=0; g<lg; g++ )); do
gsid=$(( off + g ))
if (( gsid < HALF )); then
log="logs/eval_27b_base_shard$(printf "%02d" $gsid).log"
echo " [node $SLURM_NODEID gpu $g] baseline shard $gsid/$BASE_SHARDS -> $log"
CUDA_VISIBLE_DEVICES=$g \
python examples/trl/prm_eval.py \
--policy-model "$BASE_MODEL" \
--temperature 0.0 \
--max-tokens 300 \
--game-all \
--results-dir "$BASE_RESULTS_DIR" \
--shard-id "$gsid" --num-shards "$BASE_SHARDS" \
--skip-guided --skip-score \
> "$log" 2>&1 &
else
guided_sid=$(( gsid - HALF ))
log="logs/eval_27b_guided_shard$(printf "%02d" $guided_sid).log"
echo " [node $SLURM_NODEID gpu $g] guided shard $guided_sid/$GUIDED_SHARDS -> $log"
CUDA_VISIBLE_DEVICES=$g \
python examples/trl/prm_eval.py \
--prm-path "$PRM_PATH" \
--policy-model "$GUIDED_MODEL" \
--temperature 0.7 \
--max-tokens 2048 \
--game-all \
--results-dir "$GUIDED_RESULTS_DIR" \
--shard-id "$guided_sid" --num-shards "$GUIDED_SHARDS" \
--skip-baseline --n-candidates "$N_CANDIDATES" --skip-score \
> "$log" 2>&1 &
fi
pids+=($!)
done
rc=0
for p in "${pids[@]}"; do wait "$p" || rc=1; done
exit $rc
' || fail=$?
echo "Phase 1 done (fail=$fail) at $(date)"
# -----------------------------------------------------------------------
# Phase 2: Static eval — runs on head node GPU 0 and GPU 1.
# playpen eval --suite static plays static benchmark games and writes
# statscore to {dir}/{model_name}.val.json
# -----------------------------------------------------------------------
echo ""
echo "=== Phase 2: Static eval (GPUs 0,1 on head node) ==="
CUDA_VISIBLE_DEVICES=0 playpen eval "$BASE_MODEL" --suite static -r "$RESULTS_DIR/base-static" \
> "logs/eval_27b_base_static.log" 2>&1 &
CUDA_VISIBLE_DEVICES=1 playpen eval "$GUIDED_MODEL" --suite static -r "$RESULTS_DIR/guided-static" \
> "logs/eval_27b_guided_static.log" 2>&1 &
wait
echo "Phase 2 done at $(date)"
# -----------------------------------------------------------------------
# Phase 3: Merge shard results, score clem games, compute clemscore
# -----------------------------------------------------------------------
echo ""
echo "=== Phase 3: Merge + score ==="
python - <<'PY'
import sys, json, os
from pathlib import Path
sys.path.insert(0, "examples/trl")
from prm_eval import _merge_results, _clem_score
import clemcore.clemeval as clemeval
RESULTS_DIR = os.environ["RESULTS_DIR"]
BASE_RESULTS_DIR = os.environ["BASE_RESULTS_DIR"]
GUIDED_RESULTS_DIR = os.environ["GUIDED_RESULTS_DIR"]
BASE_SHARDS = int(os.environ["BASE_SHARDS"])
GUIDED_SHARDS = int(os.environ["GUIDED_SHARDS"])
BASE_MODEL = os.environ["BASE_MODEL"]
GUIDED_MODEL = os.environ["GUIDED_MODEL"]
base_dir = Path(BASE_RESULTS_DIR)
guided_dir = Path(GUIDED_RESULTS_DIR)
print(f"Merging {BASE_SHARDS} baseline shard(s) into {base_dir} ...")
_merge_results(base_dir, BASE_SHARDS)
print(f"Merging {GUIDED_SHARDS} guided shard(s) into {guided_dir} ...")
_merge_results(guided_dir, GUIDED_SHARDS)
# prm_eval.py with --skip-guided writes to baseline/ subdir; --skip-baseline writes to prm-guided/
baseline_clem = base_dir / "baseline"
guided_clem = guided_dir / "prm-guided"
for label, results in [("baseline", baseline_clem), ("guided", guided_clem)]:
if not results.exists():
print(f"WARNING: {results} not found, skipping scoring")
continue
games = sorted({p.name for p in results.glob("*/epoch_00001/*") if p.is_dir()})
print(f"Scoring {label}: {games}")
for g in games:
_clem_score(results, g)
def get_clemscore(results_path):
if not results_path.exists():
return float("nan")
try:
df = clemeval.perform_evaluation(str(results_path), return_dataframe=True)
return round(df["-, clemscore"][0], 2)
except Exception as e:
print(f" clemeval failed on {results_path}: {e}")
return float("nan")
base_clemscore = get_clemscore(baseline_clem)
guided_clemscore = get_clemscore(guided_clem)
def get_statscore(static_results_dir, model_name):
val_json = static_results_dir / f"{model_name}.val.json"
if val_json.exists():
data = json.loads(val_json.read_text())
return round(data.get("statscore", float("nan")), 2)
return float("nan")
static_base = Path(RESULTS_DIR) / "base-static"
static_guided = Path(RESULTS_DIR) / "guided-static"
base_statscore = get_statscore(static_base, BASE_MODEL)
guided_statscore = get_statscore(static_guided, GUIDED_MODEL)
print()
print("=" * 60)
print(f"{'':30s} {'Baseline':>10} {'PRM-guided':>10} {'Δ':>6}")
print(f"{'Model':30s} {BASE_MODEL[-10:]:>10} {GUIDED_MODEL[-10:]:>10}")
print("-" * 60)
print(f"{'clemscore':30s} {base_clemscore:>10.2f} {guided_clemscore:>10.2f} {guided_clemscore - base_clemscore:>+6.2f}")
print(f"{'statscore':30s} {base_statscore:>10.2f} {guided_statscore:>10.2f} {guided_statscore - base_statscore:>+6.2f}")
print("=" * 60)
for model, clem_s, stat_s, static_dir in [
(BASE_MODEL, base_clemscore, base_statscore, static_base),
(GUIDED_MODEL, guided_clemscore, guided_statscore, static_guided),
]:
out = static_dir / f"{model}.val.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps({"clemscore": clem_s, "statscore": stat_s}, indent=2))
print(f"Wrote {out}")
PY
echo ""
echo "=============================="
echo "Done: $(date)"
echo "=============================="
exit $fail
|