Skip to content

[Module] Add configurable Linear that inherits from Module - #2527

Merged
fegin merged 10 commits into
mainfrom
gh/fegin/91/head
Mar 12, 2026
Merged

fegin merged 10 commits into
mainfrom
gh/fegin/91/head

Conversation

@fegin

@fegin fegin commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Why the Change
Same as #2428 and #2434. This is the third PR that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases that swap the linear modules with fp8/mx linear modules.

Summary

  • Introduces torchtitan.models.common.linear.Linear, a configurable nn.Linear subclass that also inherits from Module, following the same Config/build() pattern as RMSNorm and Embedding.
  • Updates all shared components (GQAttention, FeedForward, Decoder) and all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to use Linear.Config instead of raw nn.Linear.
  • Adds capture_module_configs() and inject_module_protocol() utilities in protocols/module.py to preserve the Module protocol through Float8/MX quantization conversions. Float8 creates new instances (losing attributes), so configs are captured beforehand and re-attached afterwards. MX uses class swaps (attributes survive), so re-attachment acts as a safety net.
  • Replaces the bias: bool field on GQAttention.Config with per-projection Linear.Config fields (wq, wk, wv, wo), enabling per-linear configuration of bias, init_std, and init_mean.
  • Adds comprehensive unit tests for Linear, config injection, and the capture/re-attach round-trip.

fegin added 2 commits March 9, 2026 13:07
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 9, 2026
**Why the Change**
Same as #2428 and #2434. This is the third PR that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable nn.Linear subclass that also inherits from Module, following the same Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities in protocols/module.py to preserve the Module protocol through Float8/MX quantization conversions. Float8 creates new instances (losing attributes), so configs are captured beforehand and re-attached afterwards. MX uses class swaps (attributes survive), so re-attachment acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with per-projection Linear.Config fields (wq, wk, wv, wo), enabling per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the capture/re-attach round-trip.


ghstack-source-id: 12305fc
Pull-Request: #2527
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 9, 2026
@fegin
fegin marked this pull request as draft March 9, 2026 20:07
@fegin fegin changed the title [Module] Add configurable Linear that inherits from Module [WIP][Module] Add configurable Linear that inherits from Module Mar 9, 2026
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 9, 2026
**Why the Change**
Same as #2428 and #2434. This is the third PR that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable nn.Linear subclass that also inherits from Module, following the same Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities in protocols/module.py to preserve the Module protocol through Float8/MX quantization conversions. Float8 creates new instances (losing attributes), so configs are captured beforehand and re-attached afterwards. MX uses class swaps (attributes survive), so re-attachment acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with per-projection Linear.Config fields (wq, wk, wv, wo), enabling per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the capture/re-attach round-trip.

ghstack-source-id: d957648
Pull-Request: #2527
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 9, 2026
**Why the Change**
Same as #2428 and #2434. This is the third PR that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable nn.Linear subclass that also inherits from Module, following the same Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities in protocols/module.py to preserve the Module protocol through Float8/MX quantization conversions. Float8 creates new instances (losing attributes), so configs are captured beforehand and re-attached afterwards. MX uses class swaps (attributes survive), so re-attachment acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with per-projection Linear.Config fields (wq, wk, wv, wo), enabling per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the capture/re-attach round-trip.

ghstack-source-id: b2da087
Pull-Request: #2527
fegin added 2 commits March 10, 2026 10:47
[ghstack-poisoned]
[ghstack-poisoned]
@@ -546,12 +558,8 @@ def forward(

def init_weights(self, init_std: float = 0.02, **kwargs) -> None:
for linear in (self.wq, self.wk, self.wv):

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.

So after this pr, we will call init_weights to all weights in linear init_weights

[ghstack-poisoned]
@fegin fegin changed the title [WIP][Module] Add configurable Linear that inherits from Module [Module] Add configurable Linear that inherits from Module Mar 10, 2026
@fegin
fegin requested a review from acisseJZhong March 10, 2026 19:28
@fegin
fegin marked this pull request as ready for review March 10, 2026 19:28
Comment thread torchtitan/models/common/linear.py Resolved
Comment thread torchtitan/models/common/linear.py Resolved
Comment thread torchtitan/models/common/linear.py Resolved
Comment thread torchtitan/models/common/moe/moe.py Resolved
Comment thread torchtitan/models/common/moe/moe.py Resolved
self.w1 = nn.Linear(dim, config.hidden_dim, bias=config.bias)
self.w2 = nn.Linear(config.hidden_dim, dim, bias=config.bias)
self.w3 = nn.Linear(dim, config.hidden_dim, bias=config.bias)
self.w1 = config.w1.build(

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.

same: pass in config.bias?

@fegin fegin Mar 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same reply. config.bias has been set when config is created. Users should only pass arguments that need to be computed during runtime or shared across modules to build().

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 10s —— View job


PR Review: [Module] Add configurable Linear that inherits from Module

  • Read repository guidelines
  • Read PR diff and all changed files (22 files)
  • Analyze new Linear module and Config pattern
  • Analyze protocol utilities (capture_module_attrs, inject_module_protocol)
  • Review quantization integration (float8, mx)
  • Review model config updates across all models
  • Review unit tests
  • Check existing reviewer comments
  • Post comprehensive review

Overall Assessment

This PR introduces a well-structured Linear module following the same Config/build() pattern as RMSNorm and Embedding. The design is consistent with the existing codebase conventions. The quantization integration (capture/inject/verify) is thoughtful and addresses a real problem with float8/MX conversions losing Module protocol attributes. The test coverage is comprehensive.

Below are the issues and suggestions I identified, roughly ordered by severity.


Issues

1. init_weights does not respect init_mean override from kwargs (Medium)

In torchtitan/models/common/linear.py:54-59, the init_weights method allows init_std to be overridden via kwargs but does not allow init_mean to be overridden the same way. This is inconsistent — if a parent wants to override init_std at call time, it should presumably be able to override init_mean too. Reviewer @acisseJZhong also flagged this.

def init_weights(self, **kwargs) -> None:
    init_std: float | None = kwargs.pop("init_std", None)
    std = init_std if init_std is not None else self._init_std
    nn.init.trunc_normal_(self.weight, mean=self._init_mean, std=std)

Consider adding init_mean override support for symmetry, or document why only init_std is overridable.

Fix this →

2. init_weights does not consider dtype (Medium)

In torchtitan/models/common/linear.py:57, nn.init.trunc_normal_ is called without regard to the weight's dtype. Reviewer @mori360 flagged this. For consistency with the rest of the codebase (and to avoid potential issues with low-precision dtypes like float16), it may be worth adding a dtype guard or documenting the expected behavior. The old TokenChoiceTopKRouter.init_weights (which this subsumes for the gate linear) called nn.init.trunc_normal_ similarly, so this may be an acceptable pre-existing pattern — but worth a deliberate decision.

3. Missing bias propagation in FeedForward and MoE shared experts (Medium — flagged by reviewers)

Reviewers @acisseJZhong flagged two places where bias is not explicitly propagated through Linear.Config:

  • torchtitan/models/common/feed_forward.py:52-59: The FeedForward.Config takes Linear.Config fields for w1/w2/w3, but the bias setting on those configs is whatever the caller provides. This is fine as-is since the caller controls the Linear.Config. However, if a model historically needed bias=True on FFN linears, the caller must now remember to set bias=True on each Linear.Config individually. Currently no model uses bias=True for FFN, so this is not a functional issue but is worth documenting.

  • torchtitan/models/common/moe/moe.py:170: TokenChoiceTopKRouter.__init__ creates Linear.Config(bias=gate_bias) inline, which correctly passes through the gate_bias config. This looks correct.

  • torchtitan/models/common/moe/moe.py:424-429: The MoE.__init__ creates FeedForward.Config for shared experts with default Linear.Config() (bias=False). If a model needs bias on shared expert linears, this would need to be configurable. Currently no model uses bias=True here, so this is acceptable but could be made configurable in a follow-up.

4. Decoder.init_weights bypasses Linear.init_weights for the output layer (torchtitan/models/common/decoder.py:130-139) (Low)

The output layer is built as config.output.build(...) which creates a Linear instance, but Decoder.init_weights then directly calls nn.init.trunc_normal_ on self.output.weight rather than using self.output.init_weights(...). This means the init_mean and init_std stored on the Linear config are ignored for the output layer. This appears intentional (the output layer uses a special dim**-0.5 std with cutoff), but it bypasses the Module protocol. Consider either:

  • Using self.output.init_weights(init_std=final_out_std) and encoding the cutoff logic in Linear, or
  • Adding a comment explaining why this layer is special-cased.

5. Inconsistent init_weights signatures across Flux layers (Low)

Several Flux layer init_weights methods use positional-style signatures rather than **kwargs:

  • MLPEmbedder.init_weights(self, init_std: float = 0.02) at torchtitan/models/flux/model/layers.py:116
  • DoubleStreamBlock.init_weights(self) at torchtitan/models/flux/model/layers.py:266
  • SingleStreamBlock.init_weights(self) at torchtitan/models/flux/model/layers.py:382
  • LastLayer.init_weights(self) at torchtitan/models/flux/model/layers.py:436

These are marked with # pyrefly: ignore [bad-override] which indicates they don't conform to the Module.init_weights(**kwargs) signature. This is a pre-existing issue, not introduced by this PR, but worth noting since these classes now inherit from Module.

6. Flux SelfAttention, Modulation, QKNorm don't inherit from Module (Low)

In torchtitan/models/flux/model/layers.py, SelfAttention (line 142), Modulation (line 179), and QKNorm (line 126) still inherit directly from nn.Module rather than Module. They create Linear instances inline via Linear.Config(...).build(...) but don't follow the Config/build() pattern themselves. These classes have init_weights methods but don't use the **kwargs signature. This seems intentional for Flux (which has a different architecture than LLMs), but may cause issues if these modules contain nn.Linear submodules that quantization converters try to process.


Positive Observations

  1. Clean capture/inject/verify pattern (torchtitan/protocols/module.py:38-135): The three-function pattern (capture_module_attrs → quantization conversion → inject_module_protocol + verify_module_protocol) is well-designed. The caching of patched classes in inject_module_protocol avoids creating duplicate types. The _raise_error sentinel on __init__ prevents accidental direct construction of patched classes.

  2. Consistent quantization integration: Both Float8LinearConverter.convert() and MXLinearConverter.convert() (and their grouped-MM variants) follow the identical pattern: verify → capture → convert → inject → verify. This is defensive and catches regressions early.

  3. Per-projection Linear.Config in GQAttention: Replacing bias: bool with individual wq, wk, wv, wo Linear.Config fields is a good design choice that enables per-projection customization (e.g., GPT-OSS uses bias=True on all attention projections).

  4. Test coverage: The test file (tests/unit_tests/test_linear.py) covers the key scenarios well: config build, bias, init_weights, dtype, direct construction, shared configs, injection, idempotency, MX-style class swap, capture/re-attach round-trip, and verify_module_protocol.

  5. Config reuse via field(init=False): Using in_features: int = field(init=False) and out_features: int = field(init=False) to exclude runtime-determined dimensions from the config constructor is a clean pattern consistent with RMSNorm and Embedding.


Minor Nits

  • torchtitan/protocols/module.py:69: The docstring says "This API is designed for model converter that may swap the modules" — should be "converters" (plural).
  • The naming capture_module_attrs in the PR description is called capture_module_configs() but in code it's capture_module_attrs. The PR description should be updated to match.

Summary

The PR is well-structured and the core design is sound. The main actionable items are:

  1. Consider adding init_mean override support in Linear.init_weights for symmetry with init_std (or document the asymmetry).
  2. Consider whether Decoder.init_weights should use self.output.init_weights() rather than bypassing it.

The remaining reviewer comments from @acisseJZhong and @mori360 about bias propagation and dtype appear to be addressed or are acceptable as-is with the explanations above.


Comment thread torchtitan/models/gpt_oss/model.py Resolved
Comment on lines +45 to +47
w1: Linear.Config
w2: Linear.Config
w3: Linear.Config

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.

I would consider these as "SwiGLUFeedForward" implementation details that doesn't need to be swapped / configurable, until we receive requests to configure them. It's kind verbose to have them in every model config registry without specifying any real arg.

You may argue that people still want to experiment with different init -- that's the reason why we have next PR.

Same for wq/wk/wv/wo.

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.

Chatted offline

  • we think it's not necessary to use build style at all for these internal details of a module.
  • the init method can be owned by root module, as a dict from fqn to init function mapping, which can be changed by users who modify model code
  • the sharding may still need to be defined per each module (unclear right now), but probably should still be owned by parent module

Comment thread torchtitan/models/common/moe/moe.py Resolved
# We need to first verify if all nn.Linear have been converted to Linear.
verify_module_protocol(model, nn.Linear, Linear)
saved_attrs = capture_module_attrs(
model, ["_init_mean", "_init_std"], nn_module_cls=nn.Linear

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.

Are these the only thing we need to save? I thought

  • these fields could be moved to config, not in the Linear class itself.
  • but then we still need to keep the inheritance from Float8Linear to torchtitan.Linear.

After all, if we have to keep such code, they should exist in torchao, not torchtitan.

@danielvegamyhre what's your latest thought on torchao APIs? In this PR, we are having torchtitan-specialized nn.Linear and I think torchao should still work without we do anything special here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

these fields could be moved to config, not in the Linear class itself.
These fields are moved to StateInitializer in the next PR, #2540. The only thing we need to save is _state_initializer.

After all, if we have to keep such code, they should exist in torchao, not torchtitan.

I'm happy to remove this logic if torchao handle this. But I don't want to be blocked by another refactor from another repo. I would consider to move forward with this logic living inside this repo and refactor until both repo are happy.

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.

That's fine. If so, let's

  • move these utils inside quantization, not in general protocols folder.
  • mark them as temporary and leave TODOs

[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 11, 2026
**Why the Change**
Same as #2428 and #2434. This is the third PR that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable nn.Linear subclass that also inherits from Module, following the same Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities in protocols/module.py to preserve the Module protocol through Float8/MX quantization conversions. Float8 creates new instances (losing attributes), so configs are captured beforehand and re-attached afterwards. MX uses class swaps (attributes survive), so re-attachment acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with per-projection Linear.Config fields (wq, wk, wv, wo), enabling per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the capture/re-attach round-trip.

ghstack-source-id: 85093ae
Pull-Request: #2527

@tianyu-l tianyu-l 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.

sg, please address #2527 (comment) before merge

fegin added 2 commits March 12, 2026 00:15
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 12, 2026
**Why the Change**
Same as #2428 and #2434. This is the third PR that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable nn.Linear subclass that also inherits from Module, following the same Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities in protocols/module.py to preserve the Module protocol through Float8/MX quantization conversions. Float8 creates new instances (losing attributes), so configs are captured beforehand and re-attached afterwards. MX uses class swaps (attributes survive), so re-attachment acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with per-projection Linear.Config fields (wq, wk, wv, wo), enabling per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the capture/re-attach round-trip.

ghstack-source-id: f205521
Pull-Request: #2527
@fegin
fegin changed the base branch from gh/fegin/91/base to main March 12, 2026 16:32
@fegin
fegin merged commit 5732118 into main Mar 12, 2026
19 of 23 checks passed
mori360 pushed a commit to mori360/torchtitan that referenced this pull request Mar 12, 2026
)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* __->__ pytorch#2527

**Why the Change**
Same as pytorch#2428 and
pytorch#2434. This is the third PR
that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases
that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable
nn.Linear subclass that also inherits from Module, following the same
Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and
all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to
use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities
in protocols/module.py to preserve the Module protocol through Float8/MX
quantization conversions. Float8 creates new instances (losing
attributes), so configs are captured beforehand and re-attached
afterwards. MX uses class swaps (attributes survive), so re-attachment
acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with
per-projection Linear.Config fields (wq, wk, wv, wo), enabling
per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the
capture/re-attach round-trip.
acisseJZhong added a commit that referenced this pull request Mar 17, 2026
# Motivation

  Continues the modularization effort from #2428 (Embedding), #2434 (RMSNorm), and
  #2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
  Config/build() pattern, enabling per-component configurability and consistent
  weight initialization.

 # Summary

  - GroupedExperts inherits from Module with a nested Config dataclass. dim,
  hidden_dim, and num_experts use field(init=False) so they are set at build() time
   by the parent MoE.
  - TokenChoiceTopKRouter inherits from Module with a nested Config dataclass.
  Replaces the flat gate_bias: bool field with gate: Linear.Config, enabling full
  gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts use
  field(init=False).
  - TokenReorderer inherits from Module with a no-op init_weights (stateless
  module). num_experts and top_k use field(init=False).
  - MoE.Config replaces flat router/expert fields (top_k, score_func, route_norm,
  route_scale, gate_bias, use_grouped_mm, num_expert_groups, num_limited_groups,
  _debug_force_load_balance) with nested experts: GroupedExperts.Config and router:
   TokenChoiceTopKRouter.Config.
  - Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use nested
  router/expert configs.
  - Adds 34 unit tests covering Config/build(), init_weights, forward passes, and
  nested config propagation for all modularized components.

cc fegin #2540 may needs to rebase on this. 


[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Mar 17, 2026
# Motivation

  Continues the modularization effort from #2428 (Embedding), #2434 (RMSNorm), and
  #2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
  Config/build() pattern, enabling per-component configurability and consistent
  weight initialization.

 # Summary

  - GroupedExperts inherits from Module with a nested Config dataclass. dim,
  hidden_dim, and num_experts use field(init=False) so they are set at build() time
   by the parent MoE.
  - TokenChoiceTopKRouter inherits from Module with a nested Config dataclass.
  Replaces the flat gate_bias: bool field with gate: Linear.Config, enabling full
  gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts use
  field(init=False).
  - TokenReorderer inherits from Module with a no-op init_weights (stateless
  module). num_experts and top_k use field(init=False).
  - MoE.Config replaces flat router/expert fields (top_k, score_func, route_norm,
  route_scale, gate_bias, use_grouped_mm, num_expert_groups, num_limited_groups,
  _debug_force_load_balance) with nested experts: GroupedExperts.Config and router:
   TokenChoiceTopKRouter.Config.
  - Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use nested
  router/expert configs.
  - Adds 34 unit tests covering Config/build(), init_weights, forward passes, and
  nested config propagation for all modularized components.

cc fegin #2540 may needs to rebase on this. 


[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Mar 17, 2026
# Motivation

  Continues the modularization effort from #2428 (Embedding), #2434 (RMSNorm), and
  #2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
  Config/build() pattern, enabling per-component configurability and consistent
  weight initialization.

 # Summary

  - GroupedExperts inherits from Module with a nested Config dataclass. dim,
  hidden_dim, and num_experts use field(init=False) so they are set at build() time
   by the parent MoE.
  - TokenChoiceTopKRouter inherits from Module with a nested Config dataclass.
  Replaces the flat gate_bias: bool field with gate: Linear.Config, enabling full
  gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts use
  field(init=False).
  - TokenReorderer inherits from Module with a no-op init_weights (stateless
  module). num_experts and top_k use field(init=False).
  - MoE.Config replaces flat router/expert fields (top_k, score_func, route_norm,
  route_scale, gate_bias, use_grouped_mm, num_expert_groups, num_limited_groups,
  _debug_force_load_balance) with nested experts: GroupedExperts.Config and router:
   TokenChoiceTopKRouter.Config.
  - Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use nested
  router/expert configs.
  - Adds 34 unit tests covering Config/build(), init_weights, forward passes, and
  nested config propagation for all modularized components.

cc fegin #2540 may needs to rebase on this. 


[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Mar 17, 2026
# Motivation

  Continues the modularization effort from #2428 (Embedding), #2434 (RMSNorm), and
  #2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
  Config/build() pattern, enabling per-component configurability and consistent
  weight initialization.

 # Summary

  - GroupedExperts inherits from Module with a nested Config dataclass. dim,
  hidden_dim, and num_experts use field(init=False) so they are set at build() time
   by the parent MoE.
  - TokenChoiceTopKRouter inherits from Module with a nested Config dataclass.
  Replaces the flat gate_bias: bool field with gate: Linear.Config, enabling full
  gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts use
  field(init=False).
  - TokenReorderer inherits from Module with a no-op init_weights (stateless
  module). num_experts and top_k use field(init=False).
  - MoE.Config replaces flat router/expert fields (top_k, score_func, route_norm,
  route_scale, gate_bias, use_grouped_mm, num_expert_groups, num_limited_groups,
  _debug_force_load_balance) with nested experts: GroupedExperts.Config and router:
   TokenChoiceTopKRouter.Config.
  - Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use nested
  router/expert configs.
  - Adds 34 unit tests covering Config/build(), init_weights, forward passes, and
  nested config propagation for all modularized components.

cc fegin #2540 may needs to rebase on this. 


[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Mar 17, 2026
# Motivation

  Continues the modularization effort from #2428 (Embedding), #2434 (RMSNorm), and
  #2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
  Config/build() pattern, enabling per-component configurability and consistent
  weight initialization.

 # Summary

  - GroupedExperts inherits from Module with a nested Config dataclass. dim,
  hidden_dim, and num_experts use field(init=False) so they are set at build() time
   by the parent MoE.
  - TokenChoiceTopKRouter inherits from Module with a nested Config dataclass.
  Replaces the flat gate_bias: bool field with gate: Linear.Config, enabling full
  gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts use
  field(init=False).
  - TokenReorderer inherits from Module with a no-op init_weights (stateless
  module). num_experts and top_k use field(init=False).
  - MoE.Config replaces flat router/expert fields (top_k, score_func, route_norm,
  route_scale, gate_bias, use_grouped_mm, num_expert_groups, num_limited_groups,
  _debug_force_load_balance) with nested experts: GroupedExperts.Config and router:
   TokenChoiceTopKRouter.Config.
  - Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use nested
  router/expert configs.
  - Adds 34 unit tests covering Config/build(), init_weights, forward passes, and
  nested config propagation for all modularized components.

cc fegin #2540 may needs to rebase on this. 


[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request Mar 17, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at
bottom):
* __->__ #2571

# Motivation

Continues the modularization effort from #2428 (Embedding), #2434
(RMSNorm), and
  #2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
Config/build() pattern, enabling per-component configurability and
consistent
  weight initialization.

 # Summary

- GroupedExperts inherits from Module with a nested Config dataclass.
dim,
hidden_dim, and num_experts use field(init=False) so they are set at
build() time
   by the parent MoE.
- TokenChoiceTopKRouter inherits from Module with a nested Config
dataclass.
Replaces the flat gate_bias: bool field with gate: Linear.Config,
enabling full
gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts
use
  field(init=False).
- TokenReorderer inherits from Module with a no-op init_weights
(stateless
  module). num_experts and top_k use field(init=False).
- MoE.Config replaces flat router/expert fields (top_k, score_func,
route_norm,
route_scale, gate_bias, use_grouped_mm, num_expert_groups,
num_limited_groups,
_debug_force_load_balance) with nested experts: GroupedExperts.Config
and router:
   TokenChoiceTopKRouter.Config.
- Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use
nested
  router/expert configs.
- Adds 34 unit tests covering Config/build(), init_weights, forward
passes, and
  nested config propagation for all modularized components.

cc @fegin #2540 may needs to rebase on this.
acisseJZhong added a commit that referenced this pull request Mar 17, 2026
# Motivation

Continues the modularization effort from #2428 (Embedding), #2434
(RMSNorm), and
  #2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
Config/build() pattern, enabling per-component configurability and
consistent
  weight initialization.

 # Summary

- GroupedExperts inherits from Module with a nested Config dataclass.
dim,
hidden_dim, and num_experts use field(init=False) so they are set at
build() time
   by the parent MoE.
- TokenChoiceTopKRouter inherits from Module with a nested Config
dataclass.
Replaces the flat gate_bias: bool field with gate: Linear.Config,
enabling full
gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts
use
  field(init=False).
- TokenReorderer inherits from Module with a no-op init_weights
(stateless
  module). num_experts and top_k use field(init=False).
- MoE.Config replaces flat router/expert fields (top_k, score_func,
route_norm,
route_scale, gate_bias, use_grouped_mm, num_expert_groups,
num_limited_groups,
_debug_force_load_balance) with nested experts: GroupedExperts.Config
and router:
   TokenChoiceTopKRouter.Config.
- Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use
nested
  router/expert configs.
- Adds 34 unit tests covering Config/build(), init_weights, forward
passes, and
  nested config propagation for all modularized components.

cc @fegin #2540 may needs to rebase on this.
weifengpy pushed a commit to weifengpy/torchtitan-flexshard that referenced this pull request Mar 27, 2026
)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* __->__ pytorch#2527

**Why the Change**
Same as pytorch#2428 and
pytorch#2434. This is the third PR
that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases
that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable
nn.Linear subclass that also inherits from Module, following the same
Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and
all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to
use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities
in protocols/module.py to preserve the Module protocol through Float8/MX
quantization conversions. Float8 creates new instances (losing
attributes), so configs are captured beforehand and re-attached
afterwards. MX uses class swaps (attributes survive), so re-attachment
acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with
per-projection Linear.Config fields (wq, wk, wv, wo), enabling
per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the
capture/re-attach round-trip.
weifengpy pushed a commit to weifengpy/torchtitan-flexshard that referenced this pull request Mar 27, 2026
# Motivation

Continues the modularization effort from pytorch#2428 (Embedding), pytorch#2434
(RMSNorm), and
  pytorch#2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
Config/build() pattern, enabling per-component configurability and
consistent
  weight initialization.

 # Summary

- GroupedExperts inherits from Module with a nested Config dataclass.
dim,
hidden_dim, and num_experts use field(init=False) so they are set at
build() time
   by the parent MoE.
- TokenChoiceTopKRouter inherits from Module with a nested Config
dataclass.
Replaces the flat gate_bias: bool field with gate: Linear.Config,
enabling full
gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts
use
  field(init=False).
- TokenReorderer inherits from Module with a no-op init_weights
(stateless
  module). num_experts and top_k use field(init=False).
- MoE.Config replaces flat router/expert fields (top_k, score_func,
route_norm,
route_scale, gate_bias, use_grouped_mm, num_expert_groups,
num_limited_groups,
_debug_force_load_balance) with nested experts: GroupedExperts.Config
and router:
   TokenChoiceTopKRouter.Config.
- Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use
nested
  router/expert configs.
- Adds 34 unit tests covering Config/build(), init_weights, forward
passes, and
  nested config propagation for all modularized components.

cc @fegin pytorch#2540 may needs to rebase on this.
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* __->__ pytorch#2527

**Why the Change**
Same as pytorch#2428 and
pytorch#2434. This is the third PR
that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases
that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable
nn.Linear subclass that also inherits from Module, following the same
Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and
all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to
use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities
in protocols/module.py to preserve the Module protocol through Float8/MX
quantization conversions. Float8 creates new instances (losing
attributes), so configs are captured beforehand and re-attached
afterwards. MX uses class swaps (attributes survive), so re-attachment
acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with
per-projection Linear.Config fields (wq, wk, wv, wo), enabling
per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the
capture/re-attach round-trip.
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
# Motivation

Continues the modularization effort from pytorch#2428 (Embedding), pytorch#2434
(RMSNorm), and
  pytorch#2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
Config/build() pattern, enabling per-component configurability and
consistent
  weight initialization.

 # Summary

- GroupedExperts inherits from Module with a nested Config dataclass.
dim,
hidden_dim, and num_experts use field(init=False) so they are set at
build() time
   by the parent MoE.
- TokenChoiceTopKRouter inherits from Module with a nested Config
dataclass.
Replaces the flat gate_bias: bool field with gate: Linear.Config,
enabling full
gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts
use
  field(init=False).
- TokenReorderer inherits from Module with a no-op init_weights
(stateless
  module). num_experts and top_k use field(init=False).
- MoE.Config replaces flat router/expert fields (top_k, score_func,
route_norm,
route_scale, gate_bias, use_grouped_mm, num_expert_groups,
num_limited_groups,
_debug_force_load_balance) with nested experts: GroupedExperts.Config
and router:
   TokenChoiceTopKRouter.Config.
- Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use
nested
  router/expert configs.
- Adds 34 unit tests covering Config/build(), init_weights, forward
passes, and
  nested config propagation for all modularized components.

cc @fegin pytorch#2540 may needs to rebase on this.
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* __->__ pytorch#2527

**Why the Change**
Same as pytorch#2428 and
pytorch#2434. This is the third PR
that changes Linear to inherit from Module.

But unlike previous two PRs, we also need to consider converter cases
that swap the linear modules with fp8/mx linear modules.

**Summary**

- Introduces `torchtitan.models.common.linear.Linear`, a configurable
nn.Linear subclass that also inherits from Module, following the same
Config/build() pattern as RMSNorm and Embedding.
- Updates all shared components (GQAttention, FeedForward, Decoder) and
all model configs (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux) to
use Linear.Config instead of raw nn.Linear.
- Adds capture_module_configs() and inject_module_protocol() utilities
in protocols/module.py to preserve the Module protocol through Float8/MX
quantization conversions. Float8 creates new instances (losing
attributes), so configs are captured beforehand and re-attached
afterwards. MX uses class swaps (attributes survive), so re-attachment
acts as a safety net.
- Replaces the bias: bool field on GQAttention.Config with
per-projection Linear.Config fields (wq, wk, wv, wo), enabling
per-linear configuration of bias, init_std, and init_mean.
- Adds comprehensive unit tests for Linear, config injection, and the
capture/re-attach round-trip.
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
# Motivation

Continues the modularization effort from pytorch#2428 (Embedding), pytorch#2434
(RMSNorm), and
  pytorch#2527 (Linear). This PR makes MoE components (GroupedExperts,
  TokenChoiceTopKRouter, TokenReorderer) inherit from Module and use the
Config/build() pattern, enabling per-component configurability and
consistent
  weight initialization.

 # Summary

- GroupedExperts inherits from Module with a nested Config dataclass.
dim,
hidden_dim, and num_experts use field(init=False) so they are set at
build() time
   by the parent MoE.
- TokenChoiceTopKRouter inherits from Module with a nested Config
dataclass.
Replaces the flat gate_bias: bool field with gate: Linear.Config,
enabling full
gate configuration (e.g., Linear.Config(bias=True)). dim and num_experts
use
  field(init=False).
- TokenReorderer inherits from Module with a no-op init_weights
(stateless
  module). num_experts and top_k use field(init=False).
- MoE.Config replaces flat router/expert fields (top_k, score_func,
route_norm,
route_scale, gate_bias, use_grouped_mm, num_expert_groups,
num_limited_groups,
_debug_force_load_balance) with nested experts: GroupedExperts.Config
and router:
   TokenChoiceTopKRouter.Config.
- Updates all model configs (DeepSeek V3, Qwen3, GPT-OSS, Llama4) to use
nested
  router/expert configs.
- Adds 34 unit tests covering Config/build(), init_weights, forward
passes, and
  nested config propagation for all modularized components.

cc @fegin pytorch#2540 may needs to rebase on this.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants