Skip to content

Huvu/gemma4 e4b tp sp#5508

Draft
huvunvidia wants to merge 15 commits into
NVIDIA:mainfrom
huvunvidia:huvu/gemma4-e4b-tp-sp
Draft

Huvu/gemma4 e4b tp sp#5508
huvunvidia wants to merge 15 commits into
NVIDIA:mainfrom
huvunvidia:huvu/gemma4-e4b-tp-sp

Conversation

@huvunvidia

Copy link
Copy Markdown
Contributor
  • I, the PR author, have personally reviewed every line of this PR.

What does this PR do ?

⚠️ For major changes (either in lines of code or in its impact), please make sure to first share a design doc with the team. If you're unsure what's the best way to do so, contact @NVIDIA/mcore-oncall.

Issue tracking

For PRs from open-source community contributors:

  • New features: a linked issue is required. Please open a feature request and reference it here before submitting the PR.
  • Small updates (bug fixes, minor improvements): a linked issue is recommended and will accelerate the PR review process.

Linked issue:

Contribution process

Pre-checks

  • I have added relevant unit tests
  • I have added relevant functional tests
  • I have added proper typing to my code Typing guidelines
  • I have added relevant documentation
  • I have run the autoformatter.sh on my PR

Code review

Feel free to message or comment @NVIDIA/mcore-oncall to help accelerate your merge into main. The less complex your PR is, the faster it will be approved and merged!

All PRs start as draft. If you open a non-draft PR, it will be automatically converted to draft.

Step 1: Mark PR as "Ready for Review"

  1. When your PR is ready, click Ready for Review.
  2. An oncall reviewer is auto-assigned and expert reviewers are notified based on your changes.
    • Some PRs may jump straight to step 2. This is determined by .github/CODEOWNERS.

⚠️ Only mark as ready once merge-conflicts are resolved and the CI is passing.
Final Review might get declined if these requirements are not fulfilled.

Step 2: Final Review

For PRs that change megatron/core, once all expert reviewers have approved, the Final Review label is applied automatically and final reviewers are assigned.

For PRs outside megatron/core, this step is skipped.

Step 3: Approved

Once all required reviewers have approved, the Approved label is applied automatically.

Merge

Any member of mcore-engineers will be able to merge your PR.

JRD971000 and others added 15 commits June 22, 2026 15:08
…+ I-b)

Gemma4TransformerConfig subclasses TransformerConfig with per-layer
get_config_for_layer (256/512 kv_channels, 1e4/1e6 rotary_base, sliding
window) plus forward-only flags (softcap, embed scaling, PLE dims). The
three primitive modules are bitwise-faithful ports of HF Gemma4:
- Gemma4RMSNorm: fp32 pow(-0.5), plain weight, with_scale flag.
- Gemma4RotaryEmbedding: sliding full-rotary + full proportional RoPE.
- Gemma4PLE: per_layer_inputs with bf16-rounded embed scales.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…pecs (I-c)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Per-layer config dropped gemma4-only fields (hidden_size_per_layer_input,
layer_types, etc.) and passed non-base rotary_base into TransformerConfig.
Carry all non-base fields + derived layer_types onto the per-layer config;
rope theta is handled by Gemma4RotaryEmbedding by layer_type, not config.
build_module returns a FunctionType unchanged rather than invoking it, so
build_module(gemma4_rms_norm_scaleless_builder, ...) left self.v_layernorm as the
builder function itself, which crashed at forward time (apply_module: 'function is
not a subclass of torch.nn.Module'). Call the builder directly, matching how the
base attention/layer build q/k/input layernorms from their LayerNormBuilder slots.

This makes the I-c suite fully green (V6_local, kv_bus, V6_te all PASS).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Thin entrypoint mirroring pretrain_gpt.py that builds Gemma4Model with
Gemma4TransformerConfig and the gemma4 local/TE layer specs. Reuses the GPT
data pipeline, batch logic, loss, and forward step. The final-logit softcap
and sqrt(H) embedding scaling live inside Gemma4Model.forward and reach the
training loss path. Includes a self-contained nvrx __version__ shim applied
before megatron import.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Base TransformerConfig defaults normalization='LayerNorm', so the TE spec's
TENorm was building a mean-subtracting te.pytorch.LayerNorm instead of RMSNorm,
causing large TE-spec divergence (V4 logits max-abs ~36, per-layer ~90). The
local spec was unaffected (hard-wires Gemma4RMSNorm). Forcing RMSNorm in
__post_init__ drops TE per-layer divergence to bf16-noise (~0-3).
…ing)

The bias_dropout_add path runs in-place in eval/no-grad mode, which aliases the
post-norm output tensor across the attention/MLP sub-blocks and corrupts the
sandwich-norm result. Gemma4 sublayers have no bias and dropout=0, so add the
residual explicitly: h = residual + post_norm(sublayer(pre_norm(h))). Mirrors HF
Gemma4TextDecoderLayer exactly.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
per_layer_input_gate used gather_output=False, which at TP>1 would shard the
gate to ple_dim/TP while the threaded per_layer_input (p_i) stays full-width,
so gate * p_i mismatches (e.g. 32 vs 256 at TP=8). Gather the gate so the PLE
sub-block runs replicated. No-op at TP=1 (numerically identical); does not
affect weight sharding or checkpoint load.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: ataghibakhsh <ataghibakhsh@nvidia.com>
Make Gemma 4 E4B correct under tensor + sequence parallelism (TP=2/4/8 +SP),
training-only, parity with the verified TP=1 oracle.

- PLE SP layout (gemma4_model.py, gemma4_layer.py): unify the per-layer-input
  gate/projection as a standard Column(gather_output=False)->Row(input_is_parallel=
  True) pair and shard per_layer_inputs on the PLE dim via
  scatter_to_tensor_model_parallel_region. Gemma4Model.forward gathers decoder_input
  (SP-guarded, tensor_parallel_output_grad=False to avoid a TP gradient overcount) to
  recompute full-sequence PLE while the residual stream stays sequence-sharded.
  Replaces the prior gather_output=True hack; correct at TP=1 / TP>1 noSP / TP>1+SP.
- Norm grad-tag (gemma4_norm.py): mark weighted Gemma4RMSNorm weights sequence_parallel
  so their replicated-but-partial grads all-reduce across TP under SP (mirrors TENorm).
- Config hardening (pretrain_gemma4.py): force qk_layernorm / add_bias_linear /
  add_qkv_bias and assert GQA num_query_groups for correct TP>num_query_groups sharding.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: ataghibakhsh <ataghibakhsh@nvidia.com>
V0-V7 verification tooling (lives outside megatron/, supporting the TP+SP work):
- tp_fwd.py: TP/SP-parameterized forward (vocab-gather, SP-aware per-layer capture,
  --pad-seq-to for SP sequence-divisibility), mlm_env.py worktree path shim.
- compare_logits.py: parity verdict (greedy + logits/per-layer bands, --real-len).
- diag_pos.py: per-position top-2 logit diagnostic (near-tie vs bug).
- tp_reshard.py: V7 dist-ckpt reshard round-trip.
- v0_dryrun / tp_parity / v_sp2 / v_sp4 / v_sp8 / v_sp_all / v6_* / v7_reshard sbatch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: ataghibakhsh <ataghibakhsh@nvidia.com>
…TP/SP harness)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: ataghibakhsh <ataghibakhsh@nvidia.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: ataghibakhsh <ataghibakhsh@nvidia.com>
…n+parity)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: ataghibakhsh <ataghibakhsh@nvidia.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: ataghibakhsh <ataghibakhsh@nvidia.com>
@huvunvidia huvunvidia requested review from a team as code owners June 26, 2026 16:18
@copy-pr-bot

copy-pr-bot Bot commented Jun 26, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@svcnvidia-nemo-ci svcnvidia-nemo-ci marked this pull request as draft June 26, 2026 16:18
@github-actions

Copy link
Copy Markdown
Contributor

This PR has been automatically converted to draft because all PRs must start as drafts.

When you are ready for review, click Ready for Review to begin the review process. This will:

  1. Add the oncall reviewer (optional reviewer)
  2. Add required review teams based on your changes

See the contribution guide for more details.

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.

2 participants