Repository navigation
[Module] Model Config Programming - #2785
Conversation
[ghstack-poisoned]
**Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Add dim (and layer_id/n_layers where needed) as field(init=False) on TransformerBlock, GQAttention, FeedForward, MoE, and model-specific Attention configs (DeepSeek V3, GPT-OSS, Flux) - Use wqkv/w2w3 as template configs: expand_layer_configs() deep-copies them into per-linear configs (wq/wk/wv, w2/w3) with concrete in_features/out_features - Create shared config expansion helpers in config_expand.py (fill_gqa_fields, fill_ffn_fields, fill_moe_fields, fill_decoder_fields) used by all model registries - Update expand_layer_configs() in all model registries (llama3, llama4, qwen3, deepseek_v3, gpt_oss, flux) to fill all field(init=False) dimensional fields on the entire config tree - Eliminate all build() kwargs from model modules — every build() call is now just config.foo.build() with no arguments - Remove kwargs_in_config code path from Configurable.Config.build() (zero remaining users) - Deduplicate debug model configs in llama3 registry (flex_attn/varlen variants now derive from base debug config) - Update all experiments (VLM, RL, graph_trainer) and unit tests to match the new pattern ghstack-source-id: 6f5f4fa Pull-Request: #2785
| } | ||
|
|
||
|
|
||
| def model_registry(flavor: str, attn_backend_override: str | None = None) -> ModelSpec: |
There was a problem hiding this comment.
I thought this was convenient, what's the motivation of reverting back to old style?
There was a problem hiding this comment.
If you are already doing the config programming, why do you need to set `attn_backend_override during model_registry time? We can just create config_flex, config_varlen, config_sdpa and all three share the same base config and the difference is attn_backend_override.
There was a problem hiding this comment.
Oh the reason is that:
In torchtitan RL effort we only support "varlen" for now, while the default is SDPA. So for any existing model, we'll have to create a varlen variation, and later flex variation, where the only difference is inner attention type. So providing this attn_backend arg saves cartesian product number of model configs.
The idea is similar to Ailing's argument -- users only want to change certain arg more often than others. So it's purely out of convenience concern. In some sense, attention is pretty much the only thing in model code user need to tune, and maybe also EP token dispatcher that @acisseJZhong is working on. So I don't expect the args to model_registry to explode much.
There was a problem hiding this comment.
But we still create qwen3_debugmodel_flex and other similar configs anyway. If so, why do we have two layers of programming? Why not just centralize the same programming flow in once place, __init__.py? Now we need to check config_registry.py to understand someone will pass arguments to mode_registry and we expand it based on that arguments.
We can just pre-register all the model config functions like qwen3_debugmodel_flex: _qwen3_debugmodel_flex in init.py. model_registry(flavor: str) just calls config = llama3_configs[flavor]() and it will guarantee different combinations. I don't see why this is less convenient. And we can leave the arguments for model_registry for runtime information that cannot be decided during __init__.py is imported.
There was a problem hiding this comment.
I think the actual reason was code dedup for cartesian product number of configs [flavors] x [sdpa, varlen, flex]. If your proposal somehow share the code for different combinations, that's OK.
However, this will still be creating cartesian number of model config names, "modelname_[# of flavor]_[#_attn_backends]", which I'm OK with but don't see the benefit.
There was a problem hiding this comment.
The current solution also causes the cartesian product problem, doesn't it? config_registry.py needs to do the cartesian product definitions, no? I'm not strongly against that, but I don't see the difference of the two approaches because both have the cartesian product problem. Am I missing anything?
There was a problem hiding this comment.
More concretely, the current solution defines _qwen3_debugmodel_flex, _qwen3_debugmodel_varlen, and _qwen3_debugmodel_sdpa in config_registry.py. The approach here is to define the same configurations in __init__.py using shared base configs, similar to what the current solution does. But it achieve this without passing attn_backend_override to model_registry().
The config number are the same. If the current solution only defines debugmodel + #_attn_backends, then with this approach, the same number of configurations will be defined in _qwen3.__init__.py. If the current solution enumerates all, this approaches will also enumerate all.
There was a problem hiding this comment.
model config and job config are two different space, the former is limited, the latter is unlimited
e.g. usually you won't call a job config _qwen3_debugmodel_flex , instead it will be
_qwen3_debugmodel_flex_1_5_trillions_tokens_xyz_data_mixing_qwen3_debugmodel_varlen_amd_gpu_midtraining_phase_3- etc.
There was a problem hiding this comment.
Implementation wise, there are not difference since they are both functions, so if you have _qwen3_debugmodel_flex as a training config, which is a function, you will also have qwen3_debugmodel_flex function for this, which will only be executed if users use it. The examples you gave include non-model configurations, but we have argued this last year, attention backend should be a model config.
There was a problem hiding this comment.
@claude review this conversion and give your opinions
[ghstack-poisoned]
**Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Add dim (and layer_id/n_layers where needed) as field(init=False) on TransformerBlock, GQAttention, FeedForward, MoE, and model-specific Attention configs (DeepSeek V3, GPT-OSS, Flux) - Use wqkv/w2w3 as template configs: expand_layer_configs() deep-copies them into per-linear configs (wq/wk/wv, w2/w3) with concrete in_features/out_features - Create shared config expansion helpers in config_expand.py (fill_gqa_fields, fill_ffn_fields, fill_moe_fields, fill_decoder_fields) used by all model registries - Update expand_layer_configs() in all model registries (llama3, llama4, qwen3, deepseek_v3, gpt_oss, flux) to fill all field(init=False) dimensional fields on the entire config tree - Eliminate all build() kwargs from model modules — every build() call is now just config.foo.build() with no arguments - Remove kwargs_in_config code path from Configurable.Config.build() (zero remaining users) - Deduplicate debug model configs in llama3 registry (flex_attn/varlen variants now derive from base debug config) - Update all experiments (VLM, RL, graph_trainer) and unit tests to match the new pattern ghstack-source-id: d7c21ea Pull-Request: #2785
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0) (oldest at bottom): * #2785 * #2780 * __->__ #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 |
[ghstack-poisoned]
**Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove `layer` template field from Decoder.Config; models now require a fully-specified `layers: list[...]` - Remove `field(init=False)` from all config classes (Linear, Embedding, RMSNorm, GQAttention, FeedForward, MoE, GroupedExperts, TokenChoiceTopKRouter, etc.) — all dimensional fields are now regular required fields - Remove `wqkv`/`w2w3` template patterns from GQAttention.Config and FeedForward.Config — use direct `wq`/`wk`/`wv` and `w1`/`w2`/`w3` instead - Remove `expand_layer_configs()` from all model registries — layers are built directly in __init__.py via helper functions - Remove `Function.Config` / `resolve_deferred` for param_init — depth-scaled init dicts are computed directly per-layer - Add shared config builder helpers in `config_helpers.py` (make_gqa_config, make_ffn_config, make_moe_config, etc.) - Delete `config_expand.py` (fill_gqa_fields, fill_ffn_fields, fill_moe_fields, fill_decoder_fields all replaced) - Remove expansion-only fields from TransformerBlock subclass Configs (every_n_layers_nope, interleave_moe_layer_step, n_dense_layers, moe_enabled) - Update all experiments (VLM, RL, graph_trainer, autoparallel, ft) and unit tests ghstack-source-id: 658e073 Pull-Request: #2785
**Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove `layer` template field from Decoder.Config; models now require a fully-specified `layers: list[...]` - Remove `field(init=False)` from all config classes (Linear, Embedding, RMSNorm, GQAttention, FeedForward, MoE, GroupedExperts, TokenChoiceTopKRouter, etc.) — all dimensional fields are now regular required fields - Remove `wqkv`/`w2w3` template patterns from GQAttention.Config and FeedForward.Config — use direct `wq`/`wk`/`wv` and `w1`/`w2`/`w3` instead - Remove `expand_layer_configs()` from all model registries — layers are built directly in __init__.py via helper functions - Remove `Function.Config` / `resolve_deferred` for param_init — depth-scaled init dicts are computed directly per-layer - Add shared config builder helpers in `config_helpers.py` (make_gqa_config, make_ffn_config, make_moe_config, etc.) - Delete `config_expand.py` (fill_gqa_fields, fill_ffn_fields, fill_moe_fields, fill_decoder_fields all replaced) - Remove expansion-only fields from TransformerBlock subclass Configs (every_n_layers_nope, interleave_moe_layer_step, n_dense_layers, moe_enabled) - Update all experiments (VLM, RL, graph_trainer, autoparallel, ft) and unit tests ghstack-source-id: abf2b35 Pull-Request: #2785
|
@claude review the conversations under #2785 (comment), list the tradeoffs, and give your opinion |
|
Claude finished @tianyu-l's task in 3m 23s —— View job Analysis:
|
| Dimension | Approach A (attn_backend_override param) |
Approach B (pre-defined variant functions) |
|---|---|---|
| Cartesian product cost | Fewer config functions — N flavors, with backends applied at call time. But config_registry.py still creates N×M job config functions (qwen3_debugmodel_flex, etc.), so the combinatorial explosion exists regardless. |
Same N×M config entries, just spread across __init__.py (model configs) and config_registry.py (job configs). |
| Code duplication | The match block in model_registry() centralizes the override logic — one place to add a new backend. |
Each variant function repeats the deepcopy-iterate-mutate pattern (~7 lines). Adding a new backend means N new functions (one per flavor that needs it). |
| Discoverability / Single source of truth | To understand which attention backends a model supports, you check two places: __init__.py for base configs and model_registry() for the override logic. The config_registry.py callsite ties them together. |
qwen3_configs dict is the single registry — you see every available (flavor, backend) combination in one place. |
| Separation of concerns | Mixes model config space with a runtime override mechanism inside the model registry function. The model_registry() function becomes partially a config transformer. |
Model configs are fully resolved before model_registry() is called. The registry is a pure lookup. |
| API surface / extensibility | If a new tunable axis emerges (e.g., EP token dispatcher), it can be added as another param to model_registry(). Risk: parameter list grows over time. |
Each new axis requires explicit variant functions. Risk: N×M×K explosion if multiple axes need combinations. Benefit: no risk of parameter accumulation on model_registry(). |
| Downstream/experiment usage | RL code writes model_registry("0.6B", attn_backend_override="varlen") — concise, intent is clear from the call. |
RL code writes model_registry("0.6B_varlen") — equally concise, but the variant must be pre-registered in __init__.py. |
| Consistency with the PR's goal | Retains a layer of late-binding config transformation after initial config creation, which conflicts with the PR's stated goal of "all configs fully resolved before build()". |
Fully aligned with the "no kwargs, no late binding" philosophy of the PR. |
My opinion
Both approaches agree that the cartesian product of (model_flavor, attention_backend) entries must exist somewhere — the debate is really about where the backend variation logic lives and when it executes.
I lean toward Approach B (this PR) for core torchtitan, for these reasons:
-
Architectural consistency. The PR's core thesis is that model configs should be fully determined at configuration authoring time, not at
model_registry()call time. Havingattn_backend_overrideas a runtime parameter tomodel_registry()creates a special case that undermines this principle. If attention backends get this treatment, what's the principled argument against addingrope_override,norm_override, etc.? -
The cartesian product argument is a wash. As fegin correctly points out, both approaches produce the same number of named configurations. In Approach A,
config_registry.pystill definesqwen3_debugmodel_flex,qwen3_debugmodel_varlen, etc. — the combinatorics aren't avoided, just split across two files. -
Single source of truth matters. With Approach B,
qwen3_configsis the authoritative list of all available model configs. With Approach A, you have to mentally composeqwen3_configs× thematchcases inmodel_registry()to understand the full space.
However, I acknowledge a legitimate concern from tianyu-l's side:
The deepcopy-iterate-mutate boilerplate that Approach B introduces for each variant is real overhead. The 7-line pattern repeated in _0_6b_varlen, _1_7b_varlen, _8b_varlen, etc. is tedious. A practical middle ground would be to extract a helper function:
def _with_attention_backend(
base_fn, inner_attention, mask_type="block_causal"
) -> Callable[[], Qwen3Model.Config]:
def _variant():
config = base_fn()
for layer_cfg in config.layers:
layer_cfg.attention.inner_attention = deepcopy(inner_attention)
layer_cfg.attention.mask_type = mask_type
return config
return _variant
# Then:
_0_6b_varlen = _with_attention_backend(_0_6b, VarlenAttention.Config())
_8b_varlen = _with_attention_backend(_8b, VarlenAttention.Config())This gives the per-layer deepcopy logic a single definition (like Approach A's match block) while keeping all model config variants as explicit entries in qwen3_configs (like Approach B). The config space is fully enumerable by reading the dict, and model_registry() stays argument-free.
For the RL experiment specifically, if it needs to use varlen for an arbitrary model without pre-registering the variant, it can do the deepcopy-mutate in its own config_registry.py — this follows torchtitan's principle that experiments shouldn't modify core interfaces.
**Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove `layer` template field from Decoder.Config; models now require a fully-specified `layers: list[...]` - Remove `field(init=False)` from all config classes (Linear, Embedding, RMSNorm, GQAttention, FeedForward, MoE, GroupedExperts, TokenChoiceTopKRouter, etc.) — all dimensional fields are now regular required fields - Remove `wqkv`/`w2w3` template patterns from GQAttention.Config and FeedForward.Config — use direct `wq`/`wk`/`wv` and `w1`/`w2`/`w3` instead - Remove `expand_layer_configs()` from all model registries — layers are built directly in __init__.py via helper functions - Remove `Function.Config` / `resolve_deferred` for param_init — depth-scaled init dicts are computed directly per-layer - Add shared config builder helpers in `config_helpers.py` (make_gqa_config, make_ffn_config, make_moe_config, etc.) - Delete `config_expand.py` (fill_gqa_fields, fill_ffn_fields, fill_moe_fields, fill_decoder_fields all replaced) - Remove expansion-only fields from TransformerBlock subclass Configs (every_n_layers_nope, interleave_moe_layer_step, n_dense_layers, moe_enabled) - Update all experiments (VLM, RL, graph_trainer, autoparallel, ft) and unit tests ghstack-source-id: 6729b0d Pull-Request: #2785
|
@claude I partly disagree with your comments. Here are my arguments.
The real constraint we would like to have is not "model configs should be fully determined at configuration authoring time", but "model configs should be fully determined before calling config.build()". As long as the config we obtain from config_registry.py is fully ready, that's good enough.
I disagree, because in reality you may not need the full cartesian product of model configs in config_registry. The attn_backend arg in model_registry gives you the option to not pre-define a model config if it's not used by any config_registry. One could argue that we don't have to have all the full cartesian product of model configs such as "_0_6b_varlen" in init.py, either. But it would be hard to predict what would be needed, what wouldn't be. Moreover, the risk of having exploded amount of model configs is real. E.g. if we add more options in addition to attn_backend, let's say three different ep_comm_backend options, then the number of pre-registered model configs would be num_model_size_variants * num_attn_backends * num_ep_comm_backend, which will soon become a burden to maintain. You could introduce helper functions that's shared by multiple model configs, but that seems not very different from introducing args in |
|
Claude finished @tianyu-l's task in 5m 54s —— View job Revised analysis:
|
tianyu-l
left a comment
There was a problem hiding this comment.
Overall lgtm! See if #2785 (comment) makes more sense to you, but we don't have to converge in this PR.
| rope: RoPE.Config | ||
| layer: TransformerBlock.Config | ||
| layers: list | None = None | ||
| layers: list # list[TransformerBlock.Config] or subclass configs |
There was a problem hiding this comment.
can we just type it with list[TransformerBlock.Config]? I feel it should be compatible as long as each element in the list is a subclass of TransformerBlock.Config
There was a problem hiding this comment.
btw the actual layers is a module Dict. Do we want to make this config a dict, to be consistent?
There was a problem hiding this comment.
Yes, I tried, but this causes way too many typing errors. I will revisit this later.
| self.wq_a = config.wq_a.build() | ||
| self.q_norm = config.q_norm.build() | ||
| self.wq_b = config.wq_b.build() | ||
| self.wkv_a = config.wkv_a.build() | ||
| self.kv_norm = config.kv_norm.build() | ||
| self.wkv_b = config.wkv_b.build() | ||
| self.wo = config.wo.build() |
There was a problem hiding this comment.
ooops, this is much less readable
Maybe we can introduce some post_init validation on the config?
There was a problem hiding this comment.
Curious, what's your idea of post_init validation? This is an actual build.
There was a problem hiding this comment.
e.g. the shapes of consecutive matmal would match against each other
In traditional attention, it was simpler to reason. For MLA it's very hard to infer what each weight's shape is, by only looking at model code in this file.
[ghstack-poisoned]
**Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove `layer` template field from Decoder.Config; models now require a fully-specified `layers: list[...]` - Remove `field(init=False)` from all config classes (Linear, Embedding, RMSNorm, GQAttention, FeedForward, MoE, GroupedExperts, TokenChoiceTopKRouter, etc.) — all dimensional fields are now regular required fields - Remove `wqkv`/`w2w3` template patterns from GQAttention.Config and FeedForward.Config — use direct `wq`/`wk`/`wv` and `w1`/`w2`/`w3` instead - Remove `expand_layer_configs()` from all model registries — layers are built directly in __init__.py via helper functions - Remove `Function.Config` / `resolve_deferred` for param_init — depth-scaled init dicts are computed directly per-layer - Add shared config builder helpers in `config_helpers.py` (make_gqa_config, make_ffn_config, make_moe_config, etc.) - Delete `config_expand.py` (fill_gqa_fields, fill_ffn_fields, fill_moe_fields, fill_decoder_fields all replaced) - Remove expansion-only fields from TransformerBlock subclass Configs (every_n_layers_nope, interleave_moe_layer_step, n_dense_layers, moe_enabled) - Update all experiments (VLM, RL, graph_trainer, autoparallel, ft) and unit tests ghstack-source-id: de844a5 Pull-Request: #2785
[ghstack-poisoned]
**Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove `layer` template field from Decoder.Config; models now require a fully-specified `layers: list[...]` - Remove `field(init=False)` from all config classes (Linear, Embedding, RMSNorm, GQAttention, FeedForward, MoE, GroupedExperts, TokenChoiceTopKRouter, etc.) — all dimensional fields are now regular required fields - Remove `wqkv`/`w2w3` template patterns from GQAttention.Config and FeedForward.Config — use direct `wq`/`wk`/`wv` and `w1`/`w2`/`w3` instead - Remove `expand_layer_configs()` from all model registries — layers are built directly in __init__.py via helper functions - Remove `Function.Config` / `resolve_deferred` for param_init — depth-scaled init dicts are computed directly per-layer - Add shared config builder helpers in `config_helpers.py` (make_gqa_config, make_ffn_config, make_moe_config, etc.) - Delete `config_expand.py` (fill_gqa_fields, fill_ffn_fields, fill_moe_fields, fill_decoder_fields all replaced) - Remove expansion-only fields from TransformerBlock subclass Configs (every_n_layers_nope, interleave_moe_layer_step, n_dense_layers, moe_enabled) - Update all experiments (VLM, RL, graph_trainer, autoparallel, ft) and unit tests ghstack-source-id: 7063be5 Pull-Request: #2785
**Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove `layer` template field from Decoder.Config; models now require a fully-specified `layers: list[...]` - Remove `field(init=False)` from all config classes (Linear, Embedding, RMSNorm, GQAttention, FeedForward, MoE, GroupedExperts, TokenChoiceTopKRouter, etc.) — all dimensional fields are now regular required fields - Remove `wqkv`/`w2w3` template patterns from GQAttention.Config and FeedForward.Config — use direct `wq`/`wk`/`wv` and `w1`/`w2`/`w3` instead - Remove `expand_layer_configs()` from all model registries — layers are built directly in __init__.py via helper functions - Remove `Function.Config` / `resolve_deferred` for param_init — depth-scaled init dicts are computed directly per-layer - Add shared config builder helpers in `config_helpers.py` (make_gqa_config, make_ffn_config, make_moe_config, etc.) - Delete `config_expand.py` (fill_gqa_fields, fill_ffn_fields, fill_moe_fields, fill_decoder_fields all replaced) - Remove expansion-only fields from TransformerBlock subclass Configs (every_n_layers_nope, interleave_moe_layer_step, n_dense_layers, moe_enabled) - Update all experiments (VLM, RL, graph_trainer, autoparallel, ft) and unit tests ghstack-source-id: 8d6dc02 Pull-Request: #2785
Brings in 7 upstream commits, notably the config system refactor that removes field(init=False)/build() kwargs in favor of fully-specified configs at creation time.
Remove Function.Config / resolve_deferred / expand_layer_configs in favor of fully-specified per-layer configs built at creation time: - Add _build_agpt_layers() using make_gqa_config / make_ffn_config - Set all dimensional fields (in_features, out_features, normalized_shape, num_embeddings, embedding_dim) explicitly - Replace layer= template with layers= list - Replace _LINEAR_DEPTH_INIT (Function.Config) with _depth_init() - Apply flex/varlen attention as overlays on base configs - Remove expand_layer_configs() call from model_registry() Mirrors upstream llama3/__init__.py pattern from pytorch#2785.
Update Attention, moeTransformerBlock, and moeModel for the Model Config Programming pattern (pytorch#2785): - Attention: add dim field to Config, remove dim kwarg from __init__, all .build() calls take no kwargs, remove default_factory on inner_attention (now required) - moeTransformerBlock: remove n_dense_layers from Config (layer selection now happens at config creation time), remove layer_id/dim/ n_layers kwargs from __init__ - moeModel: remove n_layers and layer fields from Config, mutate attention configs in-place in update_from_config instead of dataclasses.replace
Remove Function.Config / resolve_deferred / expand_layer_configs in favor of fully-specified per-layer configs built at creation time: - Add _make_moe_attn_config() builder with all Linear/RMSNorm dimensional fields set (mirrors _make_dsv3_attn_config) - Add _build_moe_layers() with dense/MoE layer selection per layer_id - Replace _LINEAR_DEPTH_INIT / _EXPERTS_DEPTH_INIT (Function.Config) with _depth_init() / _depth_experts_init() functions - Convert all config entries to lazy factory functions - Use make_moe_config / make_router_config / make_experts_config / make_ffn_config from config_utils - Remove expand_layer_configs() call from model_registry() Mirrors upstream deepseek_v3/__init__.py pattern from pytorch#2785.
…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 |
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0) (oldest at bottom): * __->__ pytorch#2785 **Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove all `field(init=False)` fields. - No template fields. - All the configs fields must be constructed before `build()` is called. - No, kwargs is allowed unless the kwargs is not in the config. Overwriting config must happen before `build()`.
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0) (oldest at bottom): * __->__ pytorch#2785 **Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove all `field(init=False)` fields. - No template fields. - All the configs fields must be constructed before `build()` is called. - No, kwargs is allowed unless the kwargs is not in the config. Overwriting config must happen before `build()`.
…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 |
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0) (oldest at bottom): * __->__ pytorch#2785 **Summary** The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time. There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (**after this PR is landed, rebasing is a nightmare for such a PR, lol**). For experimental models, authors/owners can decide however they want to orchestrate the model construction. **Key changes** - Remove all `field(init=False)` fields. - No template fields. - All the configs fields must be constructed before `build()` is called. - No, kwargs is allowed unless the kwargs is not in the config. Overwriting config must happen before `build()`.
Annotate Decoder.Config.layers and DeepSeek MTPDecoder.Config.mtp_layers; clear pytorch#2936 / pytorch#2785 typing TODOs. Use cast() at flavor boundaries for list invariance and getattr for DeepSeek/Kimi optional fields. Signed-off-by: bantianyue <[email protected]> Co-authored-by: bantianyue <[email protected]>
Stack from ghstack (oldest at bottom):
Summary
The title is a bit click-baity, but it captures the goal of this and previous PRs. After this PR, all model modules' build() require no kwargs. Each model spec should be fully defined, calculated, and inferred before build() is called — basically during configuration authoring time.
There are many different ways to program the configurations; this (and previous) PRs use one design that I think balances readability, explicitness, and verbosity. It may not fit other people's taste. We can further discuss how default core model config programming style should look (after this PR is landed, rebasing is a nightmare for such a PR, lol). For experimental models, authors/owners can decide however they want to orchestrate the model construction.
Key changes
field(init=False)fields.build()is called.build().