Repository navigation
refactor max_context_length - #4328
Conversation
|
|
There was a problem hiding this comment.
let's not hack this file -- fyi we are moving away from CLI configuring #4114
There was a problem hiding this comment.
Thank you for letting me know. I think it is a good choice. We are not using the CLI either.
The way I like to use titan is directly with a trainer config:
Trainer.Config(...).train()It ends being a pretty large config file but I can easily swap, modify, and version any change.
There was a problem hiding this comment.
We are discussing how to do the transformation (e.g., enabling different CP backend, enabling different TP backend). Would like to hear users' opinion as well: #4322 (comment)
| def model_registry( | ||
| flavor: str, | ||
| *, | ||
| seq_len: int | None = None, |
There was a problem hiding this comment.
I think the change in this PR makes it friendly for pretraining / midtraining, where it's legit to modify default max context length. This is what I liked about this PR's direction.
However, it smells dangerous for SFT when users could accidentally specify an input longer than checkpoint's max context length.
Is your point that SFT users should call model_registry without specifying this field? It gives no guard, basically.
There was a problem hiding this comment.
However, it smells dangerous for SFT when users could accidentally specify an input longer than checkpoint's max context length.
You mean that users could do SFT with a context length larger then the one seen in pretrain? It would be odd but I do not see a reason to prevent it.
Is your point that SFT users should call model_registry without specifying this field? It gives no guard, basically.
Actually, I think users should be entirely responsible of setting the seq_len. I think a default could be convenient. But if you think that this could be error prone, I can also remove it.
There was a problem hiding this comment.
You mean that users could do SFT with a context length larger then the one seen in pretrain? It would be odd but I do not see a reason to prevent it.
I'm always a bit worried that users would, by accident, specify over-long inputs to a trained model with intrinsic limitation on context length. Say model X has 10k context length capability, but user specifies 1M context input for SFT because their data is long.
Another way to put it, when model X is released with claimed max context length, how should a training framework like torchtitan respect this field? This PR is doing "set it as default in model_registry and let user freely override", which I feel may also be fine, because that's the more general thing to do.
I think the tension is really between
- torchtitan for pretraining (+post training) workflow
- torchtitan for post-training only workflow
also cc @fegin on the new model_registry arg
| # TODO: model_spec.model.max_context_length is the RoPE cache size, which | ||
| # core config_registry functions now build from their seq_len parameter | ||
| # rather than from the architecture's full context. Once a model registry | ||
| # in torchtitan/models is used here, this reads the training sequence | ||
| # length, not the model's generation capacity. Give ModelSpec a dedicated | ||
| # capacity field and read that instead. |
There was a problem hiding this comment.
Does it make sense if we still make model.max_context_length a cached property, by traversing through all RoPE.max_context_length? I'm considering deprecate ModelSpec and put all fields in Model / Decoder / their configs.
Or is there model that has absolutely no RoPE at all? In that case, what'd be the context length limit?
There was a problem hiding this comment.
In my opinion, the max_context_length is something that the users need to provide. Trying to infer what that could be is going to be error prone and architecture dependent.
|
|
||
| from torchtitan.tools.logging import logger | ||
|
|
||
| # Spellings tyro accepts for TrainingConfig.max_context_length. Kept in argv |
There was a problem hiding this comment.
let's remove hacks in this file
There was a problem hiding this comment.
| llama3_configs = { | ||
| "debugmodel": _debugmodel, | ||
| "1B": _1b, | ||
| "3B": _3b, | ||
| "8B": _8b, | ||
| "70B": _70b, | ||
| "405B": _405b, | ||
| } |
There was a problem hiding this comment.
let's provide a per-flavor default max_context_length in this dictionary, and when calling model_registry if user given seq_len is longer than it, we raise
There was a problem hiding this comment.
I would like to confirm if you mean something like this:
llama3_configs = {
"debugmodel": (_debugmodel, 2048),
"1B": (_1b, 131072),
"3B": (_3b, 131072),
"8B": (_8b, 131072),
"70B": (_70b, 131072),
"405B": (_405b, 131072),
}
def model_registry(
flavor: str,
*,
seq_len: int = 131072,
attn_backend: str = "flex",
tp_gemm_backend: TpGemmBackend = "default",
converters: list[ModelConfigConverter.Config] | None = None,
) -> ModelSpec:
# seq_len is forwarded only when the caller sets it, so each flavor
# builder keeps its architecture's full context as the default.
get_config, max_seq_len = llama3_configs[flavor]
if seq_len > max_seq_len:
logger.warning(
f"Requested seq_len={seq_len} exceeds max context length for {flavor}."
)
max_seq_len = seq_len
config = get_config(
attn_backend=attn_backend,
tp_gemm_backend=tp_gemm_backend,
seq_len=max_seq_len
)That would be, when using model_registry:
- we choose a "max"
seq_lenvalue for rope_cache.- if users provide a smaller value we keep the default one. Not strictly a problem, the rope_cache will be bigger to accommodate any request. But why allocating more then neccessary?
- if users provide a bigger value we accomodate the user.
Why not something like this:
llama3_configs = {
"debugmodel": _debugmodel,
"1B": _1b,
"3B": _3b,
"8B": _8b,
"70B": _70b,
"405B": _405b,
}
def model_registry(
flavor: str,
*,
seq_len: int = 8192,
attn_backend: str = "flex",
tp_gemm_backend: TpGemmBackend = "default",
converters: list[ModelConfigConverter.Config] | None = None,
) -> ModelSpec:
config = llama3_configs[flavor](
attn_backend=attn_backend,
tp_gemm_backend=tp_gemm_backend,
**({} if seq_len is None else {"seq_len": seq_len})
)We would do exactly what the user say. If he does not say anything, we use our per-flavor default provided in the keyword argument of the respective _1b, ..., _405b
There was a problem hiding this comment.
Third option:
llama3_configs = {
"debugmodel": (_debugmodel, 2048),
"1B": (_1b, 131072),
"3B": (_3b, 131072),
"8B": (_8b, 131072),
"70B": (_70b, 131072),
"405B": (_405b, 131072),
}
def model_registry(
flavor: str,
*,
seq_len: int | None,
attn_backend: str = "flex",
tp_gemm_backend: TpGemmBackend = "default",
converters: list[ModelConfigConverter.Config] | None = None,
) -> ModelSpec:
get_config, max_seq_len = llama3_configs[flavor]
config = get_config(
attn_backend=attn_backend,
tp_gemm_backend=tp_gemm_backend,
seq_len = seq_len or max_seq_len
)This would also allow to pass seq_len in the returned ModelSpec pretty easily. I think you meant something like this
There was a problem hiding this comment.
I meant third, yes. But I want the seq_len > max_seq_len check -- in particular, I want it to raise, not warning. My rationale is that
- when you use this particular model, it's capability is already intrinsically limited.
- but when you are doing pretraining of your own model, you don't need to have this raise / check.
| # in torchtitan/models is used here, this reads the training sequence | ||
| # length, not the model's generation capacity. Give ModelSpec a dedicated | ||
| # capacity field and read that instead. | ||
| engine_kwargs["max_model_len"] = model_spec.model.max_context_length |
There was a problem hiding this comment.
we should remove model_spec.model.max_context_length, right?
There was a problem hiding this comment.
I saw that vllm also has "max_position_embeddings" required at https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/rl/models/vllm_registry.py#L150
I think that should be kept -- it seems to be getting max context length from our rope field to set cache, which sounds right, except for that we will see models in the future without rope so probably needs to be optional
===============================================
Regarding this max_model_len, here are something meaningful after some codebase search
- general config https://github.com/vllm-project/vllm/blob/99013d77d332a2d21d7214b57fa495f2bad2b448/vllm/config/scheduler.py#L29
- For KV cache pre-allocation https://github.com/vllm-project/vllm/blob/99013d77d332a2d21d7214b57fa495f2bad2b448/docs/features/context_extension.md?plain=1#L69
- For maximum generation length https://github.com/vllm-project/vllm/blob/99013d77d332a2d21d7214b57fa495f2bad2b448/vllm/v1/engine/__init__.py#L54
It seems we should keep it the same as what our user sets for trainer (if you couldn't train longer than this, you shouldn't generate longer).
================================================
@francesco-bertolotti could you add a new field ModelSpec.max_context_length together with (name, flavor), which we set during model_registry() call and modify the code here to be
| engine_kwargs["max_model_len"] = model_spec.model.max_context_length | |
| engine_kwargs["max_model_len"] = model_spec.max_context_length |
9e4b63a to
90610c2
Compare
|
|
|
|
||
|
|
||
| def deepseek_v3_671b() -> Trainer.Config: | ||
| def deepseek_v3_671b(seq_len: int = 4096) -> Trainer.Config: |
There was a problem hiding this comment.
Given that we already have default in model_registry, let's make the default to be None for config_registry.py files.
|
seq_len now defaults to None in every config registry. If it is not specified, the model registry resolves it to the flavor's max context length, which is much larger than what these configs used before. That would have changed what CI runs, so I pinned seq_len at every CI entry point to the value it resolved to before this branch |
|
|
||
|
|
||
| def model_registry(flavor: str) -> ModelSpec: | ||
| _MAX_CONTEXT_LEN = 131072 |
There was a problem hiding this comment.
Let's make seq_len: int required for model_registry for this particular modeling backend, and remove _MAX_CONTEXT_LEN.
There was a problem hiding this comment.
seq_len is now a required keyword arg on that model_registry and _MAX_CONTEXT_LEN is gone.
Surveyed, not merged -- two 80B captures are mid-flight and folding in 64 commits would make any new failure ambiguous. This records the analysis so the merge is cheap later. Diverged at 6ee6d5d (2026-08-30), upstream tip 966befc. ZERO upstream commits touch experiments/ezpz, so there are no conflicts in our own code. The risk is entirely in core files we import from. Of those, components/loss.py matters most: we import BaseLoss, CrossEntropyLoss, ChunkedLossWrapper and IGNORE_INDEX, all four still present, with one method renamed (typecheck_forward -> spmd_typecheck). zloss.py overrides only __init__ and __call__, so it does not inherit that rename -- checked rather than assumed, since a preserved name with a changed contract is the dangerous case, not a deleted one. Corrects my earlier risk ranking. I called pytorch#4328 (refactor max_context_length) the highest risk; that was wrong. max_context_length is UNCHANGED upstream -- same field, same default, plus a validation guard. The PR changes seq_len in model specs and registries, not the --training.max-context-length flag we pass. The single seam is agpt/config_registry.py:291, where our own agpt(seq_len=...) assigns cfg.training.max_context_length. The real risks, ordered: pytorch#4398 (valid-token counts move into collation -- that is the gradient-accumulation path), then the checkpoint cluster (pytorch#4187/pytorch#4188/pytorch#4197/pytorch#4270/pytorch#4474, which we subclass and where pinned clones have already broken on optim-statedict changes), then pytorch#4382 (Adam first-step state). Includes a merge order: smoke at 2N, then a resume from a real checkpoint, a seeded loss/grad_norm comparison, and config_registry.py:291 by inspection.
## Summary Now that #4328 landed we support NoPE by simply having `GQAttention.rope=None` # Changes 1. In `GQAttention`: `rope: RoPE.Config` -> `rope: RoPE.Config | None`. `rope=None` is NoPE. 2. Same change in `make_gqa_config` 3. `use_rope: bool` field in muse glimmer is not needed anymore. 4. Added checks for rope being None
Make max_context_length an explicit ModelSpec field
What
The model's context length is now decided when the spec is built, instead of being inferred from layer 0's RoPE config and retro-fitted onto RoPE caches later.
ModelSpecgains a requiredmax_context_length.model_registry(flavor, seq_len=...)sizes the RoPE caches up front; each flavor entry carries its own maximum, and asking for more raisesValueError.Decoder.Config.update_from_configno longer resizes RoPE caches or validates the training length, andDecoder.Config.max_context_lengthis gone.seq_lendefaults toNonein every config registry, meaning "the flavor's max context length".Why
PR to address #4289
The context length is a property of the spec you build and is known before the trainer starts, so it should be stated there. Deriving it from one attention layer's RoPE config and mutating caches during
update_from_configmade it implicit, forced inference-only callers (the RL generator) to opt out of the sync, and left two places that could disagree about how long a sequence the model supports.