Skip to content

test(megatron_bridge): cover context parallelism in the VLM QAD test - #2592

Merged
kevalmorabia97 merged 3 commits into
mainfrom
kmorabia/qad-cp-coverage
Oct 1, 2026
Merged

kevalmorabia97 merged 3 commits into
mainfrom
kmorabia/qad-cp-coverage

Conversation

@kevalmorabia97

@kevalmorabia97 kevalmorabia97 commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Type of change: new tests

Runs the VLM case of test_qad under context parallelism, so QAD on a Qwen3-VL model is covered on the path that until now could not run at all.

Qwen3VLMultimodalRotaryEmbedding CP-shards its own embedding, so the batch has to hand it full-length position_ids. Megatron-Bridge's get_batch was sharding them too, leaving the rotary embedding at seq / cp**2 against hidden states at seq / cp. The fix is upstream in NVIDIA-NeMo/Megatron-Bridge#6243; this PR is the coverage that would have caught it.

The VLM case moves from tensor to context parallelism and the PTQ step is sized to the same TP, so QAD still loads a matching checkpoint. The LLM case is unchanged (tp_size=num_gpus, cp_size=1), and test_distill_vlm still covers TP for a VLM, so nothing loses coverage.

Usage

# Unchanged: --cp_size is already a distill.py flag. On a container carrying Megatron-Bridge#6243
# it now works for VLMs, where it previously died in the rotary embedding.
python examples/megatron_bridge/distill.py --cp_size 2 --tp_size 1 ...

Testing

On 2x RTX 6000 Ada, in nemo:26.08 with Megatron-Bridge#6243 on PYTHONPATH:

  • test_qad[qwen3_5_moe_vl] at --tp_size 1 --cp_size 2 — FP8 PTQ, QAD across 2 CP ranks, export; quantizers survive and the vision tower is byte-identical. 1 passed (183 s). Without the upstream fix the same run dies with AttributeError: 'NoneType' object has no attribute 'ndim' in rope.py:175.
  • test_qad[qwen3], the unchanged LLM path — 1 passed (194 s).
  • Gate check: on today's nemo:26.08 (no #6243) the probe resolves False and the VLM case stays at cp_size=1, byte-identical to current CI; with #6243 it resolves True and runs at cp_size=num_gpus. On a 1-GPU runner it degenerates to today's config either way.
  • pre-commit run --files ... clean (ruff check, ruff format, mypy, bandit, markdownlint).

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅ — existing tests extended rather than new ones added.
  • Did you update Changelog?: N/A — test coverage and one doc line; no feature, break, deprecation, or fix for a released bug.
  • Did you get Claude approval on this PR?: ❌ — not yet run.

Additional Information

  • Depends on NVIDIA-NeMo/Megatron-Bridge#6243. Safe to merge before it lands: the gate keeps the VLM case at cp_size=1 until a container ships the fix, at which point the coverage switches on by itself.

Summary by CodeRabbit

  • Documentation
    • Updated the Qwen3.6 QAD instructions to keep tensor and pipeline parallelism set to 1, while allowing context parallelism to increase for longer sequences with the nemo:26.10 container.
  • Tests
    • QAD validation now selects parallelism settings based on whether the Megatron-Bridge context-parallel fix is available, and reports when multi-GPU VLM coverage is reduced.

Qwen3-VL's mrope rotary embedding CP-shards its own embedding, so the batch must
hand it full-length position ids. Run the VLM case of test_qad under context
parallelism to exercise that path; the LLM case keeps tensor parallelism, and the
PTQ step is sized to the same TP so QAD still loads a matching checkpoint.

Gated on the Megatron-Bridge fix (NVIDIA-NeMo/Megatron-Bridge#6243) so containers
predating it keep today's cp_size=1 configuration instead of failing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Keval Morabia <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: NVIDIA/Model-Optimizer/.coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: eecb1abe-938c-4344-9381-6dbadc356703

📥 Commits

Reviewing files that changed from the base of the PR and between 8635803 and d56cb6b.

📒 Files selected for processing (1)
  • tests/examples/megatron_bridge/test_qad.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 10 remain after this review.


📝 Walkthrough

Walkthrough

The QAD test checks for Megatron-Bridge’s mrope context-parallel fix and selects parallelism settings based on its availability and model type. PTQ and distillation use the selected settings. The tutorial updates its context-parallelism guidance.

Changes

QAD Parallelism

Layer / File(s) Summary
Select QAD parallelism
tests/examples/megatron_bridge/test_qad.py
The test probes for the mrope context-parallel fix, selects tensor and context parallelism based on VLM status and fix availability, and warns when a multi-GPU VLM run lacks the fix.
Configure PTQ and distillation
tests/examples/megatron_bridge/test_qad.py, examples/megatron_bridge/tutorials/Qwen3.6-35B-A3B/README.md
PTQ and distillation use the selected tensor-parallel size. Distillation also uses the selected context-parallel size. The tutorial allows increasing --cp_size for longer sequences with nemo:26.10 or later and retains the EP=8 match requirement.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Other

Merge Risk: ⚪ Minimal · up to d56cb

The VLM test preserves the compatible fallback and enables context parallelism when the fix is available. The checkpoint handoff is consistent with the documented guidance; no concrete merge-blocking risk is established.

🚥 Pre-merge checks | ✅ 6
✅ Passed checks (6 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding context-parallel coverage to the Megatron-Bridge VLM QAD test.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 1 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns ✅ Passed The pull request changes only one Python test and one README. The added Python code imports a probe and emits a warning; it does not add torch.load(..., weights_only=False), numpy.load(..., allow_pick…
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Comment @coderabbitai help to get the list of available commands.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

/claude review

@claude claude Bot left a comment

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.

Claude review

Scope: full review — the trigger comment was a bare /claude review. 2 files changed (17+/4-): tests/examples/megatron_bridge/test_qad.py and the Qwen3.6-35B-A3B tutorial README. Both reviewed in full.

Findings — CRITICAL: 0, IMPORTANT: 1, SUGGESTION: 1

[IMPORTANT Compatibility] — test_qad.py:35-40: the HAS_MROPE_CP_FIX probe imports a private helper (_keep_full_position_ids_for_cp) from an unmerged upstream PR, and degrades silently. If Megatron-Bridge#6243 lands with that helper renamed or inlined during review — routine for a leading-underscore function — the gate resolves False permanently, the VLM case reverts to cp_size=1, and the test keeps passing while covering nothing new. Nothing in CI output distinguishes "CP exercised" from "coverage silently gone". Minimum fix: make the resolved parallelism visible (a print, or warnings.warn on the degraded path) so a stale probe is loud instead of invisible; follow up with a version-based check or a public upstream marker once the fix merges.

[SUGGESTION] — README line 190: the nemo:26.10 cutoff is a prediction, not an observation (testing was on 26.08 with the branch on PYTHONPATH, and the upstream PR is still open). Keying the guidance to the fix rather than to an unconfirmed version number avoids sending users into an opaque rope.py AttributeError mid-job.

What I verified and found correct

  • Coverage is not lost, as the description claims. test_distill_vlm (test_distill.py:161) still runs a VLM at tp_size=num_gpus, and test_quantize_export.py still covers VLM PTQ at tp_size=num_gpus via the qwen3vl param — so moving this case PTQ to --nproc_per_node=tp_size and its distill to CP does not drop the VLM/TP paths.
  • Parallelism arithmetic is consistent. tp*pp*cp = num_gpus in both branches, so DP stays 1 and gbs=4, mbs=1 resolves to 4 gradient-accumulation steps exactly as before. seq_length=16 satisfies Megatron load-balanced CP requirement (seq % (2*cp) == 0) for the power-of-two GPU counts CI uses.
  • Checkpoint handoff is sound. Sizing the PTQ run to tp_size keeps the TP the QAD load expects, and step 3 unchanged pp_size=num_gpus export reshards from the tp=1 distilled checkpoint the same way it already resharded from tp=num_gpus. CP shards activations, not weights, so the saved state is unaffected.
  • Loss-path coverage improves rather than narrows. distill.py:378 sets per_token_loss = args.sft or args.cp_size > 1, so the VLM case now exercises the per-token branch while the LLM case keeps the aggregate branch — both are covered across the parametrization.
  • Gate falls back correctly on a 1-GPU runner (cp_size=1, tp_size=1) and for the LLM case (unchanged tp_size=num_gpus, cp_size=1).

Risk assessment: low. Tests-and-docs only; no modelopt/ source, no mode registration, config schema, public API, or export path touched, so there is no backward-compatibility or checkpoint-restore surface here. The CP fallback is genuinely safe — absent the upstream fix this is byte-identical to current CI. The one IMPORTANT finding is about the new coverage being able to disappear without anyone noticing, not about the change being wrong; a one-line warning on the degraded path resolves it.

🤖 Generated with Claude Code

The probe keys on a private helper from an unmerged upstream PR, so a rename
upstream would silently drop the context-parallel coverage while the test kept
passing green. Warn on the degraded path, note the container the fix ships in,
and mark the probe with a TODO to remove it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Keval Morabia <[email protected]>
@codecov

codecov Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 71.75%. Comparing base (57f929e) to head (d56cb6b).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2592      +/-   ##
==========================================
+ Coverage   71.58%   71.75%   +0.16%     
==========================================
  Files         607      611       +4     
  Lines       67665    69395    +1730     
==========================================
+ Hits        48439    49791    +1352     
- Misses      19226    19604     +378     
Flag Coverage Δ
examples-megatron_bridge 26.59% <ø> (-0.04%) ⬇️
unit 59.16% <ø> (+0.34%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@cjluo-nv cjluo-nv left a comment

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.

Bot review (gpt-6-astra) — DM the bot to share feedback.

LGTM: the justified test change adds gated VLM context-parallel coverage while preserving checkpoint compatibility and existing assertions.

Needs action:

  • Obtain maintainer sign-off for the justified test_qad.py topology change: VLM QAD switches to CP when supported, while test_distill_vlm retains VLM TP coverage.

No action needed:

  • PTQ and QAD use matching TP sizes; older Bridge installations retain the existing topology with a warning.
  • The LLM case and checkpoint, quantizer, and vision-weight assertions remain intact.
  • Tests were inspected, not run; the PR reports successful two-GPU runs with the upstream fix.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator Author

/claude review

@claude claude Bot left a comment

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.

Claude review (second pass — re-reviewing after 86358030)

Scope: full review; the trigger was a bare /claude review. 2 files changed (26+/4−): tests/examples/megatron_bridge/test_qad.py and the Qwen3.6-35B-A3B tutorial README. Both reviewed in full.

Findings — CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 1

Prior IMPORTANT is resolved

My last pass flagged that the HAS_MROPE_CP_FIX probe imports a private symbol from an unmerged upstream PR and degraded silently, so a rename during upstream review would delete the new coverage with nothing in CI output to say so. 86358030 adds a warnings.warn on the ImportError path, including an explicit "If the installed Megatron-Bridge should carry the fix, this probe is stale" hint, plus a TODO(Megatron-Bridge#6243) to drop the probe once the minimum Bridge carries it. That addresses the finding. My one remaining comment is a non-blocking refinement on when the warning fires, not whether it exists.

What I verified this round

  • The probe's ImportError is unambiguous. Line 27 imports _test_utils.torch.megatron.modelopt_state, which hard-imports megatron.bridge.training.post_training.checkpointing at module top. So megatron.bridge is guaranteed importable before the probe runs — collection would already have errored otherwise. The except ImportError can therefore only mean the symbol is missing, which is exactly what the warning claims. No false attribution.
  • The warning cannot fail collection. No filterwarnings entry in [tool.pytest.ini_options] (pyproject.toml:342), so this lands in the warnings summary rather than erroring. pytest does capture collection-time warnings, so it will actually surface.
  • The gate is inert in CI as configured, by design. example_tests.yml:156-161 runs this on nvcr.io/nvidia/nemo:26.08 at 1 GPU for PRs and 2 GPUs nightly. 26.08 predates #6243, so the probe resolves False and both configurations stay byte-identical to today. The new CP coverage switches on only when the container bumps to 26.10 — which matches what the description states, so this is the acknowledged design, not a gap. Worth knowing that merging this changes nothing observable in CI until that bump.
  • Parallelism arithmetic holds. tp*pp*cp == num_gpus in both branches, so DP stays 1 and gbs=4, mbs=1 still resolves to 4 gradient-accumulation steps. seq_length=16 satisfies Megatron's load-balanced CP view into 2*cp chunks for every GPU count this CI uses (cp ≤ 8 → 16 % 16 == 0 at worst).
  • Checkpoint handoff is sound. Sizing the PTQ launcher and tp_size together keeps the TP the QAD load expects. CP shards activations, not weights, so the distilled checkpoint layout is unaffected, and step 3's unchanged pp_size=num_gpus export reshards from tp=1 the same way it already resharded from tp=num_gpus.
  • cp_size=1 is a no-op for the LLM case. distill.py:124 defaults --cp_size to 1, so passing it explicitly changes nothing there — including per_token_loss (distill.py:378), which stays False for the LLM and flips to True only on the CP path.
  • No coverage lost. assert_has_modelopt_state / assert_no_quantizers_matching read the dist-checkpoint metadata and are TP-independent, so they behave the same at tp=1. VLM-at-TP coverage survives in test_distill_vlm and test_quantize_export.py.
  • README change is technically consistent. Increasing --cp_size at fixed world size holds cp*dp constant, so the documented --ep_size 8 still divides it and the "--ep_size 8 must match the PTQ checkpoint" requirement is unaffected. I also checked whether flipping per_token_loss on would make the tutorial's reported loss numbers non-comparable — at fixed seq_length with no padding, per-token and mean-of-means normalization coincide, so it doesn't.

I did not re-raise last round's SUGGESTION about the nemo:26.10 cutoff being a prediction rather than an observation; the author kept it deliberately and the test-side comment now says the same thing consistently.

Risk: low. Tests and one doc line only — no modelopt/ source, mode registration, config schema, public API, or export path, so there is no backward-compatibility or checkpoint-restore surface. The CP fallback is genuinely safe: absent the upstream fix this is identical to current CI. Note that per the other bot review, the topology change still wants maintainer sign-off on moving this case's VLM coverage from TP to CP — that's a judgment call for CODEOWNERS, not a defect.

Approving — no blocking issues.

🤖 Generated with Claude Code

The probe warned at module scope, but the PR runner has one GPU, so cp_size is 1
there whatever the probe says. Every PR run of this file therefore blamed the
missing upstream fix for a downgrade the GPU count had already forced -- and a
warning that fires when nothing is wrong is one readers learn to skip. Move it
into the test body, gated on the VLM case with more than one GPU and no fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Keval Morabia <[email protected]>
@kevalmorabia97
kevalmorabia97 merged commit 9c1cf80 into main Oct 1, 2026
34 checks passed
@kevalmorabia97
kevalmorabia97 deleted the kmorabia/qad-cp-coverage branch October 1, 2026 17:35
@github-actions

github-actions Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-10-01 17:36 UTC

kevalmorabia97 added a commit that referenced this pull request Oct 2, 2026
…2606)

### What does this PR do?

Type of change: documentation

The Qwen3.6-35B-A3B tutorial already diagnoses SciCode's **+90.9%
completion tokens** as a failure to terminate — a small fraction of
sub-steps run to the 131,072-token cap inside `<think>` and return
nothing. It offered no remedy short of redoing QAD. There is a
decode-time one.

Adding `presence_penalty: 1.5` — Qwen's own thinking-mode recommendation
for this model — removes nearly all of it with no retraining. 8 runs per
side, ~2,700 SciCode sub-steps per cell:

| Model | Capped sub-steps | SciCode (Subtask) | Generation time (s) |
| --- | --- | --- | --- |
| **BF16** (teacher) | 20 → **0** | 40.8 → 39.9 | 1,312 → 1,158 |
| W4A16 NVFP4 PTQ | 37 → **0** | 38.5 → 39.4 | 2,081 → 1,394 |
| **W4A4 NVFP4 PTQ** | 32 → **1** | 39.1 → 39.1 | 1,674 → 1,476 |
| **↳ + QAD 500 iters** | 96 → **2** | 40.2 → 39.6 | 2,340 → 1,316 |

Accuracy is neutral (deltas span −0.95 to +0.89, i.e. run-to-run noise)
and generation is 12-44% faster.

**It is scoped deliberately.** On GPQA Diamond, which never caps, the
same setting leaves accuracy unchanged while making generation **4.2×
slower** — pure cost. The tutorial says to use it where runaway
generation actually occurs and not to make it a global default.

Also in this PR:

- Defines **sub-step** and **capped** at the points they are used. A
capped sub-step scores zero, which is what makes the "accuracy is
neutral" result interesting — removing 96 automatic zeros did not raise
the score.
- Notes that `params_to_add` is how to set `presence_penalty` / `top_k`
on an `ns_*` task, appended to the existing note that already explains
why NEL's `params` block rejects them.
- Cites [Lotfi et al.,
arXiv:2606.00206](https://arxiv.org/abs/2606.00206), which reports
quantization amplifying "overthinking" and proposes a hesitation-marker
logit penalty. We tested that penalty: it helps less than
`presence_penalty` and costs a little accuracy, and its marker-density
signature does not reproduce on our W4A4 PTQ — their failure opens *new*
reasoning branches, ours repeats a finished solution.

### Usage

```yaml
# In the eval config's adapter_config, for any ns_* task:
params_to_add:
  chat_template_kwargs: {enable_thinking: true}
  presence_penalty: 1.5
```

### Testing

Docs-only; no code paths touched. The numbers come from 40 SciCode and 9
GPQA evaluation runs on oci-hsg (vLLM 0.28.0, 4× GB200), all on the
existing published checkpoints — no retraining.

- SciCode: 8 runs per side for all four models. An earlier 2-run read
showed a −2.45 accuracy drop on W4A16 that **reversed to +0.89 at 8
runs**, so every figure quoted here is from the repeat-matched set.
- GPQA: 3 baseline runs vs 2 with the penalty. The baseline was re-run
specifically to confirm the 4.2× — the three baselines span 7,878-8,261
s, and the 19-day-old run sits inside the spread of two fresh ones, so
it is the knob and not cluster drift.
- `pre-commit run --files ...` clean (markdownlint).

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ✅
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: N/A — documentation only.
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
N/A — tutorial content, not a feature or fix.
- Did you get Claude approval on this PR?: ❌ — not yet run.

### Additional Information

Independent of #2592, which touches a different section of the same
file.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Documentation**
* Clarified which evaluation configurations omit `presence_penalty` to
reproduce the reported results and how parameters are passed to
tau2-bench and `ns_*` tasks.
* Documented that optionally setting `presence_penalty: 1.5` reduces
capped SciCode sub-steps with little accuracy change and lower mean
output length; median output length remains similar. The setting remains
disabled in the configuration.
* Noted that this setting makes uncapped GPQA generation 4.2× slower and
should not be used as a global default, and added a comparison to
research on quantized-model overthinking.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Keval Morabia <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants