Skip to content

refactor max_context_length - #4328

Merged
tianyu-l merged 24 commits into
pytorch:mainfrom
francesco-bertolotti:f14-nope-refactor
Sep 2, 2026
Merged

tianyu-l merged 24 commits into
pytorch:mainfrom
francesco-bertolotti:f14-nope-refactor

Conversation

@francesco-bertolotti

@francesco-bertolotti francesco-bertolotti commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

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.

  • ModelSpec gains a required max_context_length. model_registry(flavor, seq_len=...) sizes the RoPE caches up front; each flavor entry carries its own maximum, and asking for more raises ValueError.
  • Decoder.Config.update_from_config no longer resizes RoPE caches or validates the training length, and Decoder.Config.max_context_length is gone.
  • seq_len defaults to None in every config registry, meaning "the flavor's max context length".
  • Callers updated to match: RL examples, graph_trainer, torchft, and the transformers modeling backend.
  • Every CI entry point pins the length it used before.

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

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 26, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

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.

let's not hack this file -- fyi we are moving away from CLI configuring #4114

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

cc @fegin on feedback

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.

@francesco-bertolotti

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,

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

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

Comment on lines +276 to +281
# 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.

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/config/manager.py Outdated

from torchtitan.tools.logging import logger

# Spellings tyro accepts for TrainingConfig.max_context_length. Kept in argv

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.

let's remove hacks in this file

Comment on lines 282 to 296

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.

Comment on lines 372 to 379
llama3_configs = {
"debugmodel": _debugmodel,
"1B": _1b,
"3B": _3b,
"8B": _8b,
"70B": _70b,
"405B": _405b,
}

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.

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

@francesco-bertolotti francesco-bertolotti Aug 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_len value 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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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

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.

we should remove model_spec.model.max_context_length, right?

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

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

Suggested change
engine_kwargs["max_model_len"] = model_spec.model.max_context_length
engine_kwargs["max_model_len"] = model_spec.max_context_length

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator Author

max_context_length is now decided once, at model_registry() time, and carried on ModelSpec.max_context_length.

  • Each *_configs entry becomes (builder, max_context_length): the flavor's intrinsic context limit. Flavor builders take a required seq_len instead of hardcoding the RoPE length.
  • model_registry(flavor, seq_len=None) uses the flavor cap when seq_len is omitted, and raises when the requested seq_len exceeds it.
  • Removed the runtime RoPE resize + validation from Decoder.Config.update_from_config, the Decoder.Config.max_context_length property, and the duplicated check in the RL PolicyTrainer.
  • vLLM's max_model_len now reads model_spec.max_context_length instead of walking into the model config's RoPE.



def deepseek_v3_671b() -> Trainer.Config:
def deepseek_v3_671b(seq_len: int = 4096) -> Trainer.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.

Given that we already have default in model_registry, let's make the default to be None for config_registry.py files.

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator Author

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

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.

how is this determined

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.

according to https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/transformers_modeling_backend/model.py#L462

Let's make seq_len: int required for model_registry for this particular modeling backend, and remove _MAX_CONTEXT_LEN.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seq_len is now a required keyword arg on that model_registry and _MAX_CONTEXT_LEN is gone.

@tianyu-l tianyu-l linked an issue Sep 2, 2026 that may be closed by this pull request
@tianyu-l
tianyu-l merged commit eaff38a into pytorch:main Sep 2, 2026
22 of 24 checks passed
jinsooihm added a commit that referenced this pull request Sep 3, 2026
Fix CI failure caused from #4387 caused by wrong rebasing
and lint and CPU unit tests failures probably from #4328
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 6, 2026
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.
tianyu-l pushed a commit that referenced this pull request Sep 7, 2026
## 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl 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.

NoPE implementation and max_seq_len

4 participants