#!/bin/bash
# E7（L3）两机 16 卡 Qwen3-30B-A3B 训练吞吐。用法：
#   BACKEND=alltoall|deepep|hybridep MODE=B0|B1|B2 [ITERS=40] [NSYS=1] bash train_moe.sh
# B0：默认（无 permute fusion）；B1：所有 backend 同样开 permute fusion + router fusion；
# B2：在 B1 上按 backend 调参（EXTRA 传入，如 --moe-flex-dispatcher-num-sms 32）。
ROOT=/root/paddlejob/amfp-public/weiziyang/moe_dispatcher
BACKEND=${BACKEND:-alltoall}
MODE=${MODE:-B0}
ITERS=${ITERS:-40}
GBS=${GBS:-64}
SEQ=${SEQ:-4096}
TAG=${TAG:-E7-$MODE-$BACKEND}
HF_CKPT=/root/paddlejob/amfp-public/weiziyang/models/Qwen3-30B-A3B
DATA=/root/paddlejob/amfp-public/weiziyang/data/fineweb-edu/megatron/fineweb_edu_000_text_document
OUT=$ROOT/bench/results/train/$TAG
mkdir -p $OUT

case $BACKEND in
  alltoall) DISP="--moe-token-dispatcher-type alltoall" ;;
  deepep|hybridep) DISP="--moe-token-dispatcher-type flex --moe-flex-dispatcher-backend $BACKEND" ;;
esac
case $MODE in
  B0) TUNE="" ;;
  B1|B2) TUNE="--moe-permute-fusion --moe-router-fusion" ;;
esac

ARGS="--num-layers 48 --hidden-size 2048 --ffn-hidden-size 6144 --num-attention-heads 32
  --group-query-attention --num-query-groups 4 --kv-channels 128 --qk-layernorm
  --normalization RMSNorm --norm-epsilon 1e-6 --swiglu --disable-bias-linear
  --untie-embeddings-and-output-weights --position-embedding-type rope --rotary-base 1000000
  --rotary-percent 1.0 --max-position-embeddings 40960 --make-vocab-size-divisible-by 1187
  --num-experts 128 --moe-ffn-hidden-size 768 --moe-router-topk 8 --moe-router-dtype fp32
  --moe-router-load-balancing-type aux_loss --moe-aux-loss-coeff 1e-3 --moe-grouped-gemm
  $DISP $TUNE ${EXTRA:-}
  --tensor-model-parallel-size 1 --pipeline-model-parallel-size 1 --expert-model-parallel-size 16
  --seq-length $SEQ --micro-batch-size 1 --global-batch-size $GBS
  --bf16 --use-distributed-optimizer --overlap-grad-reduce --overlap-param-gather
  --transformer-impl transformer_engine --cross-entropy-loss-fusion
  --lr 1e-6 --min-lr 1e-6 --lr-decay-style constant --lr-warmup-iters 0 --weight-decay 0.1
  --clip-grad 1.0 --adam-beta1 0.9 --adam-beta2 0.95 --init-method-std 0.02
  --train-iters $ITERS --eval-iters 0 --eval-interval 1000000 --log-interval 1 --log-throughput
  --tokenizer-type HuggingFaceTokenizer --tokenizer-model $HF_CKPT --data-path $DATA --split 100,0,0
  --distributed-timeout-minutes 30 --seed 1234 --manual-gc --manual-gc-interval 10
  --tensorboard-dir $OUT/tb"
if [[ ${NSYS:-0} == 1 ]]; then
  ARGS="$ARGS --profile --profile-step-start ${PROF_START:-20} --profile-step-end ${PROF_END:-22} --profile-ranks 0 8"
  PRE="nsys profile -t cuda,nvtx,osrt -s none --capture-range=cudaProfilerApi --capture-range-end=stop -f true -o $OUT/nsys_node\$RANK"
fi
echo "$ARGS" > $OUT/args.txt
LOG=$OUT/train HF_CKPT=$HF_CKPT bash $ROOT/bench/scripts/run_2node.sh \
  "export HF_CKPT=$HF_CKPT; ${PRE:-} torchrun --nnodes \$WORLD_SIZE --node-rank \$RANK --master-addr \$MASTER_ADDR --master-port \$MASTER_PORT --nproc-per-node 8" \
  "$ROOT/bench/scripts/train_moe.py $(echo $ARGS)"
grep -E 'iteration +[0-9]+/' $OUT/train.node0.log | tail -3
