Skip to content

[Module] Model Config Programming - #2785

Merged
fegin merged 16 commits into
mainfrom
gh/fegin/106/head
Apr 4, 2026
Merged

fegin merged 16 commits into
mainfrom
gh/fegin/106/head

Conversation

@fegin

@fegin fegin commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

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

  • 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().

fegin added 2 commits April 1, 2026 12:38
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 1, 2026
**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
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 1, 2026
Comment thread torchtitan/config/configurable.py Resolved
Comment thread torchtitan/config/configurable.py Resolved
Comment thread torchtitan/models/common/attention.py Resolved
Comment thread torchtitan/models/common/attention.py Resolved
}


def model_registry(flavor: str, attn_backend_override: str | None = None) -> ModelSpec:

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 thought this was convenient, what's the motivation of reverting back to old style?

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.

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.

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

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

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.

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

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

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?

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.

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.

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.

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.

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.

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.

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.

@claude review this conversion and give your opinions

Comment thread torchtitan/models/llama4/__init__.py Resolved
fegin added 2 commits April 1, 2026 22:09
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 2, 2026
**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
fegin added a commit that referenced this pull request Apr 2, 2026
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 |
fegin added 2 commits April 2, 2026 16:05
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 2, 2026
**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
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 3, 2026
**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
@tianyu-l

tianyu-l commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

@claude review the conversations under #2785 (comment), list the tradeoffs, and give your opinion

@claude

claude Bot commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

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


Analysis: attn_backend_override in model_registry() vs. pre-defined config variants

  • Read the conversation thread and understand both positions
  • Read relevant code files to understand the implementation details
  • Analyze tradeoffs and provide opinion

The two approaches

Approach A — tianyu-l's (base branch): model_registry() accepts an attn_backend_override parameter. Callers in config_registry.py pass a string like "varlen" or "flex", and the model registry applies the override to the template config.layer.attention before expanding layers.

# config_registry.py (base branch)
model_spec = model_registry("0.6B", attn_backend_override="varlen")

# __init__.py (base branch) — the registry handles the override
def model_registry(flavor: str, attn_backend_override: str | None = None) -> ModelSpec:
    config = qwen3_configs[flavor]()
    if attn_backend_override is not None:
        match attn_backend_override:
            case "varlen":
                config.layer.attention.inner_attention = VarlenAttention.Config()
                config.layer.attention.mask_type = "block_causal"
            # ... other cases
    expand_layer_configs(config)
    ...

Approach B — fegin's (this PR): Each attention backend variant is a separate named config function in __init__.py. Variants derive from the base config via deepcopy + mutation. model_registry() takes only flavor: str with no extra arguments.

# __init__.py (this PR)
def _0_6b_varlen() -> Qwen3Model.Config:
    config = _0_6b()
    varlen_cfg = VarlenAttention.Config()
    layers = []
    for layer_cfg in config.layers:
        layer_cfg = deepcopy(layer_cfg)
        layer_cfg.attention.inner_attention = varlen_cfg
        layer_cfg.attention.mask_type = "block_causal"
        layers.append(layer_cfg)
    config.layers = layers
    return config

qwen3_configs = {
    "0.6B": _0_6b,
    "0.6B_varlen": _0_6b_varlen,
    ...
}

def model_registry(flavor: str) -> ModelSpec:  # no extra args
    config = qwen3_configs[flavor]()
    ...

Tradeoffs

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:

  1. 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. Having attn_backend_override as a runtime parameter to model_registry() creates a special case that undermines this principle. If attention backends get this treatment, what's the principled argument against adding rope_override, norm_override, etc.?

  2. 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.py still defines qwen3_debugmodel_flex, qwen3_debugmodel_varlen, etc. — the combinatorics aren't avoided, just split across two files.

  3. Single source of truth matters. With Approach B, qwen3_configs is the authoritative list of all available model configs. With Approach A, you have to mentally compose qwen3_configs × the match cases in model_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.


[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 3, 2026
**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
@tianyu-l

tianyu-l commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

@claude I partly disagree with your comments. Here are my arguments.

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.

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.

As fegin correctly points out, both approaches produce the same number of named configurations. In Approach A, config_registry.py still defines qwen3_debugmodel_flex, qwen3_debugmodel_varlen, etc. — the combinatorics aren't avoided, just split across two files.

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 model_registry() function.

@claude

claude Bot commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

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


Revised analysis: attn_backend_override parameter vs. pre-defined config variants

  • Re-read the relevant code to ground the analysis
  • Evaluate each counterargument on its merits
  • Provide updated opinion

Addressing each counterargument

1. "The real constraint is configs fully determined before build(), not at authoring time"

This is a fair correction. I overstated the principle. The invariant that matters is config.build() receives no kwargs — and Approach A satisfies this. The attn_backend_override in model_registry() mutates the config before expand_layer_configs() and before build(), so the config is fully resolved by the time it reaches the module constructor. On this point, I was wrong to frame Approach A as violating the PR's constraint.

2. "You don't need the full cartesian product pre-registered"

Looking at the actual code, this is correct and I should have seen it more clearly. In the base branch, qwen3_configs has 12 entries (base flavors only), and the sft_qwen3_8b_math config in config_registry.py uses model_registry("8B", attn_backend_override="varlen") without needing a pre-registered "8B_varlen" model config entry.

In this PR, that forces the creation of _8b_varlen, _0_6b_varlen, _1_7b_varlen etc. as separate functions in __init__.py — bringing the dict from 12 to 16+ entries. It's true that both approaches have the same number of job configs in config_registry.py, but Approach A avoids polluting the model config namespace with variants that exist only because one job config needs them.

The distinction between "model config space" and "job config space" that tianyu-l raised is a legitimate architectural separation. The set of model flavors (0.6B, 1.7B, 4B, 8B...) is fundamentally different from the set of model configurations (8B+varlen, 8B+flex, etc.). Approach A keeps the model config space clean and composes variations at the job config level.

3. "The combinatorial explosion with more axes is a real risk"

This is the strongest argument and the one I underweighted. Let me make it concrete:

Currently there's 1 axis beyond base flavor: attention backend (sdpa, flex, flex_flash, varlen). That's manageable. But consider adding ep_comm_backend (e.g., deepep_low_latency, deepep_normal, default) — that's 3 more options. With Approach B, every model that might use MoE+varlen+deepep_low_latency needs a pre-registered function like _debugmodel_moe_varlen_deepep_low_latency. For N flavors × M attn_backends × K ep_backends, you'd get:

  • Approach A: N base configs + centralized match blocks (~30 lines each) in model_registry() → O(N + M + K) code
  • Approach B: N × M × K variant functions (even with helpers) → O(N×M×K) entries in the config dict

A helper function like _with_attention_backend() (which I suggested last time) reduces the per-variant code but doesn't reduce the number of config dict entries. This is functionally equivalent to having the parameter on model_registry() — the helper IS the parameter, just expressed differently. tianyu-l's observation that "helper functions shared by multiple model configs is not very different from introducing args in model_registry()" is accurate.


Updated opinion

I'm revising my position. Approach A (parameterized model_registry()) is the better design for axes like attention backend, for these reasons:

  1. O(N+M) vs O(N×M) scaling. This is the decisive factor. When orthogonal axes are composed at call time rather than pre-registered, you avoid combinatorial growth in the model config registry. Even if today the numbers are small, the design should accommodate the likely trajectory (EP backends, token dispatchers, etc.).

  2. Clean separation of model flavors vs. model configurations. The qwen3_configs dict represents the set of model architectures (0.6B, 1.7B, etc.), not every possible runtime variant. The attention backend is an orthogonal axis applied on top of a flavor, not a fundamentally different model.

  3. model_registry() is already a configuration step, not a lookup. Even in Approach B, model_registry() calls config() and wraps it in ModelSpec. It's not a pure dict lookup — it's a function that constructs a ModelSpec from a config. Adding backend override logic here is natural.

  4. The helper function "middle ground" I previously suggested doesn't actually solve the problem. It reduces boilerplate per variant but still requires pre-registering every combination. tianyu-l is right that it's equivalent to the parameterized approach with extra steps.

Where I still agree with the PR's direction: The core goal of eliminating kwargs from build() is good. The model_registry() parameter doesn't conflict with this — configs are fully resolved before build() is called. The two ideas (no-kwargs build() and parameterized model_registry()) are orthogonal.

Practical suggestion: If the PR wants to keep model_registry(flavor: str) with no extra args for simplicity, a reasonable compromise is to keep the parameterized form but have it apply at the config_registry.py level where the composition actually happens, rather than forcing all variants into the model config dict. But the base branch approach of having it directly on model_registry() is cleaner because it co-locates the override logic (the match block) with the config expansion that it precedes.


@fegin fegin left a comment

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.

TODOs to fix

Comment thread torchtitan/config/configurable.py Resolved
Comment thread torchtitan/config/configurable.py Resolved
Comment thread torchtitan/models/common/attention.py Resolved
Comment thread torchtitan/models/flux/__init__.py Resolved
Comment thread torchtitan/models/qwen3/__init__.py Resolved
Comment thread torchtitan/models/qwen3/__init__.py Resolved
Comment thread torchtitan/models/qwen3/__init__.py Resolved
Comment thread torchtitan/models/qwen3/__init__.py Resolved

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

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

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.

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

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.

btw the actual layers is a module Dict. Do we want to make this config a dict, to be consistent?

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.

Yes, I tried, but this causes way too many typing errors. I will revisit this later.

Comment thread torchtitan/models/common/decoder.py Resolved
Comment on lines +80 to +86
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()

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.

ooops, this is much less readable

Maybe we can introduce some post_init validation on the config?

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.

Curious, what's your idea of post_init validation? This is an actual build.

@tianyu-l tianyu-l Apr 3, 2026 •

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.

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.

fegin added 2 commits April 3, 2026 13:03
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 3, 2026
**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
fegin added 2 commits April 3, 2026 13:33
[ghstack-poisoned]
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 3, 2026
**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
[ghstack-poisoned]
fegin added a commit that referenced this pull request Apr 3, 2026
**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
@fegin
fegin changed the base branch from gh/fegin/106/base to main April 4, 2026 06:03
@fegin
fegin merged commit 4b33474 into main Apr 4, 2026
28 of 35 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 4, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 4, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 4, 2026
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
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Apr 4, 2026
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.
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 |
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* __->__ pytorch#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()`.
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Apr 14, 2026
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()`.
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 |
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.14.0)
(oldest at bottom):
* __->__ pytorch#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()`.
cursor Bot pushed a commit to bantianyue/torchtitan that referenced this pull request Oct 15, 2026
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]>
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