Repository navigation
Conversation
| lines: list[str] = [] | ||
| for target, names in conflicts.items(): | ||
| lines.append(" " + target.__qualname__ + ": " + ", ".join(sorted(names))) | ||
| raise ValueError( |
There was a problem hiding this comment.
if you have two overrides 1 targeting a parent of another do you think ti should also warn?
There was a problem hiding this comment.
Great point. In that case, I'd just error out (in first version). WDYT?
There was a problem hiding this comment.
Yeah I think that policy makes sense
| def first(cfg): | ||
| return cfg | ||
|
|
||
| with self.assertRaises(ValueError, msg="already registered"): |
There was a problem hiding this comment.
I think you want rasiesRegex
| _check_conflicts() | ||
|
|
||
| replacements: list[str] = [] | ||
| for override in _REGISTRY.values(): |
There was a problem hiding this comment.
nit: youare potentially applying all mods in the registry even if not requested in override config
There was a problem hiding this comment.
Good catch. In the current version, if a mod appears in the import chain, it'll be applied regardless if it's in override config or not. I think my intention was to strictly limit to things in the override config, to be explicit.
| if config.override.modules: | ||
| from torchtitan.registry import apply_overrides | ||
|
|
||
| apply_overrides(model_config, config.override) |
There was a problem hiding this comment.
had a long convo with codex about the odering of:
The intended contract is that factories receive the post-
update_from_configconfig and are responsible for translating/preserving relevant fields into the replacement config. I agree this should be documented explicitly, especially for common Module.Config fields like param_init and sharding_config, and we can add a regression test to lock that expectation down.
And I kind of agree that if we can have some programmatic way to enforce the overrides makes a config matching copy that would be good, or maybe we just re-order?
There was a problem hiding this comment.
And I kind of agree that if we can have some programmtic way to enforce the overrides makes a config matchign copy that would be good, or maybe we just re-order?
By re-order I assume you mean put apply_overrides earlier, say before update_from_config? I don't think we could do that, because update_from_config will set sharding config that's specific to the pre-override module.
I deliberately put apply_overrides after update_from_config before model build, to give override a chance to do a complete replacement, including param_init and sharding_config. I feel that even if we don't add additional check, the existing code will error out at the places that consume these fields, but I agree that providing helpful error messages at proper place would be good, for both humans and agents.
| INFO: Applied 32 module overrides | ||
| ``` | ||
|
|
||
| ### External Packages |
There was a problem hiding this comment.
Do you have a criteria for landing in-repo vs keeping as external in mind?
There was a problem hiding this comment.
Right now I can think of three layers, corresponding to the three goals.
- [GOAL 1] If we don't land it, the perf will look awkward (whether it's pretrain fwd-bwd / RL generator fwd-only) and thus hurt torchtitan. Then let's land it in-repo, which also serves as an example of how to use this plug-in mechanism. It can be for specific common hardware we have access to in CI.
- [GOAL 2] Our team may develop experimental features in torchtitan, in the
experimentsfolder. They can choose to use existingModelConfigConverters(more explicit), or to use this registration mechanism (less explicit, but doesn't need to create extraconfig_registry). Not a huge difference here. - [GOAL 3] For external community to showcase their advanced technologies which we are not ready to depend on in-repo (including hardware that we don't have access in CI), we recommend them being out-of-repo.
| ``` | ||
|
|
||
| ```bash | ||
| pip install torchtitan-vendor-x |
There was a problem hiding this comment.
what's the thinking on version compatibility? should we recommendtorchtitan-vendor-x to pin against a torchtitan version? the external packages depend on titan's module signatures.
There was a problem hiding this comment.
There are two layers
- Being able to modify torchtitan config without touching torchtitan code. This is fundamental capability, unblocking development inside/outside the team, which is what I wanted to focus on in this RFC.
- Above that, there is this version compatibility, which can be (and I think has to be) handled in the way you suggested. I agree it's good to clarify it in the RFC itself.
There was a problem hiding this comment.
How about pytorch version? Should vendor package also walk along nightly pytorch similar to TorchTitan? Wondering how to avoid this scenario in the future and reduce maintenance burden from TorchTitan: #3390.
There was a problem hiding this comment.
torchtitan should publish stable versions that align with pytorch stable versions. Vendor packages probably only needs to care these versions backed by pytorch stable releases.
torchtitan could publish more frequently as we are doing active (BC-breaking) development, or working closely with vendor to unblock new features that vendor would like to showcase. But in this case, vendor package has to be OK with some pytorch nightly being pinned.
| `apply_fn(xq, xk, cache, positions)`. In a follow-up, each attention layer will own | ||
| its own RoPE module as a submodule, making it naturally replaceable via the config tree. | ||
|
|
||
| ## Parallelism Compatibility |
There was a problem hiding this comment.
IIUC, CP is applied on the Attention module, and it's composability interface to consider.
There was a problem hiding this comment.
With recent refactor, all SPMD parallelism (other than FSDP) would be encoded in sharding config; in the near future (e.g. when FlexShard is ready), the storage placement would also be put in config.
So it's the author's responsibility to make sure correct sharding config is provided during config swapping.
A concrete example, if someone would like to implement fused ring-based CP, they can do
- assuming inputs and outputs are sharded on sequence dimension
- use
LocalMapConfigas the contract for above - explicit call send/recv/all-to-all collectives in the CP Attention implementation
|
|
||
| ```bash | ||
| torchtitan_train --module llama3 --config llama3_8b \ | ||
| --override.modules='["torchtitan.registry.triton_rope"]' |
There was a problem hiding this comment.
For agentic hillclimb, I think we need to make the system much more pluggable and overridable, so agent can swap out any components. E.g. swap module impl, optimizer, kernels... (and more).
GraphTrainer currently have 4 open registry, see torchtitan/experiments/graph_trainer/registry.py
User can customize pass_pipeline, memory policy, some hooks to run in the trainer.step()...
I am also further extending the registry to "fusion region extractor" and "kernel generator" in this prototype
https://github.com/pytorch/torchtitan/compare/kernel-fusion-workflow?expand=1
Agent can bring its own "extractor", and try various kernel provider (e.g. KernelAgent, torch.compile, Helion codegen...) to optimize kernel.
There was a problem hiding this comment.
I think we need to make the system much more pluggable and overridable, so agent can swap out any components. E.g. swap module impl, optimizer, kernels... (and more).
Totally, we can make it support any Configurable swapping in the first version. I think that'd be enough, because you can swap anything in the config tree, all the way up to trainer.
syed-ahmed
left a comment
There was a problem hiding this comment.
Thank you @tianyu-l ! Love this! Let's ship it. Soliciting more comments from colleagues.
| compatibility. Should the registry enforce or validate this? | ||
|
|
||
| 3. **Scope of traverse:** Currently limited to `model_config` (the model's Config tree). | ||
| Should it extend to the full `Trainer.Config` tree (optimizer, dataloader, etc.)? |
There was a problem hiding this comment.
Here are couple use cases for overriding optimizers:
- mixed precision optimizers that we had deeply integrated with torchtitan/pytorch before: Add bf16 optimizer state support via step pre-hook #2732, DeepSeek: mixed precision optimizers (BF16AdamW) pytorch#146542
- emerging optimizers: https://github.com/NVIDIA-NeMo/Emerging-Optimizers.
| Current proposal uses "override" throughout. | ||
|
|
||
| 2. **Checkpoint compatibility:** Override authors are responsible for state_dict key | ||
| compatibility. Should the registry enforce or validate this? |
There was a problem hiding this comment.
Could you please point to the state_dict key this referring to? Is this mainly to make sure e2e workflows like loading model into vllm after training in torchtitan has a good UX when using custom modules from registry?
There was a problem hiding this comment.
This is talking about the checkpoint compatibility before vs. after override.
It may or may not be necessary depending on what we want to do:
- In pretraining, if we just want to swap to efficient implementation and train from scratch, it doesn't matter if the checkpoint from the original (slow) impl can be loaded to new (efficient) impl at all.
- For continued training / sft when loading from a HF checkpoint, torchtitan only provides state dict adapter from HF checkpoint fqn to torchtitan native fqn. If the new impl doesn't work torchtitan native fqn, then it needs to override the state dict adapter in the config as well. It is not obvious why the new impl wouldn't follow the native fqn.
- For RL between trainer and generator, existing effort is using the same model definition, so checkpoint would be naturally compatible. In the future, I can imagine that people do different optimizations on trainer model and generator model. In that case, it should be desired that the state dict is still compatible, to avoid any fqn remapping, which itself is error-prone (we will still need to do resharding).
There was a problem hiding this comment.
If the new impl doesn't work torchtitan native fqn, then it needs to override the state dict adapter in the config as well.
Could we address this by allowing an optional state_dict_translator argument to @register? It would be propagated to the existing from_hf / to_hf functions, eventually enabling things like:
@register("fused_ffn", target=FeedForward.Config,
state_dict_translator=ffn_translator,
description="Fused FFN")
def fused_ffn(cfg):
return FusedFFN.Config(
dim=cfg.w1.in_features,
hidden_dim=cfg.w1.out_features,
param_init={"fused_gate_up.weight": ..., "fused_down.weight": ...},
...
)This way, override authors can freely use their own internal FQN while still loading/saving checkpoints in a compatible format. Does this approach make sense to you?
There was a problem hiding this comment.
How is that different from the checkpointing hook idea in #3396 (comment)?
I'm not seeing the full proposal on state_dict_translator, but it seems requiring inventing one more mechanism in the current Module class? If it can be directly covered by subclassing and overriding state_dict / load_state_dict, I tend to not introduce more mechanisms.
There was a problem hiding this comment.
I think there is no difference, both seek to bridge the canonical and override internal fqn, but if state_dict itself can eventually be overriden (seems it doesn't have a Config for the time being?), that would be the simplest approach.
There was a problem hiding this comment.
I seem to be wrong after playing with the idea for a bit.
Created #3569 to track the issues. Wish to land this version first.
|
|
||
| 4. **Filter functions:** v1 replaces ALL instances of a target Config class. Should we | ||
| support per-instance filtering (e.g., "only replace RoPE in layers 0-10") in the | ||
| `@register` API, or is that a v2 feature? |
There was a problem hiding this comment.
Supporting per-instance filtering is required for NVFP4 training (check layer sensitivity section here: https://arxiv.org/pdf/2509.25149). Also seems like MXFP8 training also cares about this:
There was a problem hiding this comment.
Sure, I can add that in the first version. What would be good enough, e.g. fqn / regex / etc.?
some existing examples:
https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/quantization/mx.py#L54
https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/lora.py#L157
There was a problem hiding this comment.
I think fqns should be good enough for now.
There was a problem hiding this comment.
I'll update the NVFP4 integration to use this once it's ready. Right now it's just replacing every linear layer.
|
|
||
| class TritonRoPE(Module): | ||
| """RoPE implementation using Triton kernels.""" | ||
|
|
There was a problem hiding this comment.
I'm interested in adding a Fused SwiGLU module, ideally we may want to be able to also customize the __init__ parametrization so that a kernel can access w1 and w3 as a single contiguous buffer:
Unfused (current):
x1 = x @ w1.T # w1: [H, D]
x3 = x @ w3.T # w3: [H, D]
out = (F.silu(x1) * x3) @ w2.T # w2: [D, H]
Fused:
y13 = x @ w13.T # w13: [2H, D]
x1, x3 = y13.chunk(2, dim=-1)
out = (F.silu(x1) * x3) @ w2.T
I think GroupedExperts.__init__ gets called before loading weights though, so the module needs to keep the same FQNs, unless we expose some post_init hook that can further customize parametrization? I'm not sure how it would interact with parallelization though.
There might be still a way to implement w1 and w3 as chunks of a larger contiguous allocation, and have the kernel read from them as if they were 1.
Any concerns with allowing modules to do this?
There was a problem hiding this comment.
This is interesting case!
I think GroupedExperts.init gets called before loading weights though, so the module needs to keep the same FQNs, unless we expose some post_init hook that can further customize parametrization?
Sounds the right approach to me, if we want to load a checkpoint saved from unfused (and not introduce any more complicated state dict adapter in tree).
I'm not sure how it would interact with parallelization though.
For TP, if w13 is of shape [2*D, H], making it colwise sharded, the placement would still be Shard(1), which is expressible by spmd_types.
I was wrong: the colwise sharding should happen on D, not H, thus couldn't be expressed today.
There was a problem hiding this comment.
For FusedMLP, if I want to use the new registry system (take used w13, w2), I would need to do following:
- Set correct ShardingConfig for w13 and w2 then registry
- Add load_state_dict(), state_dict() function in my registry (We should use hooks for that?)
Is there anything I missed? Or current registry is not able to handle FusedMLP?
There was a problem hiding this comment.
Today it is not supported, issue summarized in #3569
We probably need something as @sdmyzlp mentioned in #3396 (comment)
There was a problem hiding this comment.
I corrected the sample, the w13 would concat on H dim, not D dim
| from torchtitan.registry import register | ||
| from torchtitan.models.common.moe import MoE | ||
|
|
||
| class VendorXFusedMoE(Module): |
There was a problem hiding this comment.
In this design, can we in addition fuse communication? like, can i have a kernel that does allreduce + rmsnorm?
There was a problem hiding this comment.
Of course we can, as long as the ShardingConfig at the module boundary is set correct.
| def register( | ||
| name: str, | ||
| *, | ||
| target: type, |
There was a problem hiding this comment.
better if it's Type[Configurable.Config] or type[Configurable.Config]?
| etc.) for TP/FSDP to work. Model-specific `parallelize_fn` functions may reference | ||
| specific module types. |
There was a problem hiding this comment.
what does reference specific module types mean? right now each model's parallelize_fn have access to only model?
There was a problem hiding this comment.
Our direction is to remove model-specific parallelize_fn and push parallelism into config. So I wouldn't read hard into this (AI-generated) sentence.
There was a problem hiding this comment.
Yeah that makes more sense. Maybe ask ai to polish this as community users might not get this if we commit this md?
There was a problem hiding this comment.
Yeah I'll polish everything; this is more like an RFC with real code.
| submodule structure). | ||
|
|
||
| **Long-term:** Push parallelism fully into the Module protocol so `parallelize_fn` | ||
| doesn't need to know module types. This aligns with torchtitan's ongoing direction |
There was a problem hiding this comment.
what will this look like?
There was a problem hiding this comment.
Like your MoE refactor, TP/CP/EP works with config-based module boundary redistribute.
For FSDP / FlexShard, we will put bucketing and storage placement into config as well.
| Current proposal uses "override" throughout. | ||
|
|
||
| 2. **Checkpoint compatibility:** Override authors are responsible for state_dict key | ||
| compatibility. Should the registry enforce or validate this? |
There was a problem hiding this comment.
how could we tell if users' override will cause ckpt compatability issues? For customized kernel it probably won't change model weights, but it will for fused module?
There was a problem hiding this comment.
It depends on user purpose when swapping modules / configs. It is possible that user may not care about ckpt compatibility at all (e.g. train from scratch with efficient impls, or experimenting with a complete new module).
When they care:
- obvious errors should be caught by DCP or torchstore
- authors who implement the fused module should be responsible for ckpt compatibility, e.g. guard by unit test. See related discussion https://github.com/pytorch/torchtitan/pull/3396/changes/BASE..f3bfee46b599269483e972f8320c530876684f03#r3270109556
| ## Interaction with Existing Converters | ||
|
|
||
| Existing converters (Float8, LoRA) run inside `model_registry()` during config | ||
| construction. Overrides run later in `Trainer.__init__`. The override sees the |
There was a problem hiding this comment.
so the order is first model config convertor, and then overrides. wondering is this better then the other way?
There was a problem hiding this comment.
I think so.
In-repo config converter may not understand overrides at all. Overrides author knows everything, so if they believe a in-repo converter could work with their override, they could
- swap inner module of a converted module, e.g. https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/lora.py#L115
- swap the entire converted module, and then apply in-repo converter again inside the override
There was a problem hiding this comment.
I want to patch to batch invariant kernels, so seems it might be further override by other kernel overrides. Should we consider batch-invariant mode as a converter, because it's mostly op-level override, right?
There was a problem hiding this comment.
We have one for flex https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/config_registry.py#L40
I think in general
- batch invariance enablement is not only done at Module level, but also has such implicit behavior https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/utils.py#L259, https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/attention.py#L140. It's not clear to me if we should make batch invariance application a single config converter
- batch invariance mode right now is a core feature; overrides, on the other hand, is more for unblocking purpose, and I don't want to promise any property in core to be still available on arbitrary overrides. E.g. if user enable quantization in titan config (not a proper example because we are moving away from such design), but swaps in a non-quantized linear through override, it's not titan's responsibility to quantize whatever they plugged in. Similar for batch invariance.
| |----------|--------|------|--------------|----------| | ||
| | Custom module file (recommended) | Yes | No (edit file) | None | Simple, fully typed, no infra. Changing params requires file edit. | | ||
| | Untyped kwargs dict | No | Yes | ~50 lines | CLI-friendly but error-prone, awkward nested dict syntax. | | ||
| | Typed override Config (like ModelConfigConverter) | Yes | Yes | ~100 lines | Couples config_registry to override package, defeating the "no-touch" goal. | |
There was a problem hiding this comment.
seems model config convertor can be covered by Custom module file (recommended)?
There was a problem hiding this comment.
That's correct. The override is actually very powerful, but it doesn't mean we should use it whenever we can; in fact, I would suggest we use it as little as possible for in-repo development.
Dynamic import and dependency injection would make code less straightforward in general. Even the ModelConfigConverter makes it somewhat worse than building everything you need bottom-up from scratch (remember we had this quantization "as converter" or "from direct build" discussion). Override registration is taking a step further, but comes with its own tradeoff.
| a clean extension mechanism. | ||
|
|
||
| 2. **Fused module implementations.** An efficient MoE implementation may fuse the | ||
| dispatcher-compute-combine pipeline with custom routing, communication, and |
There was a problem hiding this comment.
can't wait to see megamoe in titan!!
|
|
||
|
|
||
| def _check_conflicts() -> None: | ||
| """Raise if two overrides target the same Config class.""" |
There was a problem hiding this comment.
haven't reviewed the rest yet, but do you deal with the situation where one override targets Parent and another override targets Child? I guess there are a few scenarios
- new parent still has a version of child: we could expect the child in the new parent to also be overridden. but wed have to make sure to do the parent override first and then then the child override
- new parent doesn't even have the child anymore (it has a different structure). The child override now needs to be discarded, which I think is ok as a silent no-op?
There was a problem hiding this comment.
It seems this is NOT the same question as #3396 (comment), and you are talking about A owns B, and our target is A (and B).
If so, my answer would be:
it's all up to the new implementation of A
- if new A still has child B, it can extract old A's child B and plug in new A; or it can create its new B (if B only appears in A, one doesn't need to override B)
- if new A doesn't have B any more, that's totally fine, and the Bs which belong to old A just disappear
There was a problem hiding this comment.
changing the design a bit -- both scenarios are handled by an explicit error
| model = self.model | ||
| if model is None: | ||
| return | ||
| if isinstance(model, config_cls): |
There was a problem hiding this comment.
So this if will only be hit when a user override the whole model?
eg, target=Decoder.Config. Is it valid? Should we directly ban this behavior?
There was a problem hiding this comment.
I ended up allowing that. E.g. a multimodal model may have Decoder as a child module -- I don't feel we have strong reasons to not allow swapping that.
fegin
left a comment
There was a problem hiding this comment.
Left some questions and nits.
| if isinstance(model, config_cls): | ||
| yield "model", model, self, "model" |
There was a problem hiding this comment.
It seems that we will be able to repalce the entire model using override. Not quite sure if my understanding is correct.
There was a problem hiding this comment.
Yes, I ended up allowing that. See my response to wwwjn above.
| if cfg.w1.param_init is not None and "weight" in cfg.w1.param_init: | ||
| param_init = {"w13": cfg.w1.param_init["weight"]} |
There was a problem hiding this comment.
we actually make w2w3 share the same init function. You code here is not wrong. But should we consider to avoid making w2 and w3 have the same init function?
There was a problem hiding this comment.
I ended up faithfully following what's specified today, i.e. w1 and w2 having different init fns.
|
@claude Please do a deep review focused on subtle correctness bugs and regressions that are easy for human reviewers to miss. Prioritize findings over summary. I dont care about anything that isnt a real bug drop all the noise but that, if you there isnt anything to report just say so with a small comment |
|
Claude finished @drisspg's task in 6m 19s —— View job Deep correctness reviewI read through the core override logic ( Bug: Ancestor conflict detection broken across the
This means the model lives at FQN Concrete scenario: Override A targets Severity: Low-to-medium. It requires someone to override the entire model config and a component inside it simultaneously, which is unusual. But the conflict detection exists precisely for this class of mistake, and it fails here. A simple fix: when Everything else I examined appears correct:
|
2026/06/07 update:
Addressed most comments, and aimed for landing, with latest design updated in
torchtitan/config/OVERRIDE.mdIn particular, I created a
FusedSwiGLUoverride, but admitted that checkpoint incompatibility between fused and non-fused version. Issue tracked in #3569.With the following main goals
[GOAL 1]
Provide users a way to use efficient kernels that are not "native implementations".
torchtitan/registryfolder grows too quick / becomes messy, we probably should create a separate repo to host overrides[GOAL 2]
Provide team a way to experiment with and showcase non-trivial implementations, without making intrusive changes to the rest of repo
[GOAL 3]
Provide hardware vendors a way to override modules, without touching the main repo.
[NO GOAL]
torch.libraryPlease read torchtitan/registry/DESIGN.md for details. Feedback is welcome.
Additional notes