Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added core
Empty file.
3 changes: 3 additions & 0 deletions miles/backends/megatron_utils/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,9 @@ def update_weights(self, info: "EnginesAndLock") -> None:
with torch_memory_saver.disable() if self.args.offload_train else nullcontext():
print_memory("before update_weights")
self.weight_updater.update_weights()
# Reap CUDA-IPC pending frees from any updater path; under
# torch_memory_saver offload nothing else triggers the lazy reap.
torch.cuda.ipc_collect()
Comment thread
Zhichenzzz marked this conversation as resolved.
Resolved
print_memory("after update_weights")

if is_multi_lora_enabled(self.args):
Expand Down
11 changes: 9 additions & 2 deletions miles/backends/megatron_utils/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,13 @@ def forward_step(data_iterator: DataIterator, model: GPTModel, return_schedule_p
}

if args.enable_mtp_training:
forward_kwargs["mtp_kwargs"] = {"mtp_labels": batch["tokens"]}
# Megatron-core's MTP loss expects next-token-shifted labels
# (labels[i] == token[i+1]); it rolls -1 once more per MTP depth.
# Raw tokens would make the MTP target off-by-one and blow up
# mtp_loss against the pretrained MTP head, so pre-shift here.
forward_kwargs["mtp_kwargs"] = {
"mtp_labels": torch.roll(batch["tokens"], shifts=-1, dims=-1)
}

if (x := batch["multimodal_train_inputs"]) is not None:
forward_kwargs.update(x)
Expand Down Expand Up @@ -783,6 +789,7 @@ def train(

mtp_loss_scale = 1 / num_microbatches[step_id]
tracker = MTPLossLoggingHelper.tracker
mtp_losses = None
if "values" in tracker:
values = tracker["values"]
if (x := tracker.get("reduce_group")) is not None:
Expand All @@ -806,7 +813,7 @@ def train(
role_tag = "" if role == "actor" else f"{role}-"

extra_metrics = {}
if args.enable_mtp_training:
if args.enable_mtp_training and mtp_losses is not None:
extra_metrics["mtp_loss"] = mtp_losses

if not disable_optimizer:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,10 @@ def update_weights(self) -> None:
refs, long_lived_tensors = self._send_base_params(hf_named_tensors)
results = ray.get(refs)
_check_weight_sync_results(results, is_lora=False)
# Reap CUDA-IPC pending frees; under torch_memory_saver
# offload nothing else triggers the lazy reap (leaks ~full
# export size per round otherwise).
torch.cuda.ipc_collect()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this needed? in my understanding ipc should be automatically collected in weight update (so other models work well)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

repeated ipc collect, will delete this and that one in sglang

del long_lived_tensors

mm_tower_tensors = self._mm_tower_named_tensors()
Expand Down Expand Up @@ -305,6 +309,8 @@ def update_weights(self) -> None:
_check_weight_sync_results(results, is_lora=True)
del long_lived_tensors
del accumulated_named_tensors
# Reap CUDA-IPC pending frees; under torch_memory_saver
# offload nothing else triggers the lazy reap.
torch.cuda.ipc_collect()
torch.cuda.empty_cache()

Expand Down
14 changes: 12 additions & 2 deletions miles_plugins/megatron_bridge/nemotron_h.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ def provider_bridge(self, hf_pretrained):

if not os.environ.get("MILES_NEMOTRONH_KEEP_MTP"):
provider.mtp_num_layers = None
# finalize() builds the MTP block from mtp_hybrid_override_pattern
# (refs the nonexistent Symbols.MTP_SEPARATOR -> AttributeError);
# clear the pattern too so finalize() skips MTP entirely.
provider.mtp_hybrid_override_pattern = None
return provider

def mapping_registry(self):
Expand Down Expand Up @@ -194,8 +198,14 @@ def _install_mamba_model_loss_mask_shim() -> None:

_orig_forward = MambaModel.forward

def forward(self, *args, loss_mask=None, **kwargs):
return _orig_forward(self, *args, **kwargs)
def forward(self, *args, loss_mask=None, mtp_kwargs=None, **kwargs):
# Route miles' GPT-style mtp_kwargs["mtp_labels"] into MambaModel.forward's
# mtp_labels arg (MTP loss is gated on it, mirroring gpt_model.forward);
# the main path keeps labels=None and returns logits for the PG loss.
mtp_labels = (mtp_kwargs or {}).get("mtp_labels")
return _orig_forward(
self, *args, loss_mask=loss_mask, mtp_labels=mtp_labels, **kwargs
)

MambaModel.forward = forward
MambaModel._miles_loss_mask_shim_installed = True
Expand Down
44 changes: 44 additions & 0 deletions scripts/convert-nemotron-3-ultra-550b-hf-to-dist.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/bin/bash
# Offline HF -> Megatron torch_dist conversion for Nemotron-3-Ultra-550B-A55B.
# Run once; the RL launcher then uses --load <dist> instead of paying the slow
# 512-expert HF bridge mapping on every start.
#
# The conversion layout MUST match the RL run's layout (no reshard at load):
# TP8 PP4 EP32 ETP1 => 128 ranks / 16 nodes (8 GPU each).
#
# Usage on each pod (run on all 16, ranks 0..15; rank 0 == head):
# bash convert-nemotron-3-ultra-550b-hf-to-dist.sh <NODE_RANK 0..15> <HEAD_IP>

set -u
NODE_RANK=${1:?Usage: $0 <node_rank 0..15> <head_ip>}
HEAD_IP=${2:?Usage: $0 <node_rank 0..15> <head_ip>}
NNODES=${NNODES:-16}
PORT=${PORT:-29531}

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
source "${SCRIPT_DIR}/models/nemotron-3-ultra-550b-a55b.sh" # provides MODEL_ARGS

MODELS_DIR=${MODELS_DIR:-/cluster_public/miles_data/models}
# Public HF repo (https://huggingface.co/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16).
# Override HF=<local path> to use a pre-downloaded copy on shared storage.
HF=${HF:-nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16}
SAVE=${SAVE:-$MODELS_DIR/nemotron-3-ultra-550b-a55b_torch_dist}

cd "${SCRIPT_DIR}/.."
export PYTHONPATH=/root/Megatron-LM
export CUDA_DEVICE_MAX_CONNECTIONS=1
mkdir -p "$SAVE"

torchrun --nnodes="$NNODES" --nproc-per-node=8 --node-rank="$NODE_RANK" \
--master-addr="$HEAD_IP" --master-port="$PORT" \
tools/convert_hf_to_torch_dist_bridge.py \
"${MODEL_ARGS[@]}" \
--tensor-model-parallel-size 8 \
--pipeline-model-parallel-size 4 \
--expert-model-parallel-size 32 \
--expert-tensor-parallel-size 1 \
--seq-length 4096 \
--max-position-embeddings 4096 \
--hf-checkpoint "$HF" \
--save "$SAVE" \
--megatron-to-hf-mode bridge
47 changes: 47 additions & 0 deletions scripts/models/nemotron-3-ultra-550b-a55b-4layer.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 4-layer slice of NVIDIA Nemotron-3-Ultra-550B-A55B, for single-node (8 GPU) CI.
#
# Built by cluster_scripts/debug_tool_set/checkpoint/prune_nemotron_h.py, which
# keeps source layers 0,1,7,8 and renumbers them 0..3. That selection is the
# cheapest one covering every block type the full 108-layer model has:
#
# layer 0 mamba layer 1 moe layer 2 attention layer 3 moe -> "ME*E"
# MTP head: attention + moe -> "*E"
#
# A prefix cut would need 8 layers to reach the first attention layer and drag
# in 4 MoE layers (~44B params) instead of 2. Everything else (512 experts,
# top-22, moe_latent_size=2048, sigmoid router + expert bias) is unchanged from
# nemotron-3-ultra-550b-a55b.sh, so the weight-conversion path is identical.

MODEL_ARGS=(
--disable-bias-linear
--group-query-attention
--num-attention-heads 64
--num-query-groups 2
--kv-channels 128
--num-layers 4
--hidden-size 8192
--ffn-hidden-size 5120
--normalization RMSNorm
--position-embedding-type none
--vocab-size 131072
--make-vocab-size-divisible-by 128
--untie-embeddings-and-output-weights

# MoE specifics (identical to the full model)
--num-experts 512
--moe-router-topk 22
--moe-ffn-hidden-size 5120
--moe-shared-expert-intermediate-size 10240
--moe-latent-size 2048
--moe-router-score-function sigmoid
--moe-router-enable-expert-bias
--moe-grouped-gemm
--moe-router-dtype fp32
--moe-router-num-groups 1
--moe-router-group-topk 1
--moe-router-topk-scaling-factor 5.0
--moe-router-pre-softmax
--moe-router-load-balancing-type seq_aux_loss
--moe-router-bias-update-rate 0
--moe-aux-loss-coeff 0
)
51 changes: 51 additions & 0 deletions scripts/models/nemotron-3-ultra-550b-a55b.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# NVIDIA Nemotron-3-Ultra-550B-A55B (BF16, MoE nemotron_h = hybrid Mamba2 + Attention + MoE).
# HF config:
# num_hidden_layers=108 hidden_size=8192 num_attention_heads=64 num_key_value_heads=2
# head_dim=128 intermediate_size=5120 moe_intermediate_size=5120
# n_routed_experts=512 num_experts_per_tok=22 n_shared_experts=1
# moe_shared_expert_intermediate_size=10240 routed_scaling_factor=5.0
# moe_latent_size=2048 n_group=1 topk_group=1 sigmoid routing + aux-free expert bias
# num_nextn_predict_layers=1 (MTP head) mamba n_groups=8
# Same AutoBridge path as Super-120B (--megatron-to-hf-mode bridge) + miles
# NemotronHBridge MoE/latent shim (miles_plugins/megatron_bridge/nemotron_h.py).
# NOTE: Mamba n_groups=8 forces attention/mamba tensor-parallel <= 8 (n_groups % tp == 0).

MODEL_ARGS=(
--disable-bias-linear
--group-query-attention
--num-attention-heads 64
--num-query-groups 2
--kv-channels 128
--num-layers 108
--hidden-size 8192
--ffn-hidden-size 5120
--normalization RMSNorm
--position-embedding-type none
--vocab-size 131072
--make-vocab-size-divisible-by 128
--untie-embeddings-and-output-weights

# MoE specifics
--num-experts 512
--moe-router-topk 22
--moe-ffn-hidden-size 5120
--moe-shared-expert-intermediate-size 10240
# Ultra-550B bottlenecks expert input/output through a 2048-dim latent
# (routed experts run on moe_latent_size, not hidden_size; two extra fc1/fc2
# latent projections per MoE layer). Surfaced from HF config by the miles
# NemotronH bridge; the CLI arg keeps Megatron's parser happy.
--moe-latent-size 2048
--moe-router-score-function sigmoid
--moe-router-enable-expert-bias
--moe-grouped-gemm
--moe-router-dtype fp32
# n_group=1 (MoE groups) -> group-limited routing is a no-op (single group of
# 512). HF n_groups=8 is the Mamba groups, unrelated to MoE.
--moe-router-num-groups 1
--moe-router-group-topk 1
--moe-router-topk-scaling-factor 5.0
--moe-router-pre-softmax
--moe-router-load-balancing-type seq_aux_loss
--moe-router-bias-update-rate 0
--moe-aux-loss-coeff 0
)
159 changes: 159 additions & 0 deletions scripts/run-nemotron-3-ultra-550b-a55b-4layer.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
#!/bin/bash
# Single-node (8x H200) smoke test for the 4-layer Nemotron-3-Ultra slice.
#
# Same code path as run-nemotron-3-ultra-550b-a55b.sh (AutoBridge + miles
# NemotronHBridge MoE/latent shim, colocated SGLang rollout), sized down to one
# node so the Megatron -> SGLang weight sync can be verified end to end with
# --check-weight-update-equal.
#
# Prereq: build the slice once (see scripts/models/nemotron-3-ultra-550b-a55b-4layer.sh):
# python cluster_scripts/debug_tool_set/checkpoint/prune_nemotron_h.py \
# --src <full HF ckpt> --dst $MODELS_DIR/Nemotron-3-Ultra-4layer --layers 0,1,7,8
#
# Usage:
# bash scripts/run-nemotron-3-ultra-550b-a55b-4layer.sh

pkill -9 sglang
sleep 3
ray stop --force
pkill -9 ray
pkill -9 python
sleep 3
pkill -9 ray
pkill -9 python

set -ex
export PYTHONBUFFERED=16

NVLINK_COUNT=$(nvidia-smi topo -m 2>/dev/null | grep -o 'NV[0-9][0-9]*' | wc -l)
if [ "$NVLINK_COUNT" -gt 0 ]; then HAS_NVLINK=1; else HAS_NVLINK=0; fi
echo "HAS_NVLINK: $HAS_NVLINK (detected $NVLINK_COUNT NVLink references)"

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
source "${SCRIPT_DIR}/models/nemotron-3-ultra-550b-a55b-4layer.sh"
cd "${SCRIPT_DIR}/.."

MODELS_DIR=${MODELS_DIR:-/scratch/nemotron_data/models}
DATASETS_DIR=${DATASETS_DIR:-/scratch/nemotron_data/datasets}
HF=${HF:-$MODELS_DIR/Nemotron-3-Ultra-4layer}
MEGATRON_PATH=${MEGATRON_PATH:-/mirror/nemotron/megatron}

CKPT_ARGS=(
--hf-checkpoint $HF
--ref-load $HF
--save $MODELS_DIR/nemotron-3-ultra-4layer_miles
--save-interval 10000 # never inside a smoke test
--no-save-optim
--megatron-to-hf-mode bridge
)

ROLLOUT_ARGS=(
--prompt-data $DATASETS_DIR/dapo-math-17k/dapo-math-17k.jsonl
--input-key prompt
--label-key label
--apply-chat-template
--rollout-shuffle
--rm-type deepscaler
--num-rollout 2
--rollout-batch-size 8
--n-samples-per-prompt 2
--rollout-max-response-len 256
--rollout-temperature 1
--global-batch-size 16
--balance-data
)

PERF_ARGS=(
# 8 GPUs. Mamba n_groups=8 caps attention/mamba TP at 8; TP=1 keeps the
# 4-layer slice trivially valid and leaves all 8 ranks for expert parallel
# (512 experts / EP8 = 64 per rank).
--tensor-model-parallel-size 1
--pipeline-model-parallel-size 1
--context-parallel-size 1
--expert-model-parallel-size 8
--expert-tensor-parallel-size 1

--recompute-granularity full
--recompute-method uniform
--recompute-num-layers 1

--use-dynamic-batch-size
--max-tokens-per-gpu 1024
--log-probs-chunk-size 128
)

GRPO_ARGS=(
--advantage-estimator grpo
--use-kl-loss
--kl-loss-coef 0.00
--kl-loss-type low_var_kl
--entropy-coef 0.00
--eps-clip 0.2
--eps-clip-high 0.28
)

OPTIMIZER_ARGS=(
--optimizer adam
--lr 1e-6
--lr-decay-style constant
--weight-decay 0.1
--adam-beta1 0.9
--adam-beta2 0.98
--optimizer-cpu-offload
--overlap-cpu-optimizer-d2h-h2d
--use-precision-aware-optimizer
)

SGLANG_ARGS=(
--rollout-num-gpus-per-engine 8
--sglang-ep-size 8
# DP-attention with dp=2 -> attn_tp = 8/2 = 4, which divides Mamba n_groups=8.
--sglang-dp-size 2
--sglang-enable-dp-attention
--sglang-mem-fraction-static 0.6
)

CHECK_ARGS=(
# Snapshot SGLang's loaded weights, poison them, then assert the Megatron ->
# SGLang sync restores every tensor exactly. This is what the run is for.
--check-weight-update-equal
)

MISC_ARGS=(
--attention-dropout 0.0
--hidden-dropout 0.0
--accumulate-allreduce-grads-in-fp32
--attention-softmax-in-fp32
--attention-backend auto
)

export MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"}
ray start --head --node-ip-address ${MASTER_ADDR} --num-gpus 8 --disable-usage-stats --dashboard-host=0.0.0.0 --dashboard-port=8265

# SGLANG_SKIP_SGL_KERNEL_VERSION_CHECK: the nemotron DP-attention path uses
# existing kernels; skip the blanket sgl-kernel version guard.
RUNTIME_ENV_JSON="{
\"env_vars\": {
\"PYTHONPATH\": \"${MEGATRON_PATH}\",
\"CUDA_DEVICE_MAX_CONNECTIONS\": \"1\",
\"NCCL_NVLS_ENABLE\": \"${HAS_NVLINK}\",
\"SGLANG_SKIP_SGL_KERNEL_VERSION_CHECK\": \"1\"
}
}"

ray job submit --address="http://127.0.0.1:8265" \
--runtime-env-json="${RUNTIME_ENV_JSON}" \
-- python3 train.py \
--colocate \
--actor-num-nodes 1 \
--actor-num-gpus-per-node 8 \
--rollout-num-gpus 8 \
${MODEL_ARGS[@]} \
${CKPT_ARGS[@]} \
${ROLLOUT_ARGS[@]} \
${OPTIMIZER_ARGS[@]} \
${GRPO_ARGS[@]} \
${PERF_ARGS[@]} \
${SGLANG_ARGS[@]} \
${CHECK_ARGS[@]} \
${MISC_ARGS[@]}
Loading
Loading