Skip to content

[Module] Refactor init_weights to config-based param_init system - #2633

Merged
fegin merged 33 commits into
mainfrom
gh/fegin/103/head
Apr 2, 2026
Merged

fegin merged 33 commits into
mainfrom
gh/fegin/103/head

Conversation

@fegin

@fegin fegin commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Motivation

Parameter initialization should be configurable without modifying module code. Previously, each module defined its own init_weights method with hardcoded init logic (e.g., nn.init.trunc_normal_ with a fixed std). This couples initialization strategy to module definitions, making it impossible to change init behavior without editing model code.

Design

  • Expand the config to be per-module config
  • param_init is a dict[str, Callable] on Module.Config, mapping local parameter names to init functions. It is set on every sub-config in the model config registry.
  • init_states auto-recurses the module tree (children first, then self), calling _init_self_parameters and _init_self_buffers on each module. Buffer initialization remains module-specific (e.g., RoPE cache, MoE counters) via _init_self_buffers overrides.
  • DeferredCallable.Config wraps init functions that vary by layer depth (e.g., depth-scaled std). resolve_deferred walks the config tree and resolves these markers during per-layer config expansion.
  • expand_layer_configs (per model) deep-copies the layer template N times, resolves deferred markers, and handles model-specific layer interleaving (MoE vs dense, iRoPE, sliding attention).

Summary of changes

  • Remove all init_weights methods from modules (Linear, Embedding, RMSNorm, FeedForward, GQAttention, MoE, GroupedExperts, TokenChoiceTopKRouter, RoPE, Decoder).
  • Add param_init field to Module.Config; Config.build() propagates it to the instance as _param_init.
  • Add init_states with auto-recursion, _init_self_parameters (dict-lookup init), and _init_self_buffers (module-specific buffer init).
  • Add DeferredCallable (in torchtitan/config/) for depth-varying init.
  • Add param_init.py (in torchtitan/models/common/) with resolve_deferred, skip_param_init, and depth_scaled_std utilities.
  • Remove init_mean/init_std fields from Linear.Config and Embedding.Config — init is now expressed entirely through param_init dicts.
  • Add layers list and expand_layer_configs() pattern to all model registries, replacing per-layer config construction in Decoder.__init__.
  • Add w1/w2w3 fields to FeedForward.Config and wqkv/wo fields to GQAttention.Config (replacing linear_bias: bool), so each linear sub-module gets its own param_init.

Verification

Bitwise identical loss against origin/main with --debug.seed=42 --debug.deterministic:

Model Steps Result
Llama3 10 Bitwise identical

fegin added 2 commits March 19, 2026 11:02
[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 19, 2026
fegin added a commit that referenced this pull request Mar 19, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.


ghstack-source-id: 024899c
Pull-Request: #2633
@fegin
fegin marked this pull request as draft March 19, 2026 18:04
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 19, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

ghstack-source-id: 11120b6
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 19, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

ghstack-source-id: 6871155
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 19, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

ghstack-source-id: 803f279
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 19, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: e6704e8
Pull-Request: #2633
fegin added 2 commits March 19, 2026 19:24
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 20, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: 440e49d
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 20, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: 1bcce2b
Pull-Request: #2633
@fegin fegin changed the title [WIP][Module] Refactor init_weights to config-based param_init system [Module] Refactor init_weights to config-based param_init system Mar 20, 2026
@fegin
fegin marked this pull request as ready for review March 20, 2026 02:33
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 20, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: 884689c
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 31, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: dee7497
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Mar 31, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: ee41de8
Pull-Request: #2633
fegin added a commit that referenced this pull request Mar 31, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: ee41de8
Pull-Request: #2633
fegin added 2 commits March 31, 2026 17:52
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 1, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: e7a02cb
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 1, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: 3f77f2f
Pull-Request: #2633
fegin added a commit that referenced this pull request Apr 1, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: 3f77f2f
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 1, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: aa6d367
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 1, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: 1937d1e
Pull-Request: #2633
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 1, 2026
**NOT READY TO REVIEW**
**NOT READY TO REVIEW**

**Motiviation and Design decision**

Parameter initialization should be configurable without modifying module code.  Users reuse provided helpers (e.g., `init_trunc_normal`, `init_zeros`) to customize how parameters are initialized. Parameters are identified by their FQNs, and `init_by_regex` lets users map regex patterns to initializers — so a single declarative dict at the model config level controls all parameter init.

In theory, we could just apply param_init at the root module and be done — no recursion needed. So why   does `init_states` recurse? The main motivation is that buffer initialization is usually inherently coupled with module internals and not user-configurable. Since buffers require per-module logic via `init_self_buffers`, we provide a recursive init_states that handles both: it walks the module tree, initializing parameters via the configurable param_init and buffers via module-specific overrides, in a single pass.

**Summary**
- Remove `init_weights`.
- `init_states` auto-recurses the module tree, then calls `init_self_parameters` and `init_self_buffers` on each module.
- `param_init` (a NamedInitializer callable on Module.Config) uses regex-matched FQN patterns to map parameters to initializers. Child modules without their own `param_init` delegate up the parent chain, so init logic is defined once at the model config level.
- `make_decoder_param_init provides` shared patterns for decoder-based model, reused by Llama3, Llama4, Qwen3, and DeepSeek V3. Model-specific extensions (Flux DiT-style, GPT-OSS MoE biases) are composed via dict merge.
- Removes init_mean/init_std fields from Linear.Config and Embedding.Config — init parameters are now expressed entirely through param_init patterns.

**Verification**

with loss_compare.py

  ┌─────────────┬───────┬───────────────────┐
  │    Model    │ Steps │      Result       │
  ├─────────────┼───────┼───────────────────┤
  │ Llama3      │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ Qwen3       │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ DeepSeek V3 │ 10    │ Bitwise identical │
  ├─────────────┼───────┼───────────────────┤
  │ GPT-OSS     │ 10    │ Bitwise identical │
  └─────────────┴───────┴───────────────────┘

ghstack-source-id: ef797d7
Pull-Request: #2633

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

I have two major feedback

  1. rename DeferredCallable to just Function to make it sounds generic.
  2. about when to do config expansion and per-layer param_init assignment.

If 2 is not trivial to address, we can land first and address later.

Comment thread torchtitan/trainer.py
m.to_empty(device=init_device)
with torch.no_grad():
cast(Decoder, m).init_weights(buffer_device=buffer_device)
# TODO: Change this back to init_weights once

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.

what does this TODO mean? It's already init_weights.

# handling, see below.
rope: RoPE.Config
layer: TransformerBlock.Config # required, no default
layer: TransformerBlock.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 had thought we don't need to put this in Decoder.Config. It's a pure config time thing, which evaporates after config construction.

hidden_dim: int
linear_bias: bool = False
w1: Linear.Config
w2w3: 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.

uh is this because w2w3 share the same param init fn? It sounds unusual to couple them together, but we can revisit this later.

Comment thread torchtitan/config/deferred_callable.py Outdated
R = TypeVar("R")


class DeferredCallable(Generic[R], Configurable):

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.

DeferredCallable sounds a bit contrived. I don't have a good name, but maybe we can just call it Function, in the sense that it's a generic configurable function, just like Module is a generic configurable Module.

@fegin fegin Apr 2, 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.

Callable is not a good name because it conflicts with typing.Callable. So this is the name suggested by Claude.

cfg = replace(cfg, feed_forward=None)
else:
cfg = replace(cfg, moe=None)
resolve_deferred(cfg, layer_id)

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.

Oh I think I understood the design.

Right now you are doing:

  1. At initial config construction time:
    • create a single layer config (pending expansion) INSIDE the original model config
    • assign (deferred) init function _LINEAR_DEPTH_INIT to each module during
  2. call expand_layer_configs which
    • expand single layer config to multi-layer
    • calls resolve_deferred to resolve the init function onto each layer's module

I think it has two minor issues:

  • the single-layer config gets exposed into final official config, which is unnecessary.
  • the deferred init is unnecessarily indirect, and seems overfitting torchtitan's existing depth-init paradigm.
    • I don't know if this "depth init" is a good practice or not, it was introduced by someone and never changed, so we probably shouldn't overfit.
    • If users want something different, not based on layer-id, but e.g. based on if this transformer block has MoE or not (I made this up), then resolve_deferred becomes useless to them and they have to change expand_layer_configs -- not that they shouldn't, but I think we don't have to program this way.

Concretely I would suggest the following:

  • Move config.layer out from Decoder.Config. We can first construct Llama4TransformerBlock as the thing to be expanded (if that's more convenient than passing dict around), send it to expand_layer_configs to construct a layers stacked transformer block, and use the result to construct Llama4Model.
  • Don't assign param_init on transformer blocks before layer expansion -- e.g. we can hardcode param_init for each module inside the for-loop of layer expansion, as we are anyways providing one expansion function for each model.

top_k=1,
num_shared_experts=1,
)
return Llama4Model.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.

nit: if you are already doing "first define the shared args, then init the actual config", then it may make sense to move 2nd step out so that all models can share the Llama4Model.Config(...) code. But yeah, that's a step further into "config-of-config" land.

@tianyu-l

tianyu-l commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

@claude review the latest commit. In particular, check if @tianyu-l 's latest comments makes sense.

@claude

claude Bot commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 5m 40s —— View job


Review of Latest Commit & Evaluation of @tianyu-l's Comments

  • Read the latest commit diff
  • Read core protocol files (protocols/module.py, protocols/model.py)
  • Read config infrastructure (config/deferred_callable.py, config/configurable.py)
  • Read param_init infrastructure (models/common/param_init.py)
  • Read decoder changes (models/common/decoder.py)
  • Read model-specific changes (llama3, llama4, qwen3, deepseek_v3)
  • Evaluate @tianyu-l's latest comments
  • Provide comprehensive review

Latest Commit Review

The latest commit (5661a97) updates torchtitan/components/quantization/float8.py to capture _param_init instead of the old _init_mean/_init_std attributes in capture_module_attrs. This is a straightforward and necessary change — the Float8 converters swap nn.Linear modules and need to preserve init metadata across the swap. The change correctly tracks the new single _param_init dict instead of the two removed scalar fields. No issues here.


Evaluation of @tianyu-l's Latest Review Comments

1. Rename DeferredCallable to Function — Reasonable, with caveats

The suggestion to rename DeferredCallable to Function (config/deferred_callable.py:16) makes it sound more generic and less implementation-specific. DeferredCallable focuses on the "deferred" mechanism which is an implementation detail, while Function describes what it actually is — a configurable function.

However, Function is an extremely generic name that could clash with mental models (Python's types.FunctionType, or the common Function pattern from autograd). A middle ground like ConfigurableCallable or CallableConfig might be clearer, but Function is acceptable given it lives in the torchtitan.config namespace.

If this rename happens, the file should also be renamed from deferred_callable.py to function.py or similar.

2. Config expansion timing & param_init assignment — Agreed, this is the strongest feedback

@tianyu-l's comment on torchtitan/models/llama4/__init__.py:68 identifies two real issues with the current design:

Issue A: Single-layer config layer leaks into the final model config.

Currently Decoder.Config has both layer: TransformerBlock.Config and layers: list | None = None. After expand_layer_configs() runs, layer is stale — it contains unresolved DeferredCallable.Config instances and the template MoE/FFN configs that don't match any actual layer. Yet it remains on the config object and is still accessed (e.g., Decoder.attn_config at decoder.py:206 reads self.config.layer.attention, and Llama4's get_attention_masks at model.py:206 reads self.config.layer.attention). This dual representation is confusing.

Issue B: DeferredCallable overfits the depth-init paradigm.

The DeferredCallable.Config(fn=lambda layer_id: {...}) pattern hardcodes the assumption that the deferred value is always a function of layer_id. As @tianyu-l points out, if a user wants init that depends on something other than layer ID (e.g., MoE vs. dense layer type), resolve_deferred becomes useless. The indirection adds complexity without sufficient generality.

@tianyu-l's concrete suggestion is sound:

  • Move config.layer out from Decoder.Config. We can first construct the TransformerBlock as the thing to be expanded, send it to expand_layer_configs to construct a layers stacked transformer block, and use the result to construct the final Model config.
  • Don't assign param_init on transformer blocks before layer expansion — hardcode param_init for each module inside the for-loop of layer expansion.

This would look something like:

# In llama4/__init__.py
def _debugmodel():
    dim = 256
    ...
    layers = []
    for layer_id in range(n_layers):
        moe_enabled = (layer_id + 1) % interleave_step == 0
        use_rope = layer_id % every_n_layers_nope != 0
        depth_std = depth_scaled_std(0.02, layer_id)
        
        layers.append(Llama4TransformerBlock.Config(
            attention=GQAttention.Config(
                n_heads=n_heads,
                use_rope=use_rope,
                wqkv=Linear.Config(param_init=_LINEAR_INIT),
                wo=Linear.Config(param_init={"weight": partial(trunc_normal_, std=depth_std), "bias": zeros_}),
                ...
            ),
            feed_forward=None if moe_enabled else FeedForward.Config(...),
            moe=MoE.Config(...) if moe_enabled else None,
            ...
        ))
    
    return Llama4Model.Config(
        dim=dim,
        n_layers=n_layers,
        layers=layers,  # directly provide expanded layers
        ...
    )

This eliminates DeferredCallable entirely, removes the stale layer field, and makes every layer's config concrete and inspectable from the start. The expansion logic stays in __init__.py where it already belongs conceptually.

Trade-off: This makes the config registration functions larger (each model function now has a for-loop). But the loop is explicit, readable, and doesn't require understanding the DeferredCallable + resolve_deferred machinery. A shared helper can factor out the common deep-copy + resolve pattern for models that don't need structural variation (like Llama3, where all layers are identical except for depth-scaled init).

3. layers in Decoder.Config — Agreed it should replace layer, not coexist

The comment at decoder.py:80:

I had thought we don't need to put this in Decoder.Config. It's a pure config time thing, which evaporates after config construction.

This is partially right. layer (the template) is purely a config-time convenience, but layers (the expanded list) is used at build time and even at runtime (e.g., update_from_config iterates self.layers). If we follow the suggestion above (construct layers directly in __init__.py), then:

  • layer can be removed from Decoder.Config
  • layers: list[TransformerBlock.Config] becomes a required field (no None default)
  • The assertion at decoder.py:94-97 becomes unnecessary

The existing references to self.config.layer (like Decoder.attn_config at decoder.py:203-206) would need to be updated to self.config.layers[0] or passed through the constructor.

4. w2w3 coupling in FeedForward.Config — Worth revisiting later

The comment on feed_forward.py:46:

is this because w2w3 share the same param init fn? It sounds unusual to couple them together.

Yes, looking at FeedForward.__init__ (feed_forward.py:54-58), w2 and w3 are both built from config.w2w3. This means they share the same param_init, same bias setting, etc. The coupling exists because in the original code w2 and w3 had the same init. However, this is architecturally odd — w2 is the down-projection and w3 is the gate projection, which could reasonably have different init strategies. A future cleanup could split this into w2: Linear.Config and w3: Linear.Config, but it's not blocking for this PR.

5. TODO about init_weights — Comment is confusing

At trainer.py:380:

# TODO: Change this back to init_weights once
# autoparallel contains the wrap_init_states
cast(BaseModel, m).init_weights(buffer_device=buffer_device)

@tianyu-l asks: "what does this TODO mean? It's already init_weights." The TODO is indeed confusing. Looking at protocols/model.py:24-32, init_weights is a backward-compatible alias that calls init_states. The TODO suggests the author wants to rename the call to init_states once the autoparallel wrapper is updated, but the current code already calls init_weights which delegates to init_states. The TODO should either be rephrased to clarify the intent (e.g., "Change to init_states directly once autoparallel wraps init_states instead of init_weights") or removed if the intent is already achieved.


Additional Observations on the Current State

1. Significant boilerplate in __init__.py config registrations

Each model's __init__.py repeats the same param_init patterns (_LINEAR_INIT, _LINEAR_DEPTH_INIT, _NORM_INIT, _EMBEDDING_INIT, _output_linear_init) almost identically. For example, _LINEAR_INIT, _NORM_INIT, and _EMBEDDING_INIT are defined identically in llama3/__init__.py, llama4/__init__.py, qwen3/__init__.py, and deepseek_v3/__init__.py. These should be shared from models/common/param_init.py rather than copy-pasted.

2. Decoder.attn_config still references self.config.layer

decoder.py:203-206:

@property
def attn_config(self):
    return self.config.layer.attention

This reads from the unexpanded template layer, not from layers[0]. After expansion, self.config.layer retains unresolved DeferredCallable.Config instances and may have both moe and feed_forward set (for models with MoE interleaving). Using self.config.layers[0].attention would be more correct, but the property would need to handle the case where layers is populated.

3. Qwen3TransformerBlock.Config.moe_enabled is redundant after expansion

After expand_layer_configs runs, each layer config already has exactly one of moe=None or feed_forward=None. The moe_enabled: bool = False field on Qwen3TransformerBlock.Config (qwen3/model.py:39) duplicates this information. The constructor at model.py:46 already computes self.moe_enabled = config.moe is not None, ignoring the config field entirely. This field should be removed — it's only used by expand_layer_configs as a hint, but the expansion could just check config.moe is not None directly.

4. Model-specific TransformerBlock subclasses are still near-identical

As discussed in previous reviews, Llama4TransformerBlock, Qwen3TransformerBlock, and DeepSeekV3TransformerBlock have nearly identical __init__ and forward implementations — the only structural difference is the FFN-vs-MoE branching, which is already resolved by the expansion logic. Once expansion is mandatory, these can be unified into the base TransformerBlock. The TODO at decoder.py:35-37 acknowledges this.


Summary

@tianyu-l's latest comments are well-reasoned and identify real issues:

  1. DeferredCallable rename to Function — reasonable naming improvement.
  2. Move expansion out of config, assign param_init during expansion — the strongest and most impactful suggestion. Eliminates the DeferredCallable abstraction, removes the stale layer template from the final config, and makes per-layer configs fully concrete. This aligns with @joecummings's earlier suggestion to use layers as the primary config field.
  3. layers shouldn't need to coexist with layer in Decoder.Config — correct, layer should become a local variable in the expansion function, not a field on the config.
  4. w2w3 coupling — worth noting as technical debt.
  5. TODO comment on init_weights — should be clarified or removed.

The overall direction of this PR (config-based param_init, declarative init via _param_init dicts, auto-recursive init_states) is sound. The main architectural refinement needed is consolidating the expansion + param_init assignment into the model/__init__.py functions, removing the DeferredCallable indirection.

@fegin

fegin commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Yes, I don't like the idea of some configurations becoming obsolete later. However, this make the config easier to read in __init__.py IMO. So I keep these one layer config in the Config. But we can do the truly programming style that remove those dictionary and use another config building blocks in __init__.py to construct. Let's revisit this topic in the Module Config Programming PR.

I'll change DeferredCallable to Function. As for the rest, I think we can solve them in the Module Config Programming PR.

[ghstack-poisoned]
@fegin
fegin changed the base branch from gh/fegin/103/base to main April 2, 2026 06:29
@fegin
fegin merged commit adbaa06 into main Apr 2, 2026
24 of 35 checks passed
@tianyu-l
tianyu-l deleted the gh/fegin/103/head branch April 2, 2026 06:39
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
…orch#2633)

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

## Motivation

Parameter initialization should be configurable without modifying module
code. Previously, each module defined its own `init_weights` method with
hardcoded init logic (e.g., `nn.init.trunc_normal_` with a fixed std).
This couples initialization strategy to module definitions, making it
impossible to change init behavior without editing model code.

## Design
- **Expand the config to be per-module config**
- `param_init` is a `dict[str, Callable]` on `Module.Config`, mapping
local parameter names to init functions. It is set on every sub-config
in the model config registry.
- `init_states` auto-recurses the module tree (children first, then
self), calling `_init_self_parameters` and `_init_self_buffers` on each
module. Buffer initialization remains module-specific (e.g., RoPE cache,
MoE counters) via `_init_self_buffers` overrides.
- `DeferredCallable.Config` wraps init functions that vary by layer
depth (e.g., depth-scaled std). `resolve_deferred` walks the config tree
and resolves these markers during per-layer config expansion.
- `expand_layer_configs` (per model) deep-copies the layer template N
times, resolves deferred markers, and handles model-specific layer
interleaving (MoE vs dense, iRoPE, sliding attention).

## Summary of changes

- Remove all `init_weights` methods from modules (Linear, Embedding,
RMSNorm, FeedForward, GQAttention, MoE, GroupedExperts,
TokenChoiceTopKRouter, RoPE, Decoder).
- Add `param_init` field to `Module.Config`; `Config.build()` propagates
it to the instance as `_param_init`.
- Add `init_states` with auto-recursion, `_init_self_parameters`
(dict-lookup init), and `_init_self_buffers` (module-specific buffer
init).
- Add `DeferredCallable` (in `torchtitan/config/`) for depth-varying
init.
- Add `param_init.py` (in `torchtitan/models/common/`) with
`resolve_deferred`, `skip_param_init`, and `depth_scaled_std` utilities.
- Remove `init_mean`/`init_std` fields from `Linear.Config` and
`Embedding.Config` — init is now expressed entirely through `param_init`
dicts.
- Add `layers` list and `expand_layer_configs()` pattern to all model
registries, replacing per-layer config construction in
`Decoder.__init__`.
- Add `w1`/`w2w3` fields to `FeedForward.Config` and `wqkv`/`wo` fields
to `GQAttention.Config` (replacing `linear_bias: bool`), so each linear
sub-module gets its own `param_init`.

## Verification

Bitwise identical loss against `origin/main` with `--debug.seed=42
--debug.deterministic`:

| Model  | Steps | Result            |
|--------|-------|-------------------|
| Llama3 | 10    | Bitwise identical |
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
…orch#2633)

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

## Motivation

Parameter initialization should be configurable without modifying module
code. Previously, each module defined its own `init_weights` method with
hardcoded init logic (e.g., `nn.init.trunc_normal_` with a fixed std).
This couples initialization strategy to module definitions, making it
impossible to change init behavior without editing model code.

## Design
- **Expand the config to be per-module config**
- `param_init` is a `dict[str, Callable]` on `Module.Config`, mapping
local parameter names to init functions. It is set on every sub-config
in the model config registry.
- `init_states` auto-recurses the module tree (children first, then
self), calling `_init_self_parameters` and `_init_self_buffers` on each
module. Buffer initialization remains module-specific (e.g., RoPE cache,
MoE counters) via `_init_self_buffers` overrides.
- `DeferredCallable.Config` wraps init functions that vary by layer
depth (e.g., depth-scaled std). `resolve_deferred` walks the config tree
and resolves these markers during per-layer config expansion.
- `expand_layer_configs` (per model) deep-copies the layer template N
times, resolves deferred markers, and handles model-specific layer
interleaving (MoE vs dense, iRoPE, sliding attention).

## Summary of changes

- Remove all `init_weights` methods from modules (Linear, Embedding,
RMSNorm, FeedForward, GQAttention, MoE, GroupedExperts,
TokenChoiceTopKRouter, RoPE, Decoder).
- Add `param_init` field to `Module.Config`; `Config.build()` propagates
it to the instance as `_param_init`.
- Add `init_states` with auto-recursion, `_init_self_parameters`
(dict-lookup init), and `_init_self_buffers` (module-specific buffer
init).
- Add `DeferredCallable` (in `torchtitan/config/`) for depth-varying
init.
- Add `param_init.py` (in `torchtitan/models/common/`) with
`resolve_deferred`, `skip_param_init`, and `depth_scaled_std` utilities.
- Remove `init_mean`/`init_std` fields from `Linear.Config` and
`Embedding.Config` — init is now expressed entirely through `param_init`
dicts.
- Add `layers` list and `expand_layer_configs()` pattern to all model
registries, replacing per-layer config construction in
`Decoder.__init__`.
- Add `w1`/`w2w3` fields to `FeedForward.Config` and `wqkv`/`wo` fields
to `GQAttention.Config` (replacing `linear_bias: bool`), so each linear
sub-module gets its own `param_init`.

## Verification

Bitwise identical loss against `origin/main` with `--debug.seed=42
--debug.deterministic`:

| Model  | Steps | Result            |
|--------|-------|-------------------|
| Llama3 | 10    | Bitwise identical |
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.

3 participants