Skip to content

Commit 46282b9

Browse files
committed
fix(gemma4_moe): re-tie lm_head to active embed_tokens on MoE path
The MoE path replaces language_model after HF __init__, orphaning the lm_head<->embed_tokens tie that HF set up. Re-tie lm_head to the active embed_tokens when tie_word_embeddings is set (Gemma defaults True). Add CPU tied/untied tests. Refs #2512
1 parent 033a4bf commit 46282b9

2 files changed

Lines changed: 114 additions & 0 deletions

File tree

nemo_automodel/components/models/gemma4_moe/model.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -809,6 +809,15 @@ def __init__(
809809
# Expose moe_config for the MoE parallelizer assertion
810810
self.model.moe_config = self.model.language_model.moe_config
811811

812+
# HF's super().__init__() tied lm_head.weight to the *original* text
813+
# embed_tokens, but the language_model replacement above swapped in a
814+
# fresh embed_tokens and orphaned that alias. Re-tie lm_head to the
815+
# now-active embedding when the config requests tied embeddings (Gemma
816+
# defaults to tie_word_embeddings=True). The shared Parameter survives
817+
# the in-place cast in initialize_weights().
818+
if getattr(text_config, "tie_word_embeddings", False):
819+
self.lm_head.weight = self.model.language_model.embed_tokens.weight
820+
812821
self.vocab_size = text_config.vocab_size
813822
# State dict adapter for HF ↔ NeMo weight conversion
814823
if self.backend.enable_hf_state_dict_adapter:
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Weight-tying tests for the Gemma4 MoE conditional-generation model.
16+
17+
HF's ``super().__init__()`` ties ``lm_head.weight`` to the original text
18+
``embed_tokens``. The MoE path then replaces ``language_model`` with
19+
``Gemma4MoETextModelBackend`` (a fresh ``embed_tokens``), which orphans that
20+
alias. The model re-ties ``lm_head`` to the now-active embedding when
21+
``tie_word_embeddings`` is set (Gemma defaults to ``True``); these tests pin
22+
that behavior for both the tied and untied configs.
23+
24+
Runs on CPU (no CUDA / TE / DeepEP required).
25+
"""
26+
27+
import torch
28+
from transformers.models.gemma4.configuration_gemma4 import Gemma4Config, Gemma4TextConfig
29+
30+
from nemo_automodel.components.models.common import BackendConfig
31+
from nemo_automodel.components.models.gemma4_moe.model import (
32+
Gemma4ForConditionalGeneration,
33+
Gemma4MoETextModelBackend,
34+
)
35+
36+
37+
def _make_text_config(**overrides):
38+
"""Tiny Gemma4TextConfig (2 layers, small hidden, tiny vocab, few experts)."""
39+
defaults = dict(
40+
vocab_size=256,
41+
hidden_size=64,
42+
num_attention_heads=4,
43+
num_key_value_heads=2,
44+
head_dim=16,
45+
num_hidden_layers=2,
46+
intermediate_size=128,
47+
rms_norm_eps=1e-6,
48+
max_position_embeddings=256,
49+
enable_moe_block=True, # routes construction through the NeMo MoE backend
50+
num_experts=4,
51+
top_k_experts=2,
52+
moe_intermediate_size=64,
53+
layer_types=["full_attention", "sliding_attention"],
54+
sliding_window=128,
55+
hidden_activation="gelu_pytorch_tanh",
56+
torch_dtype="bfloat16",
57+
)
58+
defaults.update(overrides)
59+
return Gemma4TextConfig(**defaults)
60+
61+
62+
def _make_cpu_backend():
63+
"""CPU-friendly backend: no TE, no DeepEP, plain torch kernels."""
64+
return BackendConfig(
65+
linear="torch",
66+
attn="sdpa",
67+
rms_norm="torch",
68+
experts="torch",
69+
dispatcher="torch",
70+
fake_balanced_gate=False,
71+
enable_hf_state_dict_adapter=False,
72+
)
73+
74+
75+
def _build(tie_word_embeddings: bool) -> Gemma4ForConditionalGeneration:
76+
config = Gemma4Config(text_config=_make_text_config(tie_word_embeddings=tie_word_embeddings))
77+
model = Gemma4ForConditionalGeneration(config, backend=_make_cpu_backend())
78+
# Sanity: construction routed through the real NeMo MoE backend (the path
79+
# that replaces language_model and breaks HF's tie).
80+
assert isinstance(model.model.language_model, Gemma4MoETextModelBackend)
81+
return model
82+
83+
84+
def test_tied_lm_head_shares_active_embedding_after_construction():
85+
"""tie_word_embeddings=True: lm_head must alias the *active* MoE embed_tokens."""
86+
model = _build(tie_word_embeddings=True)
87+
assert model.lm_head.weight is model.model.language_model.embed_tokens.weight
88+
89+
90+
def test_tied_lm_head_survives_initialize_weights():
91+
"""The tie set in __init__ must survive the bf16 cast in initialize_weights()."""
92+
model = _build(tie_word_embeddings=True)
93+
model.initialize_weights(dtype=torch.bfloat16, buffer_device=torch.device("cpu"))
94+
95+
embed = model.model.language_model.embed_tokens.weight
96+
lm_head = model.lm_head.weight
97+
assert lm_head is embed
98+
assert lm_head.dtype == torch.bfloat16
99+
100+
101+
def test_untied_lm_head_is_separate():
102+
"""tie_word_embeddings=False: lm_head must keep its own storage."""
103+
model = _build(tie_word_embeddings=False)
104+
assert model.lm_head.weight is not model.model.language_model.embed_tokens.weight
105+
assert model.lm_head.weight.data_ptr() != model.model.language_model.embed_tokens.weight.data_ptr()

0 commit comments

Comments
 (0)