Repository navigation
[Config][CP] Implement ModelTransform internface and use CP as the first example - #4322
Conversation
[ghstack-poisoned]
| _SEQ_DIM = 0 | ||
|
|
||
|
|
||
| def use_cp_kernel(config: "Trainer.Config", kernel: type[Module]) -> None: |
There was a problem hiding this comment.
Why would you take Trainer.Config, instead of just BaseModel.Config?
There was a problem hiding this comment.
trying to wrap my head around that this is kinda doing parallelize work, but not under parallelize, and has to be called separately
There was a problem hiding this comment.
There are two ways of creating a config
- Like here, first create a base version and then apply transformation. But this is just a
ModelConfigConverter, so if we follow this way, we should create aModelConfigConverter - Instead of transformation, in the first place create the target. If we ban CLI parallelism change, we could have done this together with
model_registry(attn_backend="flex", cp_backend="all-gather")
I like the latter slightly more, because with multiple converters we have to worry about the ordering of applications.
There was a problem hiding this comment.
First of all, for your example, separating attn_backend and cp_backend is an orthogonal discussion. I want make it clear so that we are not confused during the discussion; model converter can also achieve the same thing.
The major problem of ModelConfigConverter is not ordering but fusion. We can solve A->B->C by declaring the ordering somewhere. And model_registry doesn't escape this problem -- we write down the order in model_registry. The problem exists in both approaches with different solutions, but it is solvable.
The major issue of ModelConfigConverter is fusion,A(B()) or B(A()). What is the best way to do fusion is not clear to me. I haven't thought this clearly yet. And ordering must be designed in a force-able way such that people won't forget adding it.
The major issue of model_registry is the UX. The arguments of model_register is going to be complicated. For example, in the future, we need to support different attentions with different CP backends. These arguments need to be in model_registry's arguments and the complexity of arguments will inflate. model_registry become the central complexity.
So for me, ModelConfigConverter gives a better UX, but ordering (should be solvable but need more design than model_registry) and fusion are the two weak points of ModelConfigConverter.
model_registry makes solving ordering easier -- developers look at a central point to develop different optimization, we solve the ordering problem when developing a new transformation. But I don't like its UX.
There was a problem hiding this comment.
The major issue of ModelConfigConverter is fusion,A(B()) or B(A()). What is the best way to do fusion is not clear to me.
I didn't understand what is "fusion" here. Could you give an example?
These arguments need to be in model_registry's arguments and the complexity of arguments will inflate. model_registry become the central complexity.
Yes, I'm sure it will. See e.g. #4328
There was a problem hiding this comment.
Hi, weighing in since my opinion was asked (bias disclosure: I build my configs directly, so I've never needed these).
I'm not a big fan of the transformations because they need knowledge of the whole config to behave as expected. What if there's no attention module? What if it isn't where you'd expect? What if you want CP on only some layers (odd, I know)? The transformation has to rely on knowledge that may not even be available. And anything that changes on the config side now has to be ported to the transformations too.
In practice I use model_registry when a default config suffices, and build directly when I need something custom:
Trainer.Config(
model=Decoder.Config(
layers=[...],
...
),
...
)When I need customization I write a function for it, one that takes parameters and returns a config, rather than one that edits a config that already exists.
This also answers the inflation worry: CP never needs to enter model_registry's signature. It's enough that the CP settings have their own config object, so it's discoverable how CP is configured.
There was a problem hiding this comment.
I don't agree that today's model_registry is that useful. It is useful only because we added everything, e.g., tp_gemm_backend, moe_comm_backend to model_registry which we shouldn't - those options actually depend on Parallelism. So if you take those options out from model_registry, model_registry becomes a pure model definition function. And if users want to use it without any changes, it can be used with FSDP only case. For other cases, it is not enough -- with TP, you will want async TP, with CP, you will want different CP backends, with EP, you will want different MoE backends.
I do agree that directly building Trainer.Config can solve the problem. The question is it may be too verbose and hard for users to build. But with agent, I think this is one approach. Any of the proposal won't eliminate this approach.
And every solution need the certain contexts/knowledges, even the plain Trainer.Config solution.
There was a problem hiding this comment.
Our config is flexible enough that users can use it however they want, e.g.
- [bottom-up] they can build all the way from bottom up, including the model itself inside
Trainer.Config - [transform] build a default than transform it
For things in config_registry.py, I don't think they are part of the core repo anyway, and we probably should put in torchtitan_recipes/.
For model_registry, it's an intermediate layer of the lego. The biggest value is that it fixed OSS available arch, e.g. what qwen3.5 27B looks like -- this is regardless of TP / CP / MoE backend. As an OSS framework which can load HF weights, we need a way to do so. But because we are doing [bottom-up] in model_registry, we are sending CP backend / TP backend / MoE backend / Attn backend to choose building blocks.
Regarding when [transform] could be useful
- when you need to make multiple changes for one feature, e.g. apply CP with load balancing would require dataloader change
- without transform, you'd have to
When I need customization I write a function for it, one that takes parameters and returns a config, which flavor-wise sounds likemodel_registrywith inflated fields.
There was a problem hiding this comment.
@tianyu-l this is the current proposal. It includes a table that answer what belong to model_registry. The ordering part may be over-designed if there are no more transformation in the future.
cc., @jinsooihm @pianpwk
[ghstack-poisoned]
| for _, traversed, _, _ in model.traverse(BaseAttention.Config): | ||
| # traverse returns the base config type. | ||
| attention = cast(BaseAttention.Config, traversed) | ||
| attention.inner_attention = retype_node(attention.inner_attention, kernel) |
There was a problem hiding this comment.
I remember you mentioning that for Muse Glimmer, we could do Ulysess for global causal layer and selected gather for sliding window layer. Would one need to write a new ModelTransform class for that, or would this class be extended to handle such cases?
There was a problem hiding this comment.
Check line 26 of this file. That's the TODO.
There was a problem hiding this comment.
I am wondering if transform should take a function of type Module.Config -> Bool that a model provides that can conditionally apply retype_node, for ex, by looking at the sliding_window_size field. Then one can apply two transforms sequentially. But I guess that can make run_after and conflicts_with logic more complicated if transform can be parametrized.
| Needing training settings for validation does not make an option a transform. | ||
| For example, the attention backend still belongs in `model_registry`. |
There was a problem hiding this comment.
didn't understand this sentence, why attention backend couldn't be a model transform here?
There was a problem hiding this comment.
Attention kernel selection is more related to algorithm and metadata selection. For example, you can only use Flex but not varlen for a certain attention. I agree that you can use transform for attention backend. But this is more design choice -- the base model definition is defined by the model_registry.
However, you can also argue that LoRA also changes the model. So I have to admit the line here is not clearly drew.
|
|
||
| # Validate features that span config sections once model_spec is set. | ||
| if self.model_spec is not None: | ||
| validate_context_parallel(self.model_spec.model, self.parallelism) |
There was a problem hiding this comment.
maybe validate_context_parallel should live here? similar to other _validate functions here.
There was a problem hiding this comment.
I personally would like to make trainer.py succinct by moving validation logic to other files, so this particular function matches my goal, compared with making more self._validate_xyz() functions
On the other hand, I also feel it's scattered too much if
- every component owns a
validate.pyfile - cross component validation ownership is not clear
So how about creating a dedicated validate.py file under some folder, say torchtitan/config/, which holds all the validation functions?
There was a problem hiding this comment.
creating a dedicated validate.py file under some folder, say torchtitan/config/, which holds all the validation functions?
I feel this is no difference from putting all validation logic here. We could hypothetically just have a huge validate funciton that contains all the validations in this file.
every component owns a validate.py file
I think this is a good idea, like what already did for CP validation.py. For cross component validation, maybe we can duplicate in both files?
There was a problem hiding this comment.
every component owns a validate.py file
I still prefer keeping distributed/context_parallel/validation.py. So I prefer each component owns a validation.py file. The rules are CP-specific while Trainer.Config is the first object that owns the required information. So it is owned by CP but called here. This clarifies the ownership and caller.
There was a problem hiding this comment.
so, "what if" CP and quantization has composability issues, even if temporary, who owns the validation?
There was a problem hiding this comment.
Depending on which component introduces the composability issue, that component should valid the case. This is not unique to validation -- the transform/convert/pass has the problem as well. If one transform cannot work with another one, we can directly add conflict_with,. If one transform must be after another one (ensure the dtype or something), then the order must be enforced. And the validation should follow, the component that introduces the issue validate the result.
There was a problem hiding this comment.
It sounds like this introducing a DAG among validate.py in the codebase (expecting import issues, lol), with arrow directions defined by "the component that introduces the issue validate the result" which won't always be 100% clear, although I don't have examples at hand. What could be worse is that they stay decentralized so even agents need to look at the entire codebase to construct the DAG.
edit: not DAG, could have cycles
There was a problem hiding this comment.
I think I confused myself. So we agreed that validation should be done in each component's __post_init__, but cross validation should be in the lowest ancestor component which can access all the required configs. So in this case validate_context_parallel should live in Trainer.Config.__post_init__. But since we don't want to put everything in trainer.py and want to have validation.py, it should be put in config/validation.py.
I'll do the change. But the local validation still live in its own __post_init__ If we feel that is too scattered, we can later centralize them.
| # Validate features that span config sections once model_spec is set. | ||
| if self.model_spec is not None: |
There was a problem hiding this comment.
No, it is not. model_spec is always valid when Trainer is already constructed but not Trainer.Config. We may construct Trainer.Config first without model_spec. It may be from a test code only but it is not the case. We can add a TODO to remove this and change the typing, but not in this PR.
|
|
||
| # Validate features that span config sections once model_spec is set. | ||
| if self.model_spec is not None: | ||
| validate_context_parallel(self.model_spec.model, self.parallelism) |
There was a problem hiding this comment.
I personally would like to make trainer.py succinct by moving validation logic to other files, so this particular function matches my goal, compared with making more self._validate_xyz() functions
On the other hand, I also feel it's scattered too much if
- every component owns a
validate.pyfile - cross component validation ownership is not clear
So how about creating a dedicated validate.py file under some folder, say torchtitan/config/, which holds all the validation functions?
| __all__ = ["ModelTransform", "retype_node"] | ||
|
|
||
|
|
||
| class ModelTransform(ABC): |
There was a problem hiding this comment.
question 1: Instead of transform model, it's transforming model config -- should we call it ModelConfigTransform? Also, I feel this is similar to graph "passes", they are just "config passes" -- should we align the term with graph concepts?
question 2: what if later we need trainer level transform, do we rename this and generalize this, or do we have another transform abstraction?
question 3: Shall we deprecate ModelConfigConverter https://github.com/pytorch/torchtitan/blob/main/torchtitan/protocols/model.py#L19 which almost does the same thing? Can we rename and reuse it instead of creating something separate but similar? The main difference seems that ModelConfigConverter is a configurable which requires build before usage, but ModelTransform itself is a dataclass and can apply transform directly which makes sense.
There was a problem hiding this comment.
what is the main motivation for us to move from ModelConfigConverter to ModelConfigTransform?
There was a problem hiding this comment.
ModelConfigTransformis clear. The current design only performs the config rewrite, sotransformis a close term. To me,passis a self-contained term that includes both analysis, rewrite, and validation. Since our validation is done in another place,Transformsemantics is more close from my perspective. Just my opinion.- I prefer to a base ConfigTransform + TranerConfigTransform
- Yes. That's the plan. As for why don't we just improve
ModelConfigConvert? Mostly just for BC, I don't want to disrupt the users. We can of course just improve the the existingModelConfigConvertbut this may make the transition harder.
| """Mixin for attention kernels that own their CP collectives.""" | ||
|
|
||
| @property | ||
| def cp_group(self) -> dist.ProcessGroup: |
There was a problem hiding this comment.
I feel this should be a spmd_types utils rather than CP kernel util.
Also in linear attention, InnerXYZAttention is reserved for "conv" + "kernel", as the replacement boundary for vllm inference. So CPKernel is conflicting with that in naming. Maybe we can call this CPInnerAttention since that's the replacement target?
Given these two reasons, I feel this abstraction is less necessary.
There was a problem hiding this comment.
Sure, if you prefer, we can move cp_group to spmd_types utils.
| return cp_group | ||
|
|
||
|
|
||
| class AllGatherCPFlexAttention(ContextParallelKernel, FlexAttention): |
There was a problem hiding this comment.
should mention "all-gather KV"? E.g. technically I could all-gather Q
| them. | ||
| """ | ||
|
|
||
| kernel: type[Module] |
There was a problem hiding this comment.
similar -- kernel is ambiguous
| __all__ = ["apply_transforms", "transform_model"] | ||
|
|
||
|
|
||
| def _ordered(transforms: list[ModelTransform]) -> list[ModelTransform]: |
There was a problem hiding this comment.
There was a problem hiding this comment.
Yes, same as the ModelConverter argument, which we will just have one eventually.
[ghstack-poisoned]
| ) | ||
|
|
||
|
|
||
| def transform_model_config( |
There was a problem hiding this comment.
should we do
| def transform_model_config( | |
| def transform_model_config_( |
| return mesh.size(names.index(axis_name)) | ||
|
|
||
|
|
||
| def require_spmd_mesh_axis_group( |
There was a problem hiding this comment.
why not
| def require_spmd_mesh_axis_group( | |
| def get_spmd_mesh_axis_group( |
There was a problem hiding this comment.
| prepare_context_parallel_input, | ||
| ) | ||
|
|
||
| batch: dict[str, Any] = dict(input_dict) |
There was a problem hiding this comment.
separate topic: maybe should rename this to dp_local_microbatch
There was a problem hiding this comment.
Not sure about this, microbatch means either gradient accumulation or PP are used. But with a smaller scale, users may use neither.
| ) -> dict[str, Any]: | ||
| from torchtitan.models.common.cp_attention import CPInnerAttention | ||
|
|
||
| inner_attention = self.config.first_full_attention_backend |
There was a problem hiding this comment.
Is it true that today, regardless of
- if FlexAttention is used for both full and sliding window
- there could be linear attn layers
We are all using the same load balancing algo? I wonder if we should introduce cost function for each Inner(Linear)Attn instance so that our (DP / CP) load balancer can make decision on top of that.
There was a problem hiding this comment.
does the load balancer also need to know number of full attn/linear attn layers to calculate the load?
There was a problem hiding this comment.
For Muse Glimmer that has full and sliding window, you can choose which mask to balance make the balance decision #3972. It turns out adding the cost of sliding window does not change the PTRR load balancing decision because it only considers the relative order of the costs. So we can just use the mask for the full layer to load balance.
But for more complicated load balancing algorithms, it could be helpful to know the cost for each layer and the ratio between full and linear attention.
There was a problem hiding this comment.
@jinsooihm has a nice proof (iirc, lol) that shows at least for full and sliding window, PTRR will get the best result by just looking into the full attention.
But I do agree this needs some design and how the interface should be. I haven't had time to actually think about this. It is also related to #4500 (comment)
cc., @drisspg
There was a problem hiding this comment.
Another use case for the cost function could come from actual profiling rather than the estimates we may derive from the attention masks, linear/quadratic attention, etc.
| """ | ||
|
|
||
|
|
||
| def retype_node(existing: Module.Config, replacement: type[Module]) -> Module.Config: |
There was a problem hiding this comment.
retype doesn't sound a word and there is no official "node" concept, would you please try another name. How about cast_type or cast_config_type?
| parallel_dims.get_mesh("cp"), | ||
| parallelism.context_parallel_load_balancer, | ||
| parallelism.context_parallel_ptrr_mask_key, | ||
| batch = self._cp_shard_inputs( |
There was a problem hiding this comment.
can we use sth like self.inner_attention.cp_shard_inputs, where each inner attention should have it's own shard function?
There was a problem hiding this comment.
I think this needs more careful design. Currently the input is sharded once and used consistently across all layers. Who'd be responsible for generating such a plan? I personally think we should have a LoadBalancer (which works for DP as well) concept which takes the whole model config, and can be used to make CP shard decision, RL batching decision, and potentially pretraining DP sharding decision.
Add config transforms and use one to install CP attention. Validate CP against the transformed model config. ghstack-source-id: 9881a43 Pull-Request: pytorch#4322
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #4459 * #4450 * #4533 * __->__ #4449 * #4322 Switch to use `spmd_types.redistribute` instead of using `flex_cp_allgather`. The backward of the gather is a reduce-scatter, and the API requires an explicit dtype for it under reduced precision. `AllGatherCPFlexAttention.Config.reduce_dtype` exposes that choice. It defaults to None, which keeps the reduction in the input dtype and so matches `flex_cp_allgather`. Set it to float32 to trade two casts for accuracy, which matters as the CP degree grows and the reduce-scatter sums more contributions. **Numerics Verification** Loss and grad_norm are bitwise identical before and after, with the default `reduce_dtype`. `scripts/loss_compare.py` over `llama3_debugmodel_fsdp2_cp2` (FSDP 2 + CP 2, 4 H100s, spmd_types, bf16 params), shared seed checkpoint, `--debug.seed=42 --debug.deterministic`, 10 steps, values read from the TensorBoard scalars: metric max |before - after| loss 0.0 grad_norm 0.0 Step 1 loss is 8.048094749450684 on both sides and step 10 is 4.038208961486816. `--assert-equal` passed for both metrics.
## Summary - restore CIFlow tag routing so stacked PRs are tested independently of their base branch - automatically apply `ciflow/fake-pg` only to ready, non-draft PRs with relevant code or test changes - use each `ciflow/fake-pg/*` tag to run both broad 1-GPU Fake PG coverage and the 8-GPU `real_pg_required` subset - add `ciflow/real-pg` as the opt-in trigger for the full 8-GPU Real PG suite - document the integration-test cadence and reusable `execution_mode` input ## Why **The historical `ciflow/8gpu` label and moving tag allowed integration CI to run on stacked PRs whose base was not `main`**. After that label was repurposed as an opt-in full-suite trigger, stacked PRs could miss required integration coverage. PR #4322 exposed this gap: its PR checks passed, but five model configurations failed immediately after landing on `main`. This change separates the two responsibilities: - `ciflow/fake-pg` is automatically managed and triggers both Fake PG coverage and the `real_pg_required` Real PG subset for normal and stacked PRs. - `ciflow/real-pg` is manually applied when the full 8-GPU suite is desired before landing. The full Real PG suite continues to run after pushes to `main`, on schedule, and through manual or Real PG reusable workflow invocations. Failing post-merge run: https://github.com/pytorch/torchtitan/actions/runs/34625822895/job/103350597237 ## Testing - changed-file pre-commit hooks pass - all modified workflow and Probot configuration files parse as valid YAML - verified the event routing conditions for Fake PG tags (Fake PG plus the Real PG required subset), Real PG tags, main pushes, schedules, manual dispatches, and reusable workflow calls
Stack from ghstack (oldest at bottom):
Move the K/V all-gather from local-map redistribution in
Module.forward()into AllGatherCPFlexAttention. Add kernel selection and validation, then update CP recipes and tests.All CP implementation will follow this approach.