Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
5e9e81c
[recipe] feat: Add Qwen3.5 LLM-only SFT recipes with skip_megatron_pa…
cuichenx Mar 30, 2026
fa2a200
fix: Fix llm_sft.sh REPO_ROOT path, packing config, and test mock
cuichenx Mar 31, 2026
b425c64
Merge origin/main into chcui/qwen35-llm-sft-recipe
cuichenx May 4, 2026
5a5d772
Merge remote-tracking branch 'origin/main' into chcui/qwen35-llm-sft-…
cuichenx May 4, 2026
c7510dd
[test] feat: add T1.4 streaming skip test and T2.2 functional vision-…
cuichenx May 5, 2026
837874e
[test] feat: add T2.5 optimizer state functional test for Qwen3.5 LLM…
cuichenx May 5, 2026
1478bbc
[test] feat: add T2.6/T2.7/T2.8 functional tests for Qwen3.5 LLM-only…
cuichenx May 5, 2026
6d59e64
Merge branch 'main' into chcui/qwen35-llm-sft-recipe
cuichenx May 5, 2026
6c1384b
[test] fix: move qwen35 LLM functional tests to test_groups, add laun…
cuichenx May 5, 2026
833db9a
[recipe, model] refactor: Skip vision tower init in Qwen3.5 LLM-only SFT
cuichenx May 7, 2026
2e37443
[ckpt, model] refactor: remove unused skip_megatron_param_globs API
cuichenx May 11, 2026
ae69676
[model, recipe] refactor: rename Qwen3.5-VL provider field init_visio…
cuichenx May 11, 2026
76a6831
[test] test: verify checkpoint resume via sentinel weight round-trip
cuichenx May 11, 2026
b7c21d1
[test] test: extend weight parity to fused QKV and gate_up layouts
cuichenx May 11, 2026
6708918
[test] test: add peak GPU memory ceiling to T2.5
cuichenx May 11, 2026
b9ed11f
[recipe, test] refactor: drop no-op freeze_vision_* in qwen35_llm recipe
cuichenx May 11, 2026
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
24 changes: 24 additions & 0 deletions examples/models/vlm/qwen35_vl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,30 @@ Pretraining is not verified for this model.

See the [slurm_sft.sh](slurm_sft.sh) script for full parameter fine-tuning with configurable model sizes.

### LLM-only fine-tuning (SQuAD, HF weights without vision)

The `qwen35_llm_*_sft_config` recipes in `megatron.bridge.recipes` load **language-model weights only** from a Qwen3.5-VL HuggingFace checkpoint. The vision tower is never instantiated (`add_encoder=False`), so vision parameters are not allocated on GPU and not loaded from the checkpoint — peak memory reflects the language model only. The language model is the standard `GPTModel` (mRoPE-augmented), wrapped under `model.language_model`. Training uses the default SQuAD setup from `_sft_common` and **`vlm_step`** so the hybrid stack runs on text-only batches.

Run from the Bridge repo root with the generic driver [`scripts/training/run_recipe.py`](../../../../scripts/training/run_recipe.py):

```bash
# 800M dense (TP=1 PP=1, 8 GPUs)
uv run torchrun --nproc_per_node=8 scripts/training/run_recipe.py \
--recipe qwen35_llm_800m_sft_config \
--step_func vlm_step \
--hf_path Qwen/Qwen3.5-0.8B

# 35B-A3B MoE (TP=2 PP=1 EP=16)
uv run torchrun --nproc_per_node=8 scripts/training/run_recipe.py \
--recipe qwen35_llm_35b_a3b_sft_config \
--step_func vlm_step \
--hf_path Qwen/Qwen3.5-35B-A3B
```

Available recipes: `qwen35_llm_800m_sft_config`, `qwen35_llm_2b_sft_config`, `qwen35_llm_4b_sft_config`, `qwen35_llm_9b_sft_config`, `qwen35_llm_27b_sft_config`, `qwen35_llm_35b_a3b_sft_config`, `qwen35_llm_122b_a10b_sft_config`, `qwen35_llm_397b_a17b_sft_config`.

See the [llm_sft.sh](llm_sft.sh) wrapper script for a ready-to-run shell command with environment variable overrides.

### Parameter-Efficient Fine-Tuning (PEFT) with LoRA

See the [slurm_peft.sh](slurm_peft.sh) script for LoRA fine-tuning with configurable model sizes.
Expand Down
57 changes: 57 additions & 0 deletions examples/models/vlm/qwen35_vl/llm_sft.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env bash

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit: This file has mode 100644 (not executable), but it has a shebang and the README tells users to run it directly (./examples/models/vlm/qwen35_vl/llm_sft.sh). Consider chmod +x.

# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -euo pipefail

# ==============================================================================
# Qwen3.5 LLM-only SFT on SQuAD (HF VLM checkpoint, vision weights skipped)
#
# Uses scripts/training/run_recipe.py with:
# - Recipes from megatron.bridge.recipes (qwen35_llm_*_sft_config)
# - --step_func vlm_step (text-only batches; no images)
#
# From the Bridge repository root:
# ./examples/models/vlm/qwen35_vl/llm_sft.sh
#
# Environment overrides:
# NPROC_PER_NODE GPUs per node (default: 8)
# RECIPE Recipe name (default: qwen35_llm_800m_sft_config)
# HF_PATH HF model id or local directory (default: Qwen/Qwen3.5-0.8B)
# EXTRA_ARGS Extra args passed to run_recipe.py (Hydra-style overrides)
#
# Examples:
# RECIPE=qwen35_llm_2b_sft_config HF_PATH=Qwen/Qwen3.5-2B ./examples/models/vlm/qwen35_vl/llm_sft.sh
#
# EXTRA_ARGS="train.train_iters=500 checkpoint.save=/tmp/qwen35_llm_ckpt" \
# ./examples/models/vlm/qwen35_vl/llm_sft.sh
#
# Optional: pin dataset via run_recipe (default SQuAD matches the recipe):
# EXTRA_ARGS="--dataset llm-finetune dataset.dataset_name=squad" \
# ./examples/models/vlm/qwen35_vl/llm_sft.sh
# ==============================================================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)"
cd "${REPO_ROOT}"

NPROC_PER_NODE="${NPROC_PER_NODE:-8}"
RECIPE="${RECIPE:-qwen35_llm_800m_sft_config}"
HF_PATH="${HF_PATH:-Qwen/Qwen3.5-0.8B}"

# shellcheck disable=SC2086
exec uv run torchrun --nproc_per_node="${NPROC_PER_NODE}" scripts/training/run_recipe.py \
--recipe "${RECIPE}" \
--step_func vlm_step \
--hf_path "${HF_PATH}" \
${EXTRA_ARGS:-}
12 changes: 10 additions & 2 deletions src/megatron/bridge/models/conversion/auto_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,11 @@ def load_hf_weights(
trust_remote_code = getattr(self.hf_pretrained, "trust_remote_code", False)
pre_trained = PreTrainedCausalLM.from_pretrained(hf_path, trust_remote_code=trust_remote_code)
bridge = self._model_bridge
bridge.load_weights_hf_to_megatron(pre_trained, model, allowed_mismatched_params=allowed_mismatched_params)
bridge.load_weights_hf_to_megatron(
pre_trained,
model,
allowed_mismatched_params=allowed_mismatched_params,
)
# Get unquantized_state_dict from the bridge instance that was used for optimizer reload
self.unquantized_state_dict = getattr(bridge, "unquantized_state_dict", None)
return model
Expand Down Expand Up @@ -1288,7 +1292,11 @@ def to_megatron_model(

return provider.provide_distributed_model(**kwargs)

def to_megatron_provider(self, load_weights: bool = True, hf_path: str | Path | None = None) -> GPTModelProvider:
def to_megatron_provider(
self,
load_weights: bool = True,
hf_path: str | Path | None = None,
) -> GPTModelProvider:
"""
Convert to a Megatron model provider.

Expand Down
14 changes: 14 additions & 0 deletions src/megatron/bridge/models/qwen_vl/qwen35_vl_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ class Qwen35VLModelProvider(GPTModelProvider):

mtp_num_layers: Optional[int] = None

# When False, the vision tower is not instantiated. Used by LLM-only SFT
# recipes that load language-model weights from a Qwen3.5-VL checkpoint —
# vision parameters are never allocated, so peak memory reflects the LLM only.
# Matches the field name on Qwen3VLModelProvider for consistency.
add_encoder: bool = True

def __post_init__(self):
_check_qwen3_5_available()
if self.vision_config is None:
Expand Down Expand Up @@ -203,6 +209,7 @@ def provide(self, pre_process=None, post_process=None, vp_stage=None) -> Qwen3VL
vision_transformer_config=hf_vision_config,
pre_process=pre_process,
post_process=post_process,
add_encoder=self.add_encoder,
pg_collection=self._pg_collection,
mtp_block_spec=mtp_spec,
vp_stage=vp_stage,
Expand Down Expand Up @@ -342,6 +349,12 @@ class Qwen35VLMoEModelProvider(GPTModelProvider):

mtp_num_layers: Optional[int] = None

# When False, the vision tower is not instantiated. Used by LLM-only SFT
# recipes that load language-model weights from a Qwen3.5-VL checkpoint —
# vision parameters are never allocated, so peak memory reflects the LLM only.
# Matches the field name on Qwen3VLModelProvider for consistency.
add_encoder: bool = True

def __post_init__(self):
_check_qwen3_5_moe_available()
if self.vision_config is None:
Expand Down Expand Up @@ -393,6 +406,7 @@ def provide(self, pre_process=None, post_process=None, vp_stage=None) -> Qwen3VL
vision_transformer_config=hf_vision_config,
pre_process=pre_process,
post_process=post_process,
add_encoder=self.add_encoder,
pg_collection=self._pg_collection,
mtp_block_spec=mtp_spec,
vp_stage=vp_stage,
Expand Down
19 changes: 19 additions & 0 deletions src/megatron/bridge/recipes/qwen_vl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@
)

# Qwen3.5 models
from .qwen35_llm import (
qwen35_llm_2b_sft_config,
qwen35_llm_4b_sft_config,
qwen35_llm_9b_sft_config,
qwen35_llm_27b_sft_config,
qwen35_llm_35b_a3b_sft_config,
qwen35_llm_122b_a10b_sft_config,
qwen35_llm_397b_a17b_sft_config,
qwen35_llm_800m_sft_config,
)
from .qwen35_vl import (
qwen35_vl_2b_peft_config,
qwen35_vl_2b_sft_config,
Expand All @@ -64,6 +74,15 @@


__all__ = [
# Qwen3.5 LLM-only (text) SFT configs
"qwen35_llm_800m_sft_config",
"qwen35_llm_2b_sft_config",
"qwen35_llm_4b_sft_config",
"qwen35_llm_9b_sft_config",
"qwen35_llm_27b_sft_config",
"qwen35_llm_35b_a3b_sft_config",
"qwen35_llm_122b_a10b_sft_config",
"qwen35_llm_397b_a17b_sft_config",
# Qwen3.5-VL pretrain configs
"qwen35_vl_9b_pretrain_mock_config",
"qwen35_vl_35b_a3b_pretrain_mock_config",
Expand Down
191 changes: 191 additions & 0 deletions src/megatron/bridge/recipes/qwen_vl/qwen35_llm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Qwen3.5 text-only (LLM) SFT recipes for Qwen3.5-VL checkpoints.

Loads **language-model weights only** from a HuggingFace Qwen3.5-VL checkpoint.
The vision tower is never instantiated (``add_encoder=False``), so the vision
parameters are absent from the Megatron model — they are neither allocated on
GPU nor loaded from the checkpoint. The language model is the standard
``GPTModel`` (specifically ``Qwen3VLGPTModel``, a ``GPTModel`` subclass that
adds mRoPE) wrapped under ``model.language_model``; the wrapper has no vision
attribute.

Train with ``megatron.bridge.training.vlm_step.forward_step``.
"""

import torch

from megatron.bridge import AutoBridge
from megatron.bridge.recipes.common import _sft_common
from megatron.bridge.recipes.qwen_vl.qwen35_vl import (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The to_megatron_provider(load_weights=True) call here means weights are loaded eagerly during recipe construction. This is correct for training (the provider streams HF weights at model-build time), but worth a brief docstring note since other recipes typically use load_weights=False and rely on checkpoint.load instead. Makes it clear this is intentional for the HF-direct-load path.

_qwen35_vl_apply_moe,
_qwen35_vl_enable_recompute,
)
from megatron.bridge.recipes.utils.optimizer_utils import distributed_fused_adam_with_cosine_annealing
from megatron.bridge.training.config import ConfigContainer


def _qwen35_llm_sft_apply_common(
cfg: ConfigContainer,
hf_path: str,
*,
tp: int,
pp: int,
max_lr: float,
min_lr: float,
train_iters: int = 1000,
global_batch_size: int = 128,
micro_batch_size: int = 1,
) -> None:
"""Apply Qwen3.5 LLM-only SFT settings on top of ``_sft_common``."""
seq_len = cfg.dataset.seq_length

cfg.model = AutoBridge.from_hf_pretrained(hf_path).to_megatron_provider(load_weights=True)
cfg.model.seq_length = seq_len

# Skip instantiation of the vision tower entirely. Tasks for vision
# parameters never reach the loader because those parameters are absent
# from the Megatron model.
cfg.model.add_encoder = False

cfg.model.tensor_model_parallel_size = tp
cfg.model.pipeline_model_parallel_size = pp
cfg.model.pipeline_dtype = torch.bfloat16
cfg.model.virtual_pipeline_model_parallel_size = None
cfg.model.context_parallel_size = 1
cfg.model.sequence_parallel = False

cfg.model.freeze_language_model = False
# No vision tower exists (add_encoder=False), so freeze_vision_model /
# freeze_vision_projection are no-ops — omit them.

cfg.model.mtp_num_layers = None

cfg.model.transformer_impl = "transformer_engine"
cfg.model.cuda_graph_impl = "none"
cfg.model.cuda_graph_scope = "full"
cfg.model.cuda_graph_warmup_steps = 3
cfg.model.attention_backend = "auto"
cfg.model.gradient_accumulation_fusion = True
cfg.model.cross_entropy_loss_fusion = True
cfg.model.cross_entropy_fusion_impl = "native"
cfg.model.recompute_granularity = None
cfg.model.recompute_modules = None
cfg.model.fine_grained_activation_offloading = False
cfg.model.offload_modules = None

cfg.train.train_iters = train_iters
cfg.train.global_batch_size = global_batch_size
cfg.train.micro_batch_size = micro_batch_size
cfg.train.manual_gc = True
cfg.train.manual_gc_interval = 100
cfg.train.manual_gc_eval = 100

opt_cfg, scheduler_cfg = distributed_fused_adam_with_cosine_annealing(
lr_warmup_iters=min(50, train_iters),
lr_decay_iters=train_iters,
max_lr=max_lr,
min_lr=min_lr,
adam_beta2=0.98,
)
cfg.optimizer = opt_cfg
cfg.scheduler = scheduler_cfg

cfg.optimizer.use_precision_aware_optimizer = False
cfg.optimizer.main_grads_dtype = torch.float32
cfg.optimizer.main_params_dtype = torch.float32
cfg.optimizer.exp_avg_dtype = torch.float32
cfg.optimizer.exp_avg_sq_dtype = torch.float32

cfg.tokenizer.tokenizer_model = hf_path

cfg.dataset.pack_sequences_in_batch = False

cfg.ddp.overlap_grad_reduce = False
cfg.ddp.overlap_param_gather = False
cfg.ddp.check_for_nan_in_grad = True
cfg.ddp.use_distributed_optimizer = True
cfg.ddp.grad_reduce_in_fp32 = True
cfg.ddp.average_in_collective = True
cfg.ddp.data_parallel_sharding_strategy = "optim_grads_params"

cfg.mixed_precision = "bf16_mixed"


def qwen35_llm_800m_sft_config(hf_path: str = "Qwen/Qwen3.5-0.8B") -> ConfigContainer:
"""SQuAD-style SFT: Qwen3.5 800M, LLM weights only from HF, TP=1 PP=1."""
cfg = _sft_common()
_qwen35_llm_sft_apply_common(cfg, hf_path, tp=1, pp=1, max_lr=5e-6, min_lr=5e-7)
return cfg


def qwen35_llm_2b_sft_config(hf_path: str = "Qwen/Qwen3.5-2B") -> ConfigContainer:
"""SQuAD-style SFT: Qwen3.5 2B, LLM weights only from HF, TP=1 PP=1."""
cfg = _sft_common()
_qwen35_llm_sft_apply_common(cfg, hf_path, tp=1, pp=1, max_lr=5e-6, min_lr=5e-7)
return cfg


def qwen35_llm_4b_sft_config(hf_path: str = "Qwen/Qwen3.5-4B") -> ConfigContainer:
"""SQuAD-style SFT: Qwen3.5 4B, LLM weights only from HF, TP=2 PP=1."""
cfg = _sft_common()
_qwen35_llm_sft_apply_common(cfg, hf_path, tp=2, pp=1, max_lr=5e-6, min_lr=5e-7)
return cfg


def qwen35_llm_9b_sft_config(hf_path: str = "Qwen/Qwen3.5-9B") -> ConfigContainer:
"""SQuAD-style SFT: Qwen3.5 9B, LLM weights only from HF, TP=4 PP=1."""
cfg = _sft_common()
_qwen35_llm_sft_apply_common(cfg, hf_path, tp=4, pp=1, max_lr=5e-6, min_lr=5e-7)
return cfg


def qwen35_llm_27b_sft_config(hf_path: str = "Qwen/Qwen3.5-27B") -> ConfigContainer:
"""SQuAD-style SFT: Qwen3.5 27B, LLM weights only from HF, TP=4 PP=4."""
cfg = _sft_common()
_qwen35_llm_sft_apply_common(cfg, hf_path, tp=4, pp=4, max_lr=5e-6, min_lr=5e-7)
return cfg


def qwen35_llm_35b_a3b_sft_config(hf_path: str = "Qwen/Qwen3.5-35B-A3B") -> ConfigContainer:
"""SQuAD-style SFT: Qwen3.5 35B-A3B MoE, LLM weights only, TP=2 PP=1 EP=16."""
cfg = _sft_common()
_qwen35_llm_sft_apply_common(
cfg, hf_path, tp=2, pp=1, max_lr=2e-5, min_lr=2e-6, global_batch_size=32, micro_batch_size=1
)
_qwen35_vl_apply_moe(cfg, ep=16)
return cfg


def qwen35_llm_122b_a10b_sft_config(hf_path: str = "Qwen/Qwen3.5-122B-A10B") -> ConfigContainer:
"""SQuAD-style SFT: Qwen3.5 122B-A10B MoE, LLM weights only."""
cfg = _sft_common()
_qwen35_llm_sft_apply_common(
cfg, hf_path, tp=2, pp=6, max_lr=2e-5, min_lr=2e-6, global_batch_size=36, micro_batch_size=1
)
_qwen35_vl_apply_moe(cfg, ep=8)
_qwen35_vl_enable_recompute(cfg)
return cfg


def qwen35_llm_397b_a17b_sft_config(hf_path: str = "Qwen/Qwen3.5-397B-A17B") -> ConfigContainer:
"""SQuAD-style SFT: Qwen3.5 397B-A17B MoE, LLM weights only."""
cfg = _sft_common()
_qwen35_llm_sft_apply_common(
cfg, hf_path, tp=2, pp=4, max_lr=2e-5, min_lr=2e-6, global_batch_size=32, micro_batch_size=1
)
_qwen35_vl_apply_moe(cfg, ep=32)
_qwen35_vl_enable_recompute(cfg)
return cfg
Loading
Loading