Skip to content

[RL] Preserve per-group KV cache across policy updates - #4761

Merged
wwwjn merged 1 commit into
pytorch:mainfrom
wwwjn:per-group-kv-cache-salt
Oct 1, 2026
Merged

wwwjn merged 1 commit into
pytorch:mainfrom
wwwjn:per-group-kv-cache-salt

Conversation

@wwwjn

@wwwjn wwwjn commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Why

A policy update changes the model weights but does not automatically invalidate vLLM's cached KV. Letting a newly started rollout hit KV created by an older policy would give it stale prefix state. Clearing the entire cache prevents that reuse, but it also preempts every active request and makes long-running, multi-turn rollouts prefill their accumulated context again. This change supports two explicit KV-cache lifecycle modes.

Mode 1: preserve version-salted KV (default)

With generator.reset_kv_cache_on_weight_sync=false:

  1. When a generator first admits a rollout (a routing session), rank 0 pins the rollout to the generator's installed policy version. Every later turn of that rollout on the same generator reuses the pin, and the generator passes it to vLLM as cache_salt.
  2. A weight pull runs between engine.step() bursts. No request is admitted or advanced while the new weights are being installed, but existing requests and their KV blocks remain in vLLM.
  3. After the pull, in-flight rollouts resume from their existing KV instead of being preempted and re-prefilled, and their later turns hit their own history under the pinned salt.
  4. Rollouts first admitted after the pull are pinned to the new version. They cannot hit old-salt blocks, so their prefixes are computed with the new weights.
  5. Old-salt blocks remain reusable by their original rollouts until vLLM evicts them normally.

Each completion reports the pinned version as min_policy_version, since the completion may depend on KV cached under that version. policy_age and the max_offpolicy_steps check therefore account for the reused KV.

This mode avoids reset-and-reprefill work and preserves cache locality across policy updates. Its tradeoff is that the salt is only a prefix-hash namespace; it does not guarantee that every KV block used by an in-flight rollout came from one weight version. A rollout can retain prefix KV produced by its starting policy and append new KV after newer weights have been installed. Because the salt is the version number, rollouts pinned at the same version on a generator share one namespace: they reuse common prefixes such as a system prompt with tool definitions, and after a pull that namespace can also hold KV computed under the newer weights.

Mode 2: reset and re-prefill

With generator.reset_kv_cache_on_weight_sync=true:

  1. The generator installs the new weights.
  2. It clears the prefix cache and the pins, and preempts running requests.
  3. vLLM reschedules those requests and recomputes their accumulated context with the new weights before decode continues.

Config change. reset_kv_cache_on_weight_sync replaces main's reset_prefix_cache_on_weight_sync and reset_running_requests_on_weight_sync, and the default flips from reset to preserve. Configs that set either old field must switch to the new one. Resetting the prefix cache while keeping running requests' KV is no longer an option: the version salt already gives new requests fresh KV without a reset, so a reset only matters as a strict recompute, which must include running requests.

This mode provides strict recomputation under the latest installed policy and remains useful for exact trainer/generator comparisons (batch_invariant requires it). The additional prefill compute may also help overlap FSDP parameter all-gathers. The cost is extra prefill work, queueing, and latency, especially for long-running multi-turn rollouts.

The default mode follows Prime-RL's behavior: a rollout keeps its start policy version as the cache salt, and the prefix cache is not cleared on weight updates. TorchTitan obtains these semantics without calling vLLM's asynchronous pause_generation API because weight pulls are serialized between engine.step() bursts.

Where the salt lives

The salt only matters inside one engine's KV pool, so each generator owns its pins: rank 0 keeps group id -> routing session id -> pinned version and fills it at admission. The router stays stateless.

Placement belongs to the routing strategy. Later turns only hit their history if they return to the same generator, which StickySessionRoutingStrategy guarantees (the alphabet_sort recipes use it; the router default stays LeastLoadedRoutingStrategy, as on main). Under any strategy the salt is still correct: a turn that lands elsewhere pins that generator's version and misses the cache.

Request Salt Why
1st turn of a rollout The generator's installed version Pins the rollout; it cannot hit KV from older weights.
Later turn on the rollout's generator The rollout's pin Each turn extends the previous one, so the conversation history stays reusable across policy updates.
(Corner case) Later turn rerouted to another generator That generator's installed version The history KV stays on the old generator; the destination has no pin for the rollout.

Why key by rollout, not by group. Routing places rollouts, not groups: StickySessionRoutingStrategy keeps a rollout's turns on one generator by routing_session_id and spreads new rollouts by load, so siblings of a group may land on different generators and never share KV there anyway. Keying by rollout matches the routing unit and keeps staleness tight: a sibling first admitted after a pull pins the new version instead of inheriting its group's older one. The cost is that such a late sibling re-prefills the group prompt, which is short next to multi-turn history.

When pins are dropped. A generator cannot tell a finished rollout from one between turns (env steps, tool calls), so time- or idle-based pruning would drop a long rollout's pin and force a re-prefill. Only the controller knows when a group has no more calls: each GenerateFn call carries its group_id, and after a group finishes the controller calls the new release_groups router endpoint, which fans out to every generator. Validation group ids are reused every validation, so they are released too.

Why a policy version rather than a rollout id as the salt. Only a weight change makes cached KV stale, so the namespace only needs to change with the version. A per-rollout salt would give every rollout a private namespace and lose prefix reuse across rollouts, such as a shared system prompt or tool definitions. A version salt keeps that reuse while walling off KV from older policies.

image

DAPO Math performance measurement

Compared this PR's default (reset_kv_cache_on_weight_sync=false), this PR with the reset flag (true), and main (46ec3f232, which resets the prefix cache and running requests on every weight sync).

Setup

  • rl_dapo_qwen3_4b_math_8k, Qwen3-4B-Base BF16, single-turn
  • 4x H100: TP2 trainer plus two TP1 generators, LeastLoadedRoutingStrategy
  • 10 optimizer steps; 8 prompt groups/step; 16 completions/prompt
  • 2,048-token prompt and 8,192-token response limits
  • Same checkpoint, config, seeds, and hardware; one run per mode

vLLM metrics come from the engine stat logger, summed over both generators, over steps 2-10 (from the step 1 log to the step 10 log, excluding validation). Request E2E is vLLM last_token_ts - queued_ts.

Metric This PR, preserve (default) This PR, reset main
Preempted requests 0 687 858
Queue latency mean 0.86 ms 52.4 ms 61.6 ms
Time to first token mean 34.8 ms 93.6 ms 103.6 ms
Prefill time mean 32.5 ms 37.4 ms 37.2 ms
Request E2E mean 18,916 ms 20,015 ms 20,179 ms
Inter-token latency mean 19.18 ms 19.62 ms 20.43 ms
Prefix-cache hit rate 85.44% 85.27% 85.57%
Generation throughput 5,339 tok/s 5,146 tok/s 5,722 tok/s
Wall time, steps 2-10 388.5 s 391.0 s 367.2 s

Preserving KV removes every preemption at weight sync, which cuts queue latency by about 98% and time to first token by about 65%. The reset mode matches main. End-to-end metrics are within run-to-run noise: reset and main behave the same yet differ by 10% in throughput, so these runs support no throughput claim. DAPO is single-turn, so the gain is limited to the avoided re-prefill of in-flight requests; multi-turn rollouts, which lose their whole conversation history on a reset, are where preserving KV should matter most.

Test plan

  • Generator engine loop: a rollout's later turn keeps its pinned salt across a weight sync while a new rollout of the same group pins the new version; release_groups drops a group's pins (and ignores unknown groups), so a reused group id pins the current version.
  • Generator: admission passes the pinned version as cache_salt; min_policy_version is the pinned version; the reset flag controls the cache reset and clears pins only when set; batch_invariant requires the reset.
  • Verifiers: the shared generation server forwards each request's group id; requests without a group id get 400.
  • pytest tests/rl/unit_tests/cpu/: 458 passed, 3 skipped, 0 failed.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 17, 2026
@wwwjn
wwwjn force-pushed the per-group-kv-cache-salt branch from 4fe7c8e to 0eae1cc Compare September 21, 2026 18:03
@wwwjn
wwwjn marked this pull request as ready for review September 21, 2026 18:25
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 21, 2026
@wwwjn
wwwjn force-pushed the per-group-kv-cache-salt branch 2 times, most recently from 0017609 to c2145f4 Compare September 21, 2026 18:28
Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/controller.py Resolved
Comment thread torchtitan/rl/components/work_buffer.py Resolved
Comment thread torchtitan/rl/controller.py Resolved
Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/controller.py Resolved
Comment thread torchtitan/rl/controller.py Resolved
await push_task
with sl.log_trace_span("generator_pull_model_state_dict"):
start = time.perf_counter()
await self._generator_router.pull_model_state_dict.call_one(version)

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.

what if some generator finishes weight sync, but other haven't? You would use a version as salt which you haven't seen the weight from.

Comment thread torchtitan/rl/controller.py Outdated
await group_buffer.add_work(
RolloutGroupWork(
group_id=group_index,
policy_version_at_start=weight_sync.generator_policy_version,

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'm confused. Taking a step back, why do we need generator policy version to be the salt?

Is the goal of the salt is to let ALL (multi-turn) requests from a rollout group to share the same salt? Then why don't we use rollout group id???

@wwwjn wwwjn Sep 22, 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 salt is a "namespace" of the kv cache. When a kv cache query comes in, the query will first check the "namespace" then the corresponding position. We only need to update the "namespace" when the weights are being updated.

There are 2 choice of using"group_id" as the salt, or using "policy version".

Option 1: Using group_id:

  • Pros: Code is simple
  • Cons: a common system prompt is not shared across group, only the kv cache of the group prompt (if the same vllm instance has previously seen a rollout from the same group), and previous turn's kv cache of the same roullout is shared.

Option 2: Using policy_version:

  • Pros: system prompt's kv cache can be share. To be more accurate, this is a minor gain, because system prompt is several thousands tokens, while the later turns can be
  • Cons: Need to handle a corner case: In sticky routing, when a previous vllm instance is not avaliable (eg, the failed generator have v8 policy), and the rollout is being re-route to another generator which might have older policy (eg, the new generator has v7).

I decided to go with Option 2 because of the system prompt sharing. Our sticky routing is per-rollout stick to a vllm instance, not putting the siblings within a group on the same vllm instance. So the chance of sharing group prompt is less, so I think we can do our best to share system prompt. To be more fair, we should do more experiments to decide by checking the prefix caching rate.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude
review this PR, and review my review

@claude

claude Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

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


Review of PR #4761 + review of @tianyu-l's review

  • Read the PR diff against origin/main
  • Review the code changes for correctness and design
  • Review @tianyu-l's review comments
  • Post consolidated feedback

I traced the full call chain: _data_input_loop -> RolloutGroupWork.policy_version_at_start -> _rollout_loop -> _make_generate_fn(cache_salt=...) -> InterGeneratorRouter.generate -> VLLMGenerator.generate -> GenerationRequest.cache_salt -> _admit_requests -> render_cmpl, plus WeightSyncManager._generator_policy_version publication.


Overall

The mechanism is sound and the implementation is clean: version is published only after all generators finish their pull, the salt is threaded consistently, the old three-flag matrix (reset_prefix_cache_on_weight_sync / reset_running_requests_on_weight_sync + the hot_swap guard) collapses into a single well-documented reset_kv_cache_on_weight_sync=false default, and the batch-invariant recipes correctly opt back into reset. Tests cover the salt threading, the reset flag, and version publication. The known tradeoff (a group's KV can span weight versions) is honestly documented and is tracked via Completion.min/max_policy_version, so it's a deliberate, observable choice rather than a silent one.

Main things to resolve before merge are design/layering, not correctness: the vLLM-term leak up the call chain, and passing the whole WeightSyncManager into the data-input loop.


Review of @tianyu-l's review comments

controller.py:937 — "why policy version as salt, not rollout group id?" — This is the key question and I think the PR's choice is correct, but the reason isn't documented. Group-id salt would isolate every group into its own prefix namespace, which kills cross-group prefix reuse — the shared system-prompt / few-shot prefix that many groups admitted under the same policy share. Version salt is deliberately coarser than group-id: it lets same-version groups reuse each other's prefixes (that's the +2.06pp hit-rate / +3.4% throughput in the table) while still walling off old-policy blocks. Group-id would give the "same salt across turns" property but lose that win, and it would still have the same mid-group weight-mixing caveat. So version > group-id here. Suggest adding a comment stating exactly this, since it's the crux of the design.

generator.py:1113 + controller.py (_make_generate_fn) — "is cache_salt a vLLM term? be careful where the rename happens." — Agree, and this is the most actionable point. cache_salt is vLLM-specific (it's a field on vLLM's request input). Right now the vLLM name propagates all the way up into Controller._make_generate_fn's signature and docstring ("pinning prefix KV to cache_salt"). The clean boundary is: keep a neutral name upstream (e.g. policy_version_salt or kv_namespace) through the controller/router/GenerationRequest, and only translate to vLLM's cache_salt at the single render_cmpl dict in _admit_requests. That confines the vLLM vocabulary to the vLLM adapter.

controller.py:968 — "why is cache_salt in generate_fn instead of passed to run_group_rollouts?" — Agree the current shape is a little odd, and it interacts with the previous point. The salt is a per-group property; baking it into a per-group closure also means _make_generate_fn is now rebuilt once per group inside _rollout_loop (it used to be built once). That's cheap, but it does couple a swappable transport abstraction to a per-group value. Passing the group's pinned version through run_group_rollouts (as a neutral field, not the vLLM name) keeps GenerateFn transport-agnostic and reusable. Note the tension with the next point: whatever you thread through the protocol should be the neutral name, not cache_salt.

controller.py:793 & 832 — "does weight sync need initial_policy_version?" / "don't send the manager to the data-input loop." — Strongly agree with 832. _data_input_loop only reads weight_sync.generator_policy_version once per admitted group; handing it the entire WeightSyncManager over-couples them. But you can't pass a snapshot int at loop start either — the value must be read live at each admission. So the right fix is a thin live accessor, e.g. get_policy_version: Callable[[], int] (or a small published-version holder), not the manager. On 793: initial_policy_version is genuinely needed so the very first wave (admitted before any pull completes) has a defined salt equal to start_step; it just doesn't need to arrive by way of the whole manager.

weight_sync.py:127 — "what if one generator finishes sync but others haven't? You'd salt with a version whose weights you haven't seen." — Good instinct, but the current code is safe: _generator_policy_version = version runs only after await self._generator_router.pull_model_state_dict.call_one(version), and that router endpoint fans out with asyncio.gather over all generators and awaits every one (both hot-swap and strict-drain paths). So the version is published globally only once every generator holds it, and slot release happens after publication. The per-generator early-release case tianyu-l is worried about is exactly what the TODO(perf) at lines 130-133 calls out as not yet done — when that lands, the invariant becomes per-generator and this concern becomes real. Worth a one-line note in that TODO that per-generator release must also make salt publication per-generator.

work_buffer.py:42 — "confirm: in multi-turn all turns share the same salt." — Confirmed. routing_session_id is per-turn-excluding-turn (per rollout), but cache_salt is pinned once at group admission (policy_version_at_start) and reused for every turn of every rollout in the group. That's intended (it's what lets turn 2 reuse turn 1's prefix). The flip side is the acknowledged caveat: if a weight sync lands mid-group, turn 2's newly-computed KV is written under the old salt, so a group's KV can mix weight versions. Fine as documented.

controller.py:416 (approve) / generator.py:1187 ("inline the one-use function") — Agree the hot_swap-guard removal is correct now that the salt subsumes it. On _admit_requests: I'd gently push back on inlining — it's called once in the engine loop, but the extraction is what makes test_admit_requests_threads_cache_salt_to_vllm possible without spinning up the engine loop. Keeping it as a small named method has a real testability payoff, so I'd lean toward keeping it.


Additional findings (not yet raised)

  1. Validation and training salts share one integer namespace. Validation uses cache_salt=str(step) (controller.py:673) while training uses cache_salt=str(work.policy_version_at_start) — both bare stringified ints. A validation request with salt "5" and a training group pinned to version 5 live in the same prefix namespace. In practice their prompt prefixes differ (so no real KV is shared) and the weights match at that step anyway, but the overlap is a latent footgun the moment prompts or timing shift. Recommend a distinct prefix, e.g. cache_salt=f"val-{step}", so validation can never alias a training version. Fix this →

  2. GenerateFn Protocol (rollout/types.py:36) wasn't updated. It still lists only request_id / routing_session_id / sampling_config. That's fine today because the salt is closed over rather than passed as an argument — but it means the protocol no longer documents that a per-group namespace even exists. If you adopt tianyu-l's suggestion of threading the value through run_group_rollouts, the Protocol should gain the neutral-named field and its docstring.

  3. Magic literal in the docstring example (work_buffer.py, policy_version_at_start=3). Cosmetic — 0 or an inline comment reads less arbitrarily in a doc example.

  4. reset_running_requests=True is now hardcoded in _pull_model_state_dict (generator.py) since the separate flag was removed. That's the correct simplification — when a user explicitly opts into reset_kv_cache_on_weight_sync, they want both prefix drop and running-request preemption. Just confirming this is intended and not a lost degree of freedom anyone relied on.

Nice work overall — the version-publish-after-all-generators ordering and the honest documentation of the KV-spanning caveat are the parts that make this trustworthy. The remaining items are about keeping the vLLM term at the adapter boundary and loosening the data-loop/weight-sync coupling.
• branch per-group-kv-cache-salt

@wwwjn wwwjn changed the title [RL] Preserve per-group KV cache across policy updates [WIP][RL] Preserve per-group KV cache across policy updates Sep 25, 2026
@wwwjn
wwwjn force-pushed the per-group-kv-cache-salt branch from 805d2a6 to 242a5c6 Compare September 25, 2026 01:43
@wwwjn wwwjn changed the title [WIP][RL] Preserve per-group KV cache across policy updates [RL] Preserve per-group KV cache across policy updates Sep 29, 2026
Comment on lines -663 to -664
self._rollouter.run_group_rollouts(
generate_fn=generate,

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.

why this change?

Comment thread torchtitan/rl/controller.py Resolved
Comment thread torchtitan/rl/generator.py Outdated
def _cache_salt(self, request: GenerationRequest) -> str:
"""vLLM cache salt for ``request``: the version the router chose, or this
generator's installed version when the router passed None."""
if request.cache_policy_version is 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.

would it ever be None in torchtitan?

Comment thread torchtitan/rl/generator.py Outdated
self._pull_model_state_dict_future = None
self._model_state_dict_pull_request = None

def _cache_salt(self, request: GenerationRequest) -> str:

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.

do we really need this as a function?

Comment thread torchtitan/rl/generator.py Outdated
prompt_token_ids: list[int] # [prompt_tokens]
sampling: SamplingConfig
routing_session_id: str
cache_policy_version: int | 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'm not sure how accurate this is.

E.g. if I set reset_kv_cache_on_weight_sync=True, would what we set here really be the cache policy version? cache is always updated regardless of what this version is.

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.

changes in this file look very complicated

  • it seems the main thing you want to do is to have a cache to map group_id to its initial generator policy version?
  • is it easier if we handle this mapping inside generator, rather than in generator router?

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.

it seems the main thing you want to do is to have a cache to map group_id to its initial generator policy version?

Yes, all rollout in the same group always pointing to the same salt. I was thinking we can update the map to be {"rollout_session_id": initial_generator_policy_version}. The current routing strategy doesn't route sibling rollouts to the same generator, so there's not much gain sharing the prompt kv cache on each the generator.

  • where as routing_session_id = "group=G/rollout=R"
  • sibling here means rollout in the same group

is it easier if we handle this mapping inside generator, rather than in generator router?

Yes that's a simpler design. I will update the PR to that and make it simplified

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review my review -- I think the change in generator router is too complicated

@claude

claude Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 47s —— View job


Review of @tianyu-l's review: the generator router changes

  • Get the PR diff (a6aa607..5bddfbf)
  • Read inter_generator.py and the generator, controller and verifiers changes
  • Assess the router complexity and alternatives
  • Post review

Verdict: I agree the router change is too complicated. Your suggestion to keep the mapping inside the generator is the better design. Almost everything inter_generator.py now tracks, the generator already knows or could track more accurately. The version-rollback wait loop is a separate feature that got bundled into this PR.


What the router currently does (+172 lines)

  1. It keeps its own copy of each generator's version in _GeneratorHandle.policy_version. The generator already has this as self.policy_version.
  2. _GroupCacheNamespace holds (generator, cache_policy_version, sessions), and it is pinned when the group's first call is routed.
  3. _RoutingSession holds (generator, cache_policy_version, max_policy_version) for each rollout. It is rebuilt from result.min_policy_version when the router passed None.
  4. A while True wait loop uses _routing_state_changed to block calls that would land on a generator older than session.max_policy_version or group.cache_policy_version.
  5. _reusable_cache_policy_version returns a version, or None to mean "the generator picks." This two-level protocol is why you asked at generator.py:1277 whether it can ever be None.
  6. The finish_group endpoint, the controller's _run_group_rollouts wrapper and the validation rewiring (your comment at controller.py:664) exist only to clean up item 2.

The router is effectively guessing what KV each vLLM engine holds. It does so at the wrong granularity: a generator with intra-mesh DP has one KV pool per DP rank. Siblings have different routing_session_ids, so they can land on different DP ranks, and "the group's generator holds the group prompt's KV" doesn't hold there.

A simpler equivalent: pin the salt at engine admission

The router forwards routing_group_id the same way it already forwards routing_session_id, and does nothing else. The generator then resolves the salt locally:

# VLLMGenerator: rank-local, because each DP engine owns its own KV
self._group_cache_salts: dict[int, str] = {}

# at admission (the render_cmpl dict)
"cache_salt": self._group_cache_salts.setdefault(
    request.routing_group_id, str(self.policy_version)
),

# _pull_model_state_dict, reset mode
if self.config.reset_kv_cache_on_weight_sync:
    self._engine.reset_prefix_cache(reset_running_requests=True)
    self._group_cache_salts.clear()  # the KV is gone, so move every group to the new namespace

This reproduces every row of the PR's salt table:

Case Router design Generator-local setdefault
1st turn on the group's generator group salt the group's entry on this engine (same)
Sibling placed on another generator that generator's version first arrival pins this engine's version, and later siblings there share it, so the group prompt is reused on B too. That is strictly better.
Later turn on the same generator rollout salt the group's entry on this engine (same value)
Rerouted later turn destination's version destination's group entry if one exists, otherwise its current version. The mixing is the same tradeoff Mode 1 already accepts.

It also closes your weight_sync.py:121 concern by construction: the salt is always a version that the engine doing the prefill has actually installed. You don't have to reason about when a version gets published across generators.

Here is how this resolves your other comments:

  • generator.py:1277 ("would it ever be None?"): the None sentinel goes away.
  • generator.py:1274 ("do we need a function?"): the helper becomes a one-line setdefault and can be inlined.
  • generator.py:1445 ("cache_policy_version isn't accurate under reset"): agreed. GenerationRequest would carry the neutral routing_group_id, next to routing_session_id, and the version-based salt stays an internal detail of the generator. In reset mode, clearing the map makes the salt trivially consistent.

Cleanup is the one open detail. Group ids are unique for training, but validation reuses negative ids. If a stale entry for group -1 survived to the next validation, it would hit KV computed under older weights. There are two options:

  • Give validation globally unique ids, for example by folding step into the negative id, and drop entries by age on each pull. Losing an entry only costs a cache miss.
  • Keep finish_group, but have it reach the rank-local maps.

The first option lets you delete finish_group, _run_group_rollouts and the validation change.

The rollback wait loop should be its own PR

_min_policy_version, _choose_not_older_than and _routing_state_changed enforce that "a rollout never samples from an older generator than before." That is about keeping policy versions monotonic, not about whether the KV is correct, and the same issue exists on main today during hot-swap pulls. It also adds a liveness risk: if the only generator at session.max_policy_version leaves SERVING and never comes back, the call waits forever with no timeout or warning. If we want this behavior, it deserves its own PR, tests and justification.

The same applies to switching the default strategy from LeastLoadedRoutingStrategy to StickySessionRoutingStrategy. It changes behavior for every recipe, and the PR says the DAPO numbers predate it. It should be split out and measured separately.

On controller.py:477 (group id bound in _make_generate_fn)

Agreed, this is inconsistent. The PR description and test plan still say "one GenerateFn serves every group and forwards each call's routing_group_id," but commit 5bddfbf went back to closing over group_id per group. Closing over it is also what forced the verifiers GenerationServer to add a per-group registry: serve_group, uuid keys, GROUP_KEY_SAMPLING_PARAM → GenerateFn, and 409s for late requests.

My recommendation: add routing_group_id: int | None = None to the GenerateFn protocol next to routing_session_id. It is a routing key, not a vLLM term, so your objection to putting a salt on generate_fn doesn't apply. Then keep one GenerateFn for the whole run as on main. The verifiers server still needs the group id in sampling_params, but it can forward the int directly instead of maintaining a registry of closures.

Expected size after the change

  • inter_generator.py shrinks from +172 lines to about +5, since it only threads routing_group_id through.
  • Most of the +345 lines in test_inter_generator_router.py can be deleted.
  • generator.py gains a dict and one setdefault, and unit tests at admission cover the same salt table.

That keeps KV-cache knowledge next to the KV cache (principle 3) and keeps the router a pure placement layer.
• branch per-group-kv-cache-salt

@wwwjn
wwwjn force-pushed the per-group-kv-cache-salt branch from 5bddfbf to 504efe7 Compare September 30, 2026 00:33
Comment thread torchtitan/rl/generator.py Outdated
)

self.policy_version = 0
# RANK 0: group id -> routing session id -> policy version the session's cache

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.

Today, router won't necessarily send all rollouts in the same group to the same generator -- that's fine, we can revisit later.


CASE 1: reset = False

Then this code is saying different sessions (whose id is a str composed of group id + rollout id) can have different salts, if their first turns arrive at different generator policy versions.

Lastly a minor point, even so we can achieve the same by keeping a dictionary of session id to policy versions? I guess the point is that you would like to clear the key when the group is released. It makes sense, but a more clean way is to maintain dict {group_id: {rollout_id: policy_version}}. We are using session id instead of rollout id, simply because router consumes that as a single string, which is ... fine. Could you add a NOTE on the motivation of this nested dict.


CASE 2: reset = True

In this case, we don't need to maintain this dict at all, right? Every one's KV cache will be up to date. So let's make this dict None in that case. Correct me if I'm wrong.

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.

Even if they get different policy versions, would it hurt if we use the "first arrived" session's policy version as the salt, shared by all the sessions in the same group? In other words, can we make this a dictionary from group id to policy version. It can help sharing prompt kv cache among sessions, and is also easy to understand.

if their first turns arrive at different generator policy versions

The hurt of using the "first arrived" session's policy version is for the later arrived rollout, the prompt kv cache is a stale, and using session_id as the key let the later arrived rollout re-prefill the prompt. I think using group_id as the dict key ({group_id: salt}) and allowing a little bit staleness in the prompt is not a important thing here, and using session_id as a string is convient and already passed to geneate_fn. That's why I chose session_id before.

I actually don't have strong opioins between using group_id / session_id as the key, the pros and cons are clear. If the group_id as the key is straight forward, I could quickly change it back.

I guess the point is that you would like to clear the key when the group is released

yes we still passing group_id to generate_fn because we need to release a group at a time.

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.

sure, let's keep what you are doing

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.

It can help sharing prompt kv cache among sessions, and is also easy to understand.

Sorry for back and forth, I think you are right that using group_id is easy to understand. And the stalenss of the prompt doesn't matter that much given we already have so many stalenss in this version. Given we always need to pass group_id, I changed it back to be using group_id.

The final dict content is {group_id: salt}, no need to be a nested dict at this moment.

Comment thread torchtitan/rl/generator.py Outdated
# only exists so the controller, which knows group ids but not session ids, can
# drop a finished group's pins. Only the controller knows when a rollout has no
# more turns, so entries live until it calls `release_groups`.
self._cache_policy_versions: dict[int, dict[str, int]] = {}

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.

ambiguous name, maybe just

Suggested change
self._cache_policy_versions: dict[int, dict[str, int]] = {}
self._min_policy_versions: dict[int, dict[str, int]] = {}

or if you buy the "same group share salt" idea, we can rename to _group_min_policy_versions

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.

despite what claude said, I still think it's mentally cleaner if we don't maintain this dict when reset=True, in which case we don't need a salt at all?

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.

Removed it!

# Always reset running requests too: the only reason to reset is a strict
# recompute under the new weights. Keeping running requests' KV while hiding
# old KV from new requests is already what the default (no reset) does via the salt.
self._engine.reset_prefix_cache(

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.

for my understanding: Even if we don't call this line -- we won't reuse because the salt we set will be updated, and vllm would eventually clear the old cache. And this code just do it instantly (which is good for peak memory). Is this true? If so, could you add a note here.

see comment above

Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/generator.py Outdated
self._rank0_generation_futures[
request.request_id
].min_policy_version = policy_version
].min_policy_version = request.cache_policy_version

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 this is a strict improvement / bug fix?

In the past, turn 3 of a rollout will set this to be the policy version seen by turn 3; but now, under reset=False, all turns will set this to be the policy version of turn 1.

I think this could be reconciled with my comment of not maintaining it when reset=True

  • either always maintaining the dict
  • or here pass in policy_version like before, and if request doesn't already have a min_policy_version, set it to policy_version

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.

In the past, turn 3 of a rollout will set this to be the policy version seen by turn 3

if reset_on_weight_update=True, there's no bug, the policy version is the correct policy version. But when reset=False, yes previously this is a bug.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review latest change and review my review

@claude

claude Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 10s —— View job


Review of the latest change + review of @tianyu-l's review

  • Get the PR diff (46ec3f2..8aadf7b)
  • Review the latest changes
  • Review @tianyu-l's latest comments
  • Post review

Overall: The redesign addresses the last round of feedback. inter_generator.py went from +172 to +7 lines. The router now only forwards group_id and fans out release_groups. The pins live in the generator, next to the KV, and one GenerateFn serves the whole run again. GenerationRequest now uses neutral names, and cache_salt shows up only in the render_cmpl dict. The verifiers per-group registry is gone. I found one real bug (a misplaced decorator) and a few smaller items. I couldn't run the unit tests here because the command needed approval.


Findings on the latest change

1. Bug: @sl.log_trace_span("pull_model_state_dict") is now on release_groups (generator.py:1311). release_groups was inserted between the decorator and pull_model_state_dict. As a result, every release_groups call is traced as a pull_model_state_dict span, and the real pull endpoint loses its span. Move the decorator back onto pull_model_state_dict. Fix this →

2. A failed release_groups call stalls the buffer (controller.py:967). The call sits outside the try, and _fanout uses return_exceptions=False. If any generator fails the RPC, the exception skips finalize_work(group) and kills this rollout worker, so the claimed buffer slot is never finalized. Releasing a pin is best-effort, since losing one only costs a stale dict entry. It should not take down the rollout loop. Either use _fanout(..., return_exceptions=True) and log the failures, or move the release into a finally that swallows and logs errors. The validation call at controller.py:669 has the same exposure.

3. The GenerateFn docstring no longer matches the design (rollout/types.py:50). It says "Calls of one group share a prefix cache namespace, so siblings and later turns can reuse the group's KV." Pins are now keyed per session, so that text describes the design you moved away from. Its wording will need to change again if you adopt the per-group suggestion below.

4. Duplicated validation in the verifiers generation server (generation_server.py:181). _parse_sampling_config already raises sampling_params must be an object for non-dicts. The new isinstance check repeats that error. You still need the dict(...) copy before pop, but the check itself can go.

5. Minor: one RPC per group. release_groups fans out to every generator rank once per finished group. The cost is small next to generation. Since the endpoint already takes a list, batching releases would be easy later if it ever shows up in traces.


Review of @tianyu-l's comments

generator.py:983, CASE 1: pin per group instead of per session. I agree, and I'd go further: the two designs differ only in a rare corner case. The pin values are policy versions, so siblings admitted to the same engine at the same version already share a salt and reuse the group prompt under per-session pins today. The two designs give different results only when a weight pull lands between two siblings' first admissions on the same generator. As you note, that is rare because run_group_rollouts dispatches siblings together. In that window:

  • A per-session pin gives the late sibling fresher KV, but it re-prefills the group prompt, which is short.
  • A per-group pin reuses the prompt KV. The late sibling honestly reports the older min_policy_version, so max_offpolicy_steps still accounts for it.

Both are correct, and neither has a measurable perf difference. The per-group version is a flat dict[int, int], with no nested dict, no session key and an easy-to-explain rule. I'd take the simpler one: self._group_min_policy_versions.setdefault(request.group_id, self.policy_version). That also resolves the naming comment at 991 and removes the need for the NOTE about the nested dict. If @wwwjn keeps per-session pins, the nested dict is the right shape, but it deserves the NOTE you asked for. The current comment (generator.py:983-990) mostly covers it already.

generator.py:991, naming. Agreed. _min_policy_versions / _group_min_policy_versions lines up with the Completion.min_policy_version value it feeds. _cache_policy_versions is exactly the name you already flagged at 1445 as inaccurate under reset.

generator.py:983 / 1368, CASE 2: the dict isn't needed under reset. Your reasoning is right. Under reset, clear() runs on every pull, and self.policy_version only changes at a pull. So any pin set since the last pull always equals self.policy_version, which makes the dict redundant bookkeeping. It is not a bug, because the output is identical either way. The choice is between:

  • (a) keeping one code path and adding a one-line comment ("under reset, every pin equals self.policy_version"), or
  • (b) setting the dict to None when reset is on and branching at admission.

I lean slightly toward (a), because (b) adds a branch at admission and one in release_groups to save a dict that gets cleared anyway. Either is fine, though. If you pick (b), release_groups must handle None.

generator.py:468, "strict improvement / bug fix?" For this PR's default it is a required change more than a bug fix. On main's default (reset on every pull), turn 3 could never hit KV from before the pull, so stamping the admission version was correct. It was only wrong for main's non-default reset_prefix_cache_on_weight_sync=False. That config silently under-reported staleness, and it matters because TrainingSampleBuilder keeps a separate min version for each packed turn span (training_sample_builder.py:184-236). With preserve as the default, turn 3 may reuse turn 1's KV, so turn 3 must report turn 1's pin. The current code does this correctly: under reset the pin equals the admission version, so behavior matches main.

generator.py:1372 (struck through). Agreed that it's moot. One point for the record: under preserve, old-salt blocks are never cleared eagerly. They go through vLLM's normal LRU eviction, so skipping a reset doesn't raise peak memory. The KV pool is preallocated either way.

Earlier comments that are now resolved: the salt on generate_fn (now group_id is a routing key on the protocol), the vLLM term (it appears only in render_cmpl), WeightSyncManager in the data-input loop (removed), publishing a version before every generator has pulled (the salt now always comes from the version installed on the engine doing the prefill), None in _cache_salt (removed), and the one-use helper (inlined).


Summary

Fix the decorator (1) and make the release best-effort (2) before merging. Items 3 and 4 are small cleanups. On design, I agree with @tianyu-l that a flat per-group pin is the simpler choice with no real downside. The reset-mode dict question is cosmetic.
• branch per-group-kv-cache-salt

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

great work, one more nit comment

Comment thread torchtitan/rl/generator.py Outdated
Comment on lines +1201 to +1211
prompts = [
{"prompt_token_ids": request.prompt_token_ids}
for request in local_requests
]
if not self.config.reset_kv_cache_on_weight_sync:
# Salt by the pinned version so a request only reuses KV
# computed under that version.
for prompt, request in zip(
prompts, local_requests, strict=True
):
prompt["cache_salt"] = str(request.min_policy_version)

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.

nit on code structure, would be more readable if

prompts = []
for request in local_requests:
    prompt = {"prompt_token_ids": request.prompt_token_ids}
    if not self.config.reset_kv_cache_on_weight_sync:
        prompt["cache_salt"] = str(request.min_policy_version)
    prompts.append(prompt)

@wwwjn
wwwjn force-pushed the per-group-kv-cache-salt branch from 20250eb to d28a919 Compare October 1, 2026 17:52
@wwwjn wwwjn closed this Oct 1, 2026
@wwwjn wwwjn reopened this Oct 1, 2026
@wwwjn
wwwjn merged commit ab51d13 into pytorch:main Oct 1, 2026
32 of 43 checks passed
Armandpl added a commit to commaai/torchtitan that referenced this pull request Oct 21, 2026
* [DSV4] Place compressed KV at its group's first token when positions is None (#4932)

# Summary
Bug fix; since we compress tokens via ratio e..g HCA is 128 key
compressions. Token one shoudl get rope freq0 and then token 2 needs
rope freq 128. We dropped this offset when no positions are passed in.
Probs doesnt show up but good to fix regardless


### Agent note
Compressed entry j summarizes tokens [j * ratio, (j + 1) * ratio) and,
as in the DeepSeek-V4
reference, takes the RoPE position of its first token, j * ratio. With
explicit positions the
compressor used positions[::ratio], which is that. Without positions it
passed None to RoPE,
which then placed entry j at position j, so a model called without
positions (tests,
standalone calls) computed different compressed-KV RoPE than the
training path, which always
passes positions (the collators materialize them). On the debug model
the two disagreed by
5.6% relative in the logits.

The default now matches explicit positions: torch.arange(0, seqlen,
ratio). The training path
is unchanged.

The new CPU test compares the CSA (ratio 4) and HCA (ratio 128)
compressors with and without
positions; it fails before this change.

---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>

* [graph_trainer] Link public Slack channel in README (#4953)

Adds a note near the top of the GraphTrainer README inviting users and
developers to join the public PyTorch Slack channel
(https://pytorch.slack.com/archives/C0C4ZRE5BL7), so there is a
discoverable place for questions, discussion, and updates.

Docs-only change; no code affected.

* [graph_trainer] Remove graph-based EP chunking (#4952)

## Why

EP overlap had two chunking strategies: `eager` (wrap module forwards
before tracing) and `graph` (`ep_chunk_pass.py`, which rewrites the
traced graph using unbacked SymInts, a concretize pass, and trace-input
preparers). The graph strategy duplicated what eager chunking already
provides while being a large maintenance surface (~2.5k lines of pass
code plus ~2k lines of tests). This PR keeps EP overlap and removes only
the graph chunking path.

## What

- Delete `ep_chunk_pass.py` and the graph-only helpers in
`ep_pass_utils.py` (region discovery via `collect_chunked_regions` is
kept).
- Drop `EpOverlapConfig.strategy` (eager is the only mode) and
`disable_early_grad_accumulation` (graph-only).
- `ep_overlap_schedule_pass` is unchanged; the pipeline is
`populate_eager_chunk_metadata_pass` -> `isolate_ep_process_group_pass`
-> DCE -> `ep_overlap_schedule_pass`.
- `--compile.enable_fsdp_dense_region_overlap` only composed with graph
chunking; with ep_overlap enabled it is now skipped with a warning
(standalone behavior unchanged).
- Remove the now-unused `TRACE_INPUT_PREPARERS` /
`TRACE_CALL_INPUT_PREPARERS` registries, `trace_input_preparer_keys`,
and the `prepare_inputs` / `prepare_call_inputs` args of
`minimal_fx_tracer`. `PASS_PIPELINE_REGISTRY`, `POST_INIT_HOOKS`,
`PRE_TRAIN_STEP_HOOKS` are kept.
- Tests: remove graph-chunking unit tests and the graph-vs-eager
loss-compare tests; `test_ep_chunk_matches_eager_chunking_bitwise` now
compares an eager-chunked `Trainer` against `GraphTrainer` with
ep_overlap enabled.

## Testing

- `pytest torchtitan/experiments/graph_trainer/tests/test_passes.py`:
182 passed, 1 skipped (includes the 11 eager-chunking tests).
- `pre-commit`: clean except Pyrefly missing-import errors in untouched
files (local env).
- `pytest
torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py
-k TestDSv3FlexAttnBitwiseDeterministic` (GB300): 3 passed, 2 skipped
(pre-existing skips), including
`test_ep_chunk_matches_eager_chunking_bitwise` (eager-chunked `Trainer`
vs `GraphTrainer` with ep_overlap, bitwise identical).

* [deepep] free dispatch handles replayed by FullAC early-stopped recompute (#4918)

Human note:

This PR changes ~1 lines of code. Theres a dict whose content is never
deleted in Full AC with early stop. I added a line that deletes it.

Last week i landed a PR removing the hardcoded `early_stop=False` from
FullAC. This slows down models in ~1-4% and was added because of MoE
memory leakage. At the time, i tested MoE and didn't see any leakage.

Today, testing DeepEP and HybridEP, i saw the leakage for DeepEP
**only**. This PR changes ~1 lines of code, but the agent added a lot of
(useful) context for the reviewer.

Note: 
- One specific function is not compilable anymore
- The real fix would be to do it like HybridEP, but it would require a
big refactor

-----

TLDR:

- With the DeepEP dispatcher and full activation checkpointing (FullAC),
MoE training leaks GPU memory every step. On Qwen3-30B-A3B, peak active
memory goes 64 -> 77 GiB in 100 steps, with 14 allocator retries by step
100. With this PR it stays flat at ~64 GiB.
- Cause: every dispatch stores a handle in a global dict, and only
combine removes it. FullAC re-runs dispatch during backward but stops
before re-running combine, so that handle is never removed: one leak per
MoE layer per step.
- Fix: a `weakref.finalize` removes an entry when its `handle_id` tensor
is garbage-collected, so an entry whose combine never ran is freed too.
Combine still removes its entry first, so nothing changes on the normal
path.

## DeepEP 101

In an MoE layer, each token picks its top-k experts (Qwen3-30B-A3B: 8 of
128). With expert parallelism (EP), the experts are split across GPUs,
so every token has to travel to the GPUs that hold its experts, and the
expert outputs have to travel back:

```
             GPU 0 (experts 0-63)                              GPU 1 (experts 64-127)
x -> router -> dispatch ==== NVLink / RDMA all-to-all ====> expert GEMMs -> combine ==== back to each token's GPU ====> sum -> + x
```

- **dispatch** sends each token to the GPUs holding its experts.
- **combine** sends the expert outputs back and sums them per token.
- **DeepEP** (DeepSeek's library) provides fast kernels for these two
steps.

Dispatch also returns a **handle**: the routing layout (which token went
where). Combine needs it to route outputs back, and so does backward,
since dispatch's backward is a combine and combine's backward is a
dispatch. The handle holds routing buffers on the GPU (~2.8 MB each at
this shape, estimated from the leak rate).

PyTorch custom ops can only pass tensors between each other, so
`deepep.py` keeps each handle in a Python dict keyed by an int, and
passes that int around as a tiny CPU tensor, `handle_id`:

```
dispatch(x)          -> recv_x, ..., handle_id          # _handle_cache[id] = handle
combine(y, handle_id) -> out                            # handle = _handle_cache.pop(id)
```

## How the leak happens

Full activation checkpointing (FullAC) saves memory by not keeping a
layer's activations. During backward it re-runs the layer's forward
("recompute") to rebuild them. Since #4836, that recompute stops early,
as soon as it has rebuilt the last tensor backward needs. In the MoE
layer that tensor comes right before combine; nothing after combine
needs saving.

One MoE layer, one training step, on main:

```
forward:          dispatch -> cache[N] = handle      experts      combine -> cache.pop(N)     cache = {}
backward:
  recompute:      dispatch -> cache[M] = handle      experts      X  stops early, combine never re-runs
  gradients:      use handle N, which autograd kept                                          cache = {M}   <- leaked
```

Every step leaves one entry per MoE layer, and each entry keeps its
handle's GPU buffers alive: 48 layers x 100 steps ≈ 13 GiB.

Other setups aren't affected:
- **Selective AC:** it saves the dispatch/combine outputs instead of
re-running them, so dispatch never runs a second time.
- **HybridEP:** its op returns the handle itself as an opaque object,
with no dict, so a re-run handle is freed with the recompute's outputs.
- **All-to-all dispatcher:** it has no handle at all.

## The fix

```python
handle_id = _get_next_handle_id()
handle_key = handle_id.item()
_handle_cache[handle_key] = handle
# weakref.finalize(obj, fn) calls fn() once obj is garbage-collected.
# FullAC's recompute replays dispatch but stops before combine; this frees that handle.
weakref.finalize(handle_id, lambda: _handle_cache.pop(handle_key, None))
```

- Normal path: combine pops the entry as before, and the finalizer finds
nothing to remove.
- Re-run dispatch without a combine: when the stopped recompute drops
its outputs, `handle_id` is freed and the finalizer removes the entry.
- `@torch.compiler.disable` on the dispatch kernel: the op has no fake
implementation, so `torch.compile` graph-breaks and then traces the
kernel as a regular Python frame. Dynamo can't trace `weakref.finalize`:
it guards on `weakref.finalize._registry`'s size, which the call itself
changes.

### Result
8x H100, Qwen3-30B-A3B random init, dp_shard=4 tp=2 ep=2, DeepEP v2,
FullAC, 32k tokens/DP rank, c4, bf16, no compile, 100 steps. Rank 0 peak
memory (GiB):
```
                           step 2     20     40     60     80    100   alloc retries   median tps
peak active    main r1       64.3   67.3   69.3   72.6   73.5   77.2        14            5252
               main r2       64.3   66.6   69.0   71.8   73.9   77.0        14            5294
               this PR       64.0   64.7   64.4   63.9   64.2   63.8         0            5380
peak reserved  main r1       70.5   73.0   75.4   78.4   81.3   82.5
               this PR       70.2   71.0   71.1   71.1   71.1   71.1
```

Loss over steps 81-100: 7.726 / 7.580 for main r1 / r2, and 7.753 for
this PR. DeepEP runs aren't bitwise reproducible, so that spread is
run-to-run noise.

### Works with other features
CPU, the real DeepEP ops against a single-rank fake buffer; entries left
in `_handle_cache` after 2 fwd+bwd steps (`compat_checks.py`):
```
                                   main   this PR   grads match no-AC
no AC                                0       0            yes
FullAC, early stop (default)         2       0            yes
FullAC, early_stop=False             0       0            yes
selective AC (DeepEP ops saved)      0       0            yes
RegionAC, DeepEP regions replayed    0       0            yes
RegionAC, DeepEP regions saved       0       0            yes
torch.compile (aot_eager), no AC     0       0            yes
torch.compile (aot_eager) + FullAC   2       0            yes
no_grad / inference_mode forward     0       0             -
exception between dispatch/combine   1       0             -
```
- **Quantization:** Float8/MXFP8 change the expert GEMMs, not
dispatch/combine, so they don't touch the handle cache.
- **CUDA graphs, inference** (generator, expand layout): checked on 2
GPUs with the real `ElasticBuffer` (`cuda_graph_check.py`). Capture plus
5 replays on new inputs match eager bitwise, with 0 entries left, same
as main. Combine still pops at capture time, and replay runs no Python.
- **CUDA graphs, training:** config validation already rejects DeepEP
with trainer CUDA graphs (only non-blocking HybridEP is allowed), so
this path doesn't exist.
- **Graph trainer:** it traces with `make_fx` under `FakeTensorMode`,
which needs fake impls. HybridEP has them; DeepEP's ops don't, so DeepEP
isn't supported there on main either. This PR doesn't change that.
- **Pipeline parallel:** each micro-batch's dispatch has its own
`handle_id`.
- NOTE: not run on GPU: `torch.compile` (CPU: aot_eager and inductor,
including `fullgraph=True`, all leave 0 entries) and PP.

## Q&A

- **Why not just set `early_stop=False`?** It also fixes the leak, since
the recompute then always reaches combine. But every layer's backward
would re-run the combine communication and the rest of the block, for
every model.
- **Now that the finalizer exists, why keep combine's pop and the
`will_backward` flag?** I tried removing them. It's correct, but under
`torch.compile` dynamo keeps a reference to one `handle_id` per compiled
frame, so without combine's pop that handle lives until torchtitan's
next `gc.collect()` (torchtitan disables automatic GC). Keeping the pop
leaves lifetimes identical to main whenever combine runs.
- **Why not return the handle as an opaque object, like HybridEP?**
That's the right end state, and it deletes the dict entirely. It changes
both op schemas and needs its own compile/SAC validation, so there's a
`TODO` next to `_handle_cache`.
- **Why not save the DeepEP outputs under FullAC, as Selective AC
does?** It would remove the re-run dispatch (an all-to-all plus a host
sync per layer in backward). But it keeps each layer's dispatch and
combine outputs, roughly 9 GiB at this shape (estimate). That's a
separate perf trade-off.

## Code changes

- `torchtitan/distributed/deepep/deepep.py` (+12 / -1: one existing line
now reuses `handle_key`):
  - `weakref.finalize` on each `handle_id`.
  - `@torch.compiler.disable` on the dispatch kernel.
  - Comments, plus a `TODO` for the opaque handle.
- `tests/unit_tests/cpu/test_deepep_handle_cache.py` (new):
  - Runs the real DeepEP ops on CPU against a single-rank fake buffer.
- Covers FullAC with early stop on/off, `torch.compile`, and an
inference forward, checking that no entry is left.
  - Skips when `deep_ep` isn't installed.

### Validation
- New test: 4 passed. On main,
`test_full_ac_recompute_frees_handles[True]` fails. Without
`@torch.compiler.disable`, `test_compile_frees_handles` fails with the
dynamo guard error.
- `tests/unit_tests/cpu/test_inference_moe.py` passes.
- pre-commit passes. Pyrefly reports 0 errors on `deepep.py`; I ran it
by hand because the hook can't run from a worktree path.
- GPU runs (wandb project `qwen30b_moe_pretrain_pr68_pr55`):
- this PR:
https://meta.wandb.io/felipemello/qwen30b_moe_pretrain_pr68_pr55/runs/fc0l7x3n
- main r1:
https://meta.wandb.io/felipemello/qwen30b_moe_pretrain_pr68_pr55/runs/zo867pzz
- main r2:
https://meta.wandb.io/felipemello/qwen30b_moe_pretrain_pr68_pr55/runs/0znra4x7

---------

Co-authored-by: Felipe Mello <[email protected]>

* local_spmd regions with spmd.local_map (#4960)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* __->__ #4960

mistake here, from tests seems not much was incorrect

* [graph_trainer] Skip PP stage metadata inference for SPMD (#4944)

Fixes #4921

Adding is_spmd flag to GraphRuntime and Schedule to skip PP specific
initializations, that OOMed because of using real memory.

* [graph_trainer] Keep Shard(0) for routed experts when EP covers the experts (#4949)

#4867 made data_parallel look up linear_param_shard_placements(model)
for every parameter.

When `edp_shard * ep <= num_experts`, apply_simple_fsdp wraps routed
experts with shard_dim=0 to match core FSDP, which shards every
routed-expert parameter on the expert dimension.

The new lookup overrode that for the stacked W13 GroupedLinear weight,
sharding it on dim 2 instead. Sharded init then diverged from eager and
test_moe_qwen3_aot_fx_trace_vs_eager failed at step 1 (7.719911098480225
vs 7.716061592102051).

This PR lets callers pass param_shard_placements explicitly. The
expert-dim path passes {} so all routed-expert parameters use Shard(0)
again.

Note: agent pointed out " EP=1 may still have a placement mismatch
between eager and GraphTrainer." - no test currently covers this, and
this PR doesn't address it. We should discuss/review it.

Test Plan:
- pytest torchtitan/experiments/graph_trainer/tests/test_numerics.py -k
"moe_qwen3 or stacked_ or dsv3_ep_overlap_moe or dense_qwen3" (8x H100):
  qwen3 MoE losses match eager bitwise over 20 steps (failed before);
  EP-overlap seq/batch, dense qwen3 and both stacked-linear tests pass.

* Replace Tyro CLI with Python config loading (#4908)

## Human note

- removed Tyro capability: CLI now only supports few core launching
options, e.g. `--override`, `--output_dir`, `--comm_backend` (can be
found at torchtitan/config/README.md)
- removed `update_from_config` -- set sharding is done at model
constructor
- token dispatcher backend selection now is a `ModelConfigTransform`
- `moe_force_load_balance` is moved to `RoundRobinTokenChoiceTopKRouter`
as "model code"

## Summary
- replace Tyro-generated training flags with a small `ConfigLoader` CLI
for `--module`, `--config`, registered `--override`s, and operational
launch settings
- move model derivation into recipe construction, model config
transforms, and model constructors; keep context length aligned across
training, RoPE, and vLLM
- make MoE dispatcher selection a context-aware config transform and
model forced balancing a dedicated round-robin router
- migrate integration and numerics launchers to complete Python config
recipes and remove the Tyro dependency

## Testing
- `pre-commit run --all-files`
- focused CPU suites: 290+ passed (with expected skips)
- full CPU collection is blocked locally by the installed PyTorch
missing `torch.utils.checkpoint._is_cacheable_effect` required by
GraphTrainer

* [Fix] RoutedExperts output_postprocess parameter under FSDP (#4954)

`RoutedExperts.output_postprocess` can have a parameter. FSDP did not
handle it correctly, even when one specifies `SpmdType` for it.


https://github.com/pytorch/torchtitan/blob/156949fa579d021e6f7b500d1d24e40ec47cef55/torchtitan/distributed/fsdp.py#L351-L359


https://github.com/pytorch/torchtitan/blob/156949fa579d021e6f7b500d1d24e40ec47cef55/torchtitan/distributed/fsdp.py#L394-L411

Without a change in `fsdp.py`, one `SpmdType` for `output_postprocess`
does not work
- Sparse SpmdType
- expert_sharding_size > num_experts: omitted by the linear-only map,
incorrectly selects dense mesh.
- expert_sharding_size <= num_experts: correctly selects sparse mesh.
- Dense SpmdType
- expert_sharding_size > num_experts: omitted, correctly selects dense
mesh.
- expert_sharding_size <= num_experts: included with all routed
parameters, incorrectly selects sparse mesh.


Currently, `RoutedExperts` runs with `local_spmd=True` which has
`spmd.no_typecheck()`, so both dense or sparse `SpmdType` could
technically work. Semantically, sparse `SpmdType` would make more sense,
so I am going with sparse.

But using dense could save more memory because 
`edp_shard = dp_shard * cp * tp / ep` so compared to dense fsdp, sparse
fsdp shards less, and would use `ep/tp >= 1` factor more memory.




## Test Plan
- `taskset -c 0-7 python -m pytest -q
tests/unit_tests/gpu/test_fsdp_moe_sharding.py::TestApplyFsdpMoESharding`
6 passed
- Verified the new eight-GPU regression across both expert-sharding
branches, including forward, backward, and state-dict round-trip.

* [DSV4] Support packed documents (#4943)

### Human note

Wires up the packed dsv4 training; ran a bunch of experiements the
interesting offset in loss has to do with `real` tokens e.g. non padded
up to the seqlen model when the sequences dont evenly divide

## Agent Note

DeepSeek-V4 rejected packed batches (#4879) because its compressors, CSA
indexer, and sparse attention cores
ignored document boundaries. Attention Gym 0.0.14's `gather_attn` and
`lightning_indexer` accept packed
`cu_seqlens`, so all three now take per-document offsets and the recipes
go back to packed batches.

**What changes**
- `get_attention_masks` returns `VarlenMetadata` from positions (reset
to 0 at each document start; padding kept as
its own segment) instead of raising. DSV4's `preprocess_inputs` (added
in #4858) also annotates the nested offsets
  for SPMD, as kimi_k3 does.
- **Compressor:** groups restart at each document, a document's trailing
partial group forms no entry, and the
ratio-4 overlap never reaches into the previous document. Entries are
packed by document into a fixed pool of
`seqlen // ratio` slots (located with `searchsorted`, gathered by
index): no host syncs, CUDA-graph capturable.
- **Indexer + all three cores** receive `cu_seqlens` / `cu_seqlens_k`,
so top-k selection, the sliding window, and
HCA's index list stay inside each document. The CSA/HCA index width is
bounded by the longest document
(`VarlenMetadata.max_k`), not the whole packed batch: extra slots were
always -1, and at the debug recipe's
16K-token microbatch the wider HCA list made the first Triton compile
take over 20 minutes.
- **Recipes:** the debug microbatch returns to `8 * max_context_length`;
`max_num_documents=1` becomes a fixed
capacity of 64 (as in llama3), which keeps the offsets static and
sync-free.

The unpacked path is kept (not expressed as a one-document packed
batch): the gather-based path is ~30% slower
for the compressor, and a one-document packed batch already matches it
bitwise.

## Results

All loss runs: DSv4 debug model, C4, 500 steps, 16,384 tokens per step,
1x GB300, `--debug.seed 42
--debug.deterministic` unless noted. Branches: main `a475ccd89`, stack
top #4932 `5e90dfef9`, this PR.

**1. No behavior change for unpacked training.** The same one-document
batches through this PR's packed path and
through the stack top give identical loss and grad_norm at every one of
500 steps (bitwise).

**2. Packing trains on real tokens instead of padding.** One-document
microbatches are 41% padding (9,722 real
tokens per 16,384-token step, 8 documents); packed steps are all real
tokens (~14 documents).

| run (loss, lower is better) | mean loss, last 50 steps | real tokens
seen |
|---|---|---|
| stack top, one document per microbatch | 2.1195 | 4.86 M |
| this PR, packed documents | **2.0106** | 8.19 M |

![Loss vs
step](https://github.com/user-attachments/assets/bcf5f80c-baa1-42eb-b5dd-16b7bd8f65cb)

**Per real token, packing costs nothing once updates are matched.** At
16,384 tokens per step the packed run
reaches the one-document run's 4.86 M real tokens in 297 updates instead
of 500, which costs loss at this model
size (a fully annealed 297-step packed run reaches 2.245, so the LR
schedule is not the cause). A packed control
at 9,728 tokens per step (the one-document run's ~9,722 real tokens per
step) takes the same 500 updates on the
same real tokens and lands on the one-document curve:

| mean train loss (lower is better) | last 25 steps | last 50 | last 100
|
|---|---|---|---|
| one document per microbatch, 16,384 tokens/step | 2.1357 | 2.1195 |
2.1295 |
| packed, 9,728 tokens/step (matched updates) | 2.1419 | 2.1225 | 2.1283
|
| difference | +0.006 | +0.003 | -0.001 |

All differences are inside the 0.0098 seed-to-seed spread.

![Loss vs real
tokens](https://github.com/user-attachments/assets/1b020921-afbe-4189-ab3f-6eb49abe5f43)

**3. The stack below (Flex -> gather_attn, #4858) does not change
convergence.** main vs stack top over 8
seeds, mean train loss over the last 100 of 500 steps (lower is better):

| seed | main (Flex) | stack (gather_attn) | Flex - gather |
|---|---|---|---|
| 42 | 2.1246 | 2.1295 | -0.0049 |
| 1 | 2.1406 | 2.1410 | -0.0004 |
| 2 | 2.1480 | 2.1490 | -0.0010 |
| 3 | 2.1529 | 2.1457 | +0.0071 |
| 4 | 2.1229 | 2.1220 | +0.0009 |
| 5 | 2.1486 | 2.1400 | +0.0086 |
| 6 | 2.1350 | 2.1328 | +0.0022 |
| 7 | 2.1233 | 2.1166 | +0.0067 |

Mean gap +0.0024, 95% CI [-0.0015, +0.0063], paired t-test p = 0.19; 3
of 8 seeds favor Flex (sign test
p = 0.73). The gap is 0.11% of the loss and about a fifth of the stack's
own seed-to-seed spread (std 0.0114), and
it does not grow over training (+0.0022, +0.0039, +0.0029, +0.0027,
+0.0024 for steps 0-100 ... 400-500). The
first three seeds leaned toward Flex by chance.

![main vs stack, 8
seeds](https://github.com/user-attachments/assets/56fddceb-4327-42fc-b4ef-b0b6a538d337)

Seed 42 alone, step by step (top), and the bitwise check from result 1
(bottom):


![Differences](https://github.com/user-attachments/assets/21288bde-ad67-4d02-be4f-e27b96dd2b02)

## Methodology

- **Loss runs:** DSv4 debug model (10.6 M params, 16 heads x head_dim
256), C4 streamed from HF, seed 42 (plus
seeds 1-7 for main vs stack), `--debug.deterministic`, 500 steps, 16,384
tokens per step, LR warmup 2 then
linear decay to 0, CUDA graphs on, one GB300 per run. "One document per
microbatch" is the #4879 recipe
(8 x 2,048-token microbatches, 41% padding); "packed" is this PR's
recipe (one 16,384-token microbatch,
`max_num_documents=64`). Only the commit and batching differ between
runs.
- **Loss** is the logged train loss: mean over non-padding tokens of
each step's own batch. Curves are EMA(0.05);
tables use means over the last N steps. Real tokens per step were
counted by building each config's dataloader
  and walking the same 500 steps.
- **Bitwise checks** compare the full-precision TensorBoard loss and
grad_norm scalars of two runs step by step.
- **Throughput runs:** all back to back inside one `gpu-run` claim (same
GPU, full clocks), without
`--debug.deterministic` (`gather_attn` uses Triton under it), median
over steps 11+. The flash-shaped model
keeps DSv4-flash attention and indexer exactly (64 heads x 512, window
128, top-k 512) with 6 layers (SWA, SWA,
CSA, HCA, CSA, HCA) and 8 experts, 4,096 context, 8,192 tokens per step,
30 steps.
- Every chart repeats its method in a footnote.

## Performance

Without `--debug.deterministic` (so CSA/HCA run on the FA4 CuTe kernel
at head_dim 512), same GPU, run
back to back, median of steps 11+ (higher is better):

| model | run | tokens/s | real tokens/s | peak reserved |
|---|---|---|---|---|
| debug (head_dim 256, Triton) | stack top, one document per microbatch
| 101,341 | 60,135 | 0.98 GiB |
| debug (head_dim 256, Triton) | this PR, packed | 234,005 | **234,005
(3.9x)** | 5.88 GiB |
| 6-layer flash-shaped (64 x 512) | stack top, one document per 4K
microbatch | 17,717 | - | 90.5 GiB |
| 6-layer flash-shaped (64 x 512) | this PR, one document per 4K
microbatch | 17,637 | - | 90.5 GiB |
| 6-layer flash-shaped (64 x 512) | this PR, packed 8K microbatch |
19,614 | - | 106.6 GiB |

The packed path costs nothing when a batch holds one document (rows
3-4). The flash-shaped packed row uses an 8K
microbatch (vs 4K x 2 accumulation), which also explains its higher
memory. The debug model runs Triton everywhere:
attn-gym's CuTe backend needs head_dim 512, and `gather_attn` uses
Triton under `--debug.deterministic`, under
`torch.compile`, and for SWA's empty compressed pool.


![Throughput](https://github.com/user-attachments/assets/f1bc57e3-a1d9-40a5-be03-305602db9cc7)

## Test Plan

Unit tests replace #4879's rejection tests: document offsets with and
without padding; offsets reaching the model
through `preprocess_inputs`; and, on CPU fp64, a packed batch through
SWA, CSA, and HCA matching each document run
alone (partial groups and a 5-token document included). Removing the
document-start overlap mask fails the CSA
cases. CSA selects every causal candidate in this test because top-k
ties between exact-zero indexer scores are
broken by layout, and can differ packed vs unpacked.

GPU checks on GB300 (flash-shaped layers, bf16) with deterministic
algorithms: forward+backward runs under
`sync_debug_mode="error"`; a CUDA graph captured once and replayed on
new documents matches eager bitwise; a
one-document packed batch matches the unpacked path bitwise. Packed vs
per-document runs of the debug model and
the flash-shaped layers (CuTe) agree within bf16 tolerance.

```bash
pytest tests/unit_tests/cpu/test_deepseek_v4_dsa.py tests/unit_tests/cpu/test_deepseek_v4_compressor.py \
  tests/unit_tests/cpu/test_deepseek_v4_mtp.py tests/unit_tests/cpu/test_deepseek_v4_flops.py \
  tests/unit_tests/cpu/test_debug_config_defaults.py tests/unit_tests/gpu/test_deepseek_v4_attention.py
# E2E loss runs (per branch): C4, 16384 tokens/step, 500 steps
torchrun --nproc_per_node=1 -m torchtitan.train --module deepseek_v4 --config deepseek_v4_debugmodel \
  --training.steps 500 --debug.seed 42 --debug.deterministic  # C4 + TensorBoard overrides
```

Scripts, raw per-step data (CSV), and the chart generator were kept
outside the repo; available on request.

* Remove torchcomms dependency (#4941)

Torchcomms is not strictly required to run Torch Titan therefore
completely remove it as a dependency. Torchcomms is currently one of the
backend options in TorchFT and in Torchstore. Both the libraries allow
using different backends so if somebody does not want to use torchcomms,
the dependency on torchcomms is unecessary. This makes users responsible
to install the backend that they need.

<!-- forkstack:stack:start -->
---
Stack (top to bottom):
-  #4945 [rl] Stage generator weights in CPU memory
- -> #4941 Remove torchcomms dependency
---
<!-- forkstack:stack:end -->

Co-authored-by: Tushar Jain <[email protected]>

* [rl] generator: one trace span per engine-step burst (#4975)

Logging on engine.step is too much. Lets do it on the burst only.

two reasons:
1) Today our logging is slow on NFS (0.5ms per call), which doesn't
matter in training, but matters for engine.step. Peng is working on
putting logging in a background thread, so this is not a problem
anymore. This PR is a quick fix

2) Our logger output is very large for the generator. This should reduce
it significantly.

A couple of notes:
- This was done with another PR that avoid unnecessary tokenization
https://github.com/pytorch/torchtitan/pull/4976
- I have no clue why bs64 would benefit from thism ore than bs1

I didn't remeasure it, but in any case, the change is good.

## Result
- GB300, Qwen3.5-4B, logs on NFS: 
  ```
  bs64   3937 -> 9950 tok/s (2.5x), TPOT 14.1 -> 5.72 ms
  bs1     258 ->  288 tok/s (+12%)
  ```

Co-authored-by: Felipe Mello <[email protected]>

* [graph_trainer] Remove legacy AOT export helpers in graph_utils.py (#4979)

## Why

`graph_utils.py` holds the old AOT export path: `export_joint`,
`aot_export_joint_with_descriptors_alone`, `joint_graph_builder` and
`CompiledModule`. Compile mode is now only `aot_fx_trace`, so
GraphTrainer no longer uses any of it. The only importer left was
`TestReassignCollectivePgsPass` in `tests/test_passes.py`, and that test
was checking the pass on a graph from a tracer GraphTrainer no longer
uses.

This is the first step in simplifying GraphTrainer after the
GraphRuntime refactor.

## What

- Delete `graph_utils.py`.
- Port `TestReassignCollectivePgsPass` to trace the joint fwd+bwd graph
with `minimal_fx_tracer`, the tracer GraphTrainer uses. All three
overlap tests are kept.
- Remove the mentions of `graph_utils.py` from
`autoresearch/autoresearch.md`.

## Testing

```
pytest torchtitan/experiments/graph_trainer/tests/test_passes.py
182 passed, 1 skipped
```

The training code path is unchanged: this removes dead code and updates
a test, so no loss comparison is needed.

* Reorganize training recipes (#4913)

Human notes
- move model flavors definition from `__init__.py` to `flavors.py`, to
keep the former clean
- rename `model_registry` to `build_model_config` because we are not
registering anything in the function
- move `config_registry.py` recipes to torchtitan_recipes, with
unverified / inactive ones removed; the RL ones are all kept
- reorganize torchtitan_recipes and the tests subfolder, to be
consistent with the "models vs. rl vs. experiments" structure
- move `overrides/` modules into torchtitan_recipes, while keeping the
.md in core
- remove `_supported_experiments` and `_supported_models` shortcuts
- removed unused functions e.g. `dist_mean`,
`check_if_feature_in_pytorch`

## Summary

- move verified training recipes into the top-level `torchtitan_recipes`
package and keep CI-only configurations under `torchtitan_recipes.tests`
- organize recipes by model, subsystem, and test suite; consolidate
duplicate Flux and Transformers test recipe modules
- move bundled overrides out of the core library and remove unused or
unverified configurations and helpers
- move model flavor definitions to `flavors.py` and expose the uniform
`MODEL_FLAVORS` / `build_model_config` API

## Testing

- `pre-commit run --all-files`
- focused CPU configuration, model, recipe, and state-dict tests (193
passed)

* remove timeout and fix assertion (#4974)

* [Perf][Compile] Add local compilation for gated RMSNorm and loss functions (#4894)

## Summary

- Compile the shared gated RMSNorm with TorchInductor by default for
Kimi K3 and Qwen3.5.
- Preserve Kimi sigmoid gating and Qwen3.5 SiLU gating in one FP32
implementation.
- Add a function-scoped local compile API shared by gated RMSNorm and
opt-in loss compilation.
- Fall back to eager gated RMSNorm in batch-invariant mode.

Stacked on #4895. This follows up on
https://github.com/pytorch/torchtitan/pull/4832.

## Single-operator performance

### Kimi K3 gated RMSNorm

One H100 with BF16 inputs, 20 warmup iterations, 100 timed iterations
per trial, five trials, and synchronized CUDA events. Values are median
trial averages. All measurements are forward+backward and include input,
gate, and weight gradients.

Operation tested: `RMSNorm(x.float(), weight.float(), eps) *
sigmoid(gate.float())`, cast back to BF16.

Shapes use `[T, H, V]`, where `T` is the packed-token dimension, `H` is
the number of rank-local value heads, and `V` is the value-head
dimension (128 here). The handwritten Triton implementation is the
previous Kimi K3 kernel from #4832 and is used only for comparison; it
is not included in this PR.

| Shape `[T, H, V]` | Eager | Handwritten Triton | Compiled | Compiled
vs eager | Compiled vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: |
| `[2048, 16, 128]` | 346.84 us | 233.26 us | 172.07 us | **2.02x** |
**1.36x** |
| `[2048, 32, 128]` | 728.17 us | 245.18 us | 214.75 us | **3.39x** |
**1.14x** |
| `[4096, 12, 128]` | 542.46 us | 247.37 us | 243.17 us | **2.23x** |
**1.02x** |
| `[4096, 96, 128]` | 3,089.36 us | 972.49 us | 406.30 us | **7.60x** |
**2.39x** |
| `[8192, 12, 128]` | 824.82 us | 249.14 us | 223.32 us | **3.69x** |
**1.12x** |
| `[8192, 24, 128]` | 1,592.17 us | 438.95 us | 219.84 us | **7.24x** |
**2.00x** |
| `[8192, 48, 128]` | 3,088.79 us | 973.62 us | 404.70 us | **7.63x** |
**2.41x** |
| `[8192, 96, 128]` | 6,094.38 us | Compilation failure | 788.54 us |
**7.73x** | N/A |
| `[16384, 12, 128]` | 1,592.23 us | 439.85 us | 224.74 us | **7.08x** |
**1.96x** |
| `[16384, 24, 128]` | 3,091.79 us | 976.80 us | 406.68 us | **7.60x** |
**2.40x** |
| `[16384, 48, 128]` | 6,095.45 us | Compilation failure | 786.84 us |
**7.75x** | N/A |
| `[16384, 96, 128]` | 12,100.33 us | Compilation failure | 1,552.79 us
| **7.79x** | N/A |
| `[32768, 12, 128]` | 3,090.03 us | 977.90 us | 406.19 us | **7.61x** |
**2.41x** |
| `[32768, 24, 128]` | 6,094.32 us | Compilation failure | 788.40 us |
**7.73x** | N/A |
| `[65536, 12, 128]` | 6,094.23 us | Compilation failure | 788.41 us |
**7.73x** | N/A |

The compiled implementation is 2.02x-7.79x faster than eager and
1.02x-2.41x faster than handwritten Triton for every shape where the
handwritten kernel compiles. The handwritten weight-gradient reduction
exceeds Triton's maximum tensor size for the five largest row counts.

### Loss functions

One H100 with BF16 inputs, 20 warmup iterations, 100 timed iterations
per trial, five trials, and synchronized CUDA events. Values are median
trial averages. Measurements include forward and input-gradient
backward.

Operations tested:

- Cross entropy: `cross_entropy(logits.float(), labels, reduction="sum",
ignore_index=-100)` on the single-GPU, non-vocab-parallel path.
- MSE: `mse_loss(pred.float(), target.float().detach(),
reduction="sum")`.

| Operation | Input shape | Eager | Compiled | Speedup | Numerical check
|
| --- | --- | ---: | ---: | ---: | --- |
| Cross entropy | logits `[2048, 8192]`, labels `[2048]` | 340.41 us |
169.29 us | **2.01x** | `assert_close`; output max diff 0.001953125,
grad max diff 0.00000190735 |
| MSE | prediction and target `[4096, 4096]` | 438.61 us | 154.33 us |
**2.84x** | Bitwise-equal output and input gradient |

### Determinism and batch invariance

| Compiled target | Fwd+bwd deterministic | Batch invariant |
| --- | --- | --- |
| Kimi sigmoid gated RMSNorm | Yes | No (backward `grad_weight` max
diff: 0.00000858307; forward output and backward `grad_x`/`grad_gate`
max diffs: 0) |
| Qwen3.5 SiLU gated RMSNorm | Yes | No (backward `grad_weight` max
diff: 0.00000953674; forward output and backward `grad_x`/`grad_gate`
max diffs: 0) |
| Cross entropy (`none`) | Yes | Yes (output and logits-gradient max
diffs: 0) |
| Cross entropy (`sum`) | Yes | No (forward loss max diff:
0.00048828125; backward logits-gradient max diff: 0) |
| MSE (`sum`) | Yes | No (forward loss max diff: 0.25; backward
prediction-gradient max diff: 0) |

These isolated operator results do not claim an end-to-end training
speedup.

## Testing

- CPU local compile, gated RMSNorm, loss, config, and RL trainer tests:
93 passed, 9 subtests passed
- GPU gated RMSNorm codegen, grouped linear compile, Kimi KDA, and
Qwen3.5 DeltaNet tests: 10 passed
- Compiled cross-entropy and MSE loss forward+backward correctness and
performance tests passed on H100
- Pre-commit passed with Pyrefly and link checking skipped

* [rl] Default the inter-generator router to sticky sessions (#4986)

The inter-generator router defaulted to least-loaded, so the turns of
one multi-turn rollout landed on different generators and missed each
other's prefix KV (Qwen3.5-27B agentic run, 12 generators: ~35%
prefix-cache hit rate at 12-17% KV usage). Default to
`StickySessionRoutingStrategy` (new sessions still go to the
least-loaded generator), like the intra-generator router already does,
and drop the per-recipe strategy overrides so every recipe uses sticky.

* [rl] generator: token-in/token-out sampling (#4976)

TLDR: 
vllm detokenizes because users may do "stop_condition" based on some
string.
We dont expose this today, so its a waste in a generator

-----

## Problem
The generator's engine loop runs inline with vLLM's engine core
(`external_launcher` keeps it in-process), so vLLM's per-token output
processing sits on the same thread that launches the next step. vLLM
detokenizes every generated token and builds a `{token_id: Logprob}`
dict per token per request. The generator never reads text (stops are
token ids), and it keeps only the sampled token's logprob float.

## Solution
`SamplingParams(detokenize=False, flat_logprobs=True)`, and read the
logprob floats straight from `FlatLogprobs`. verl does the same
(`detokenize=False` unless stop strings are set). NeMo-RL instead turns
off tokenizer loading engine-wide (`skip_tokenizer_init`).

Outputs are unchanged. `detokenize` only switches off vLLM's output-side
text decoding (stops and EOS are checked in the engine core), and vLLM
stores the sampled token first at each position. Checked on GPU: same
prompts and seed, 64/64 requests with identical token ids and
bit-identical logprobs.

Alternatives considered:
- **`skip_tokenizer_init=True` engine-wide.** Same gain, but a larger
blast radius: `render_cmpl`, the multimodal processor, EOS defaults, and
any future text feature.
- **Engine core in its own process**, vLLM's own design. It needs weight
sync to stop reaching into the in-process model.

## Result
**Short version:** this PR removes ~75% of vLLM's CPU work per engine
step and almost all garbage-collection pauses. On H100 with current main
that is worth 0-2% tokens/s. The engine step is 4-13x longer than that
CPU work, and vLLM runs the CPU work while the GPU computes the next
step (async scheduling), so most of it was already hidden.

Tokens/s, generator only (real `VLLMGenerator`, H100, fixed-length
outputs, before/after interleaved in one process, median of 6 reps; 3
for 2048 out):
```
                               before         after          gain
4B   bs64,  1024 in,  512 out   3.47k tok/s    3.45k tok/s    none (noise ±1%)
4B   bs256,  512 in,  256 out   5.83k tok/s    5.85k tok/s    none (noise ±1%)
4B   bs128,  512 in, 2048 out   4.67k tok/s    4.72k tok/s    +1% (all 3 reps)
0.6B bs256,  512 in,  256 out   12.2k tok/s    12.4k tok/s    +1.5% (noisy, sd 1.9%)
```
GB300, Qwen3.5-4B, all other generator PRs stacked (~5.6 ms engine
step), `detokenize=False` alone (no `flat_logprobs`), one measurement:
```
bs64,  1024 in,  512 out   9.88k tok/s -> 10.14k tok/s   +2.6%
```
Where the time goes (H100):
```
                               engine step   CPU output work / step   GC pauses / batch
4B   bs64,  1024 in,  512 out   17 ms         1.35 -> 0.33 ms          17 -> 1 ms
4B   bs256,  512 in,  256 out   34 ms         4.41 -> 1.15 ms          108 -> 5 ms
4B   bs128,  512 in, 2048 out   26 ms         3.29 -> 0.77 ms          799 -> 3 ms
0.6B bs256,  512 in,  256 out   16 ms         3.86 -> 1.06 ms          109 -> 5 ms
```
- `detokenize=False` is most of the CPU saving (4B bs256: 4.41 -> 1.35
ms per step).
- `flat_logprobs=True` is the GC saving. One Python dict per generated
token made the garbage collector run 7 full collections per batch at
2048-token outputs; flat lists make it 0. That is the +1% at 2048 out,
and it should grow with longer outputs.

NOTE: DAPO-Math 4B 8k end to end on H100 (50 steps, 6 generators) showed
no measurable change.

Tests: the generator unit tests pass with `FlatLogprobs` in the fake
request outputs, and assert the new sampling params.

* [Perf][Compile] Add local compilation for OffsetRMSNorm (#4928)

## Summary

- Add an `offset_rmsnorm` local-compile target for Qwen3.5-compatible
models and enable it by default.
- Compile the existing FP32 OffsetRMSNorm expression with TorchInductor
while preserving the eager implementation and state dict.
- Fall back to eager in batch-invariant mode; the existing Triton
override remains available.

The default compile configuration enables both normalization targets:

```python
CompileConfig(local_compile=["gated_rmsnorm", "offset_rmsnorm"])
```

Stacked on #4894. The handwritten Triton comparison uses the override
from #4417.

## Single-operator performance

One H100 with BF16 inputs, 20 warmup iterations, 100 timed iterations
per trial, five trials, and synchronized CUDA events. Values are median
trial averages. Each measurement runs OffsetRMSNorm forward+backward and
includes input and weight gradients.

`[T, H, K]` represents Q/K normalization and `[T, D]` represents
transformer-block/final normalization. `T` is the packed-token
dimension, `H` is the number of rank-local heads, `K` is the head
dimension, and `D` is the model dimension.

### Q/K normalization

| Shape `[T, H, K]` | Eager | Handwritten Triton | Local compile | Local
compile vs eager | Local compile vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: |
| `[2048, 2, 256]` | 313.58 us | 219.49 us | 160.53 us | **1.95x** |
**1.37x** |
| `[2048, 12, 256]` | 453.85 us | 249.55 us | 195.39 us | **2.32x** |
**1.28x** |
| `[4096, 2, 256]` | 302.94 us | 230.75 us | 165.11 us | **1.83x** |
**1.40x** |
| `[4096, 12, 256]` | 1,007.96 us | 233.84 us | 204.22 us | **4.94x** |
**1.15x** |
| `[8192, 2, 256]` | 306.46 us | 237.97 us | 162.37 us | **1.89x** |
**1.47x** |
| `[8192, 12, 256]` | 1,927.70 us | 281.30 us | 204.86 us | **9.41x** |
**1.37x** |
| `[16384, 2, 256]` | 638.66 us | 238.48 us | 211.81 us | **3.02x** |
**1.13x** |
| `[16384, 12, 256]` | 3,653.61 us | 473.79 us | 251.77 us | **14.51x**
| **1.88x** |

### Transformer-block/final normalization

| Shape `[T, D]` | Eager | Handwritten Triton | Local compile | Local
compile vs eager | Local compile vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: |
| `[2048, 1024]` | 301.50 us | 232.64 us | 165.14 us | **1.83x** |
**1.41x** |
| `[2048, 2048]` | 303.49 us | 235.76 us | 168.55 us | **1.80x** |
**1.40x** |
| `[2048, 2560]` | 374.40 us | 235.71 us | 162.36 us | **2.31x** |
**1.45x** |
| `[2048, 4096]` | 631.91 us | 242.07 us | 162.85 us | **3.88x** |
**1.49x** |
| `[2048, 5120]` | 822.58 us | 249.33 us | 161.20 us | **5.10x** |
**1.55x** |
| `[4096, 1024]` | 298.79 us | 271.44 us | 196.35 us | **1.52x** |
**1.38x** |
| `[4096, 2048]` | 622.85 us | 233.16 us | 196.25 us | **3.17x** |
**1.19x** |
| `[4096, 2560]` | 812.56 us | 240.31 us | 186.85 us | **4.35x** |
**1.29x** |
| `[4096, 4096]` | 1,282.33 us | 275.66 us | 211.94 us | **6.05x** |
**1.30x** |
| `[4096, 5120]` | 1,571.87 us | 287.10 us | 186.61 us | **8.42x** |
**1.54x** |
| `[8192, 1024]` | 622.00 us | 244.76 us | 196.14 us | **3.17x** |
**1.25x** |
| `[8192, 2048]` | 1,277.67 us | 240.85 us | 194.41 us | **6.57x** |
**1.24x** |
| `[8192, 2560]` | 1,568.81 us | 251.18 us | 203.89 us | **7.69x** |
**1.23x** |
| `[8192, 3584]` | 2,136.69 us | 226.28 us | 194.45 us | **10.99x** |
**1.16x** |
| `[8192, 4096]` | 2,429.91 us | 236.55 us | 203.66 us | **11.93x** |
**1.16x** |
| `[8192, 4864]` | 2,851.04 us | 281.80 us | 293.99 us | **9.70x** |
**0.96x** |
| `[8192, 5120]` | 2,994.64 us | 293.76 us | 308.83 us | **9.70x** |
**0.95x** |
| `[8192, 7168]` | 4,134.76 us | 397.10 us | 415.27 us | **9.96x** |
**0.96x** |
| `[8192, 8192]` | 4,693.66 us | 451.78 us | 492.81 us | **9.52x** |
**0.92x** |

Local compile is faster than eager for every tested shape and faster
than handwritten Triton for 23 of 27 shapes. Handwritten Triton is
faster at four large-width shapes, so performance is shape-dependent and
the handwritten Triton override remains useful. A `Local compile vs
Triton` value below `1.0x` indicates that Triton is faster.

These isolated operator results do not claim an end-to-end training
speedup.

## Testing

- Local-compile codegen emits Triton for OffsetRMSNorm forward and
backward.
- Compiled forward, input gradient, and weight gradient match the eager
FP32 reference.
- A two-GPU TP test verifies the compiled Q/K norm inside its local SPMD
boundary.
- Relevant CPU/GPU tests: 19 passed, 9 subtests passed.
- All enabled pre-commit hooks passed; Pyrefly was skipped because of
unrelated environment errors.

* [2/2] [graph_trainer] PP=1 GA schedule with FSDP overlap (#4927)

Before:

If we extract UNSHARD and REDUCE_GRAD in a separate schedule action and
bucket all collectives - we lose overlap, this collectives will be
exposed.

Addition:
1. Overlap of UNSHARD and REDUCE_GRAD
Add option to preserve overlap of UNSAHRD (fsdp allgathers) and
REDUCE_GRAD(fsdp reduce_scatters) in first and last microbatch.

We result in schedule
FWD_BWD_WITH_UNSHARD, ... FWD_BWD x (num_micro_batches - 2) ...
FWD_BWD_WITH_REDUCE_GRAD

The split of fsdp collectives is done BEFORE bucketing.
This significantly simplifies split_fsdp passes.

We prepare:
1.Get FULL_FWD_BWD(nobucket) by tracing, bucketing extracted from passes
and deferred to later(FULL in the name means that we have FSDP
collectives inside)
2.  FULL_FWD_BWD(nobucket) extract only REDUCE_GRAD 
    -> get FWD_BWD_WITH_UNSHARD
    -> apply bucketing for AG only
3. 2.  FULL_FWD_BWD(nobucket) extract only UNSHARD 
    -> get FWD_BWD_WITH_REDUCE_GRAD
    -> apply bucketing for RS only
applying bucketing for AG o RS separately is seamless, current algorithm
supports missing of some types of collectives.
4. FULL_FWD_BWD -> extract both get FWD_BWD middle graph that will be
reused multiple times.

Gradient Accumulation:

For FWD_BWD_WITH_UNSHARD we add unsharded gradients into outputs
(graph_pass in grad_accumulation). They are becoming our gradient
accumulators.

For FWD_BWD we add unsharded gradients as inputs and add add_ or wgrad
fused add_ (optional under config) for gradient accumulations into
gradient accumulators passed as inputs.

For FWD_BWD_WITH_REDUCE_GRAD we add add_/wgrad fused add_ before
reduce_grads (as a pass).


2. Gradent Accumulation Ingraph Inplace

Gradient accumulation for PP=1 becomes ingraph by default. First
FWD_BWD_WITH_UNSHARD produces gradient_accumulators and returns as
outputs. (unsharded param gradients)

gradient_accumulators are fed into "middle" batches, where unsharded
gradients are inplace (or fused in wgrad producer) accumulated inside
accumulators.

The last stage FWD_BWD_WITH_REDUCE_GRAD accumulates grads in
gradient_accumulators and then does overlapped reduce_grad and returns
sharded gradients.


4. GA currently is implemented via graph passes to avoid retracing and
compile time overhead.
All gradient accumulation parts are extracted into
torchtitan/experiments/graph_trainer/grad_accumulation.py

WGrad fusion functionality stays in wgrad_accumulation.

6. Testing: GB300 x 3 EP4 FSDP4
Interesting that separate UNSHARD and REDUCE_GRAD with all bucketed
collectives was faster than overlaped case:
29 -> 31 MFU for DSv3 16b GA

But expectation is that when FSDP will include non nvlink domain -
overlap should be beneficial.

This is the reason why I want to keep both paths.

* [graph_trainer] Resolve one GraphExecutionPlan for PP=1 and PP>1 (#4980)

Stacked on `graph-trainer-pp1-ga-fsdp-overlap`.

## Why

A single FSDP placement choice currently passes through several
representations: config strings -> `GraphRuntimeFSDPPolicy` ->
`PP1FwdBwdPlan` properties. The validation is spread across
`resolve_graph_runtime_fsdp_policy`,
`resolve_graph_runtime_gradient_accumulation_policy`,
`_resolve_pp1_fwd_bwd_plan`, `_make_spmd_graph_runtime` and both graph
builders. PP>1 gets no plan at all. Its provider receives two loose
`extract_*` booleans next to an optional PP=1 plan.

This PR resolves everything once, into one object shared by PP=1 and
PP>1.

## What

- `PP1FwdBwdPlan` becomes `GraphExecutionPlan` and gains a `pp_enabled`
field. PP>1 uses the same plan: both boundaries are `"schedule"`, or
`None` without FSDP.
- `resolve_graph_execution_plan()` replaces the three resolve functions
and the two policy dataclasses.
- Config modes map to placements through lookup tables. `auto` is
handled in one place.
  - WGrad-fusion resolution returns a plain bool.
- Every placement-related check now runs during plan resolution:
  - the PP>1 config checks (`_validate_graph_pp_config`);
- the SPMD extraction support checks, moved out of
`_make_spmd_graph_runtime` into
`_validate_spmd_graph_extraction_support`;
- the dense-region-overlap check. It was duplicated in
`_build_fwd_bwd_graphs` and `_build_stage_graphs`, and it only fired
after tracing.
- `GraphTrainerStageGraphProvider` takes `plan` only. The `pp1_plan`,
`extract_fsdp_param_unshard` and `extract_fsdp_grad_reduction` fields
are gone. The factory layers forward `plan` instead of `fsdp_policy` and
`gradient_accumulation_policy`.
- The `num_microbatches < 1` check is removed.

This is intended as a pure refactor. The resolved placements, schedules
and error messages are unchanged. The one exception: the two
dense-region messages are now a single message.

## Testing

- `test_graph_pp_runner.py`: all 53 tests pass. The tests are ported to
`resolve_graph_execution_plan`. The dense-region test now covers PP=1
and PP>1, and there is a new PP>1 placement test.
- `pre-commit`: passes, except pyrefly, which already fails on
missing-import errors unrelated to this PR.
- The rest of the graph_trainer suite fails the same 24 GPU tests with
and without this PR. The failures come from this machine: a
`/tmp/seed_training.log` permission error and an Inductor config key the
local PyTorch build doesn't support.
- Not run yet: a bitwise loss comparison with `scripts/loss_compare.py`.

* [graph_trainer] Always enable graph pass instrumentation (#4977)

## Summary

Removes the `compile.debug_graph_passes` flag from
`GraphTrainerCompileConfig`. The per-pass instrumentation that used to
sit behind it now always runs in `apply_graph_passes`:

- the graph is dumped to tlparse before and after each pass
- each pass's wall-clock time is logged
- each pass's op-count / node-count diff is logged

## Why

This information is what you want whenever you're looking at a
GraphTrainer compile, and having to re-run with a flag to get it is
friction. Keeping it always on costs very little:

- The tlparse dumps go through `trace_structured` with a lazy
`payload_fn`, so the graph is only printed when `TORCH_TRACE` is set.
- `snapshot_graph` is a single O(num_nodes) walk per pass, which is
negligible next to tracing and compilation.

The visible change is more log output: each compile prints one timing
line and one diff block per pass on the logging rank.

## Changes

- `configs.py`: drop `debug_graph_passes`.
- `passes.py`: remove the `debug` gating in `apply_graph_passes`.
- `debug_utils.py`: drop the `debug` parameter from
`tlparse_log_graph_pass` (`apply_graph_passes` was its only caller).
`seq_nr` is now always included in the printed node metadata.
- `graph_trainer/.claude/CLAUDE.md`: update the "Debugging Graph Passes"
section.

Recipes or CLI invocations that set `compile.debug_graph_passes` will
need to drop it.

## Testing

- `pytest torchtitan/experiments/graph_trainer/tests/test_passes.py`:
182 passed, 1 skipped.
- Numerics are unaffected: only logging and tlparse dumps changed, and
no pass behavior changed.

* [MoE] Annotate routed-expert weights on the dense mesh when EP is off (#4973)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* __->__ #4973

Issue: any MoE model with EP=1 on more than one rank (FSDP/HSDP/CP-only,
since MoE requires EP >= TP) crashed in core FSDP:

    ValueError: When dp_mesh_dims is provided, all parameters must be
DTensors on the full SPMD mesh ... Got plain tensor for parameter
'weight'.

Why: without EP, `_routed_experts_sharding_configs` set the routed
`w13`/`w2`
sharding configs to `None`, so expert weights never got spmd_types
annotations and stayed plain tensors, which FSDP rejects once
`dp_mesh_dims` is set.

Fix: give them the dense param placement (Replicate on DP/CP/TP) when EP
is
off, so FSDP shards them on the dense mesh like other dense params. EP
configs are unchanged, and on a single rank the annotations are filtered
out,
so existing numerics/gold losses (all EP > 1) are unaffected. Callsites:
- gpt_oss: expert biases now always follow their weight's placement
  (previously only annotated under EP, so they would also stay plain).
- Grouped LoRA: accept the dense placement too. The configs are always
set
  now, so keeping the EP-only check would reject every EP=1 LoRA run.

Test Plan (8x H100, EP=1, TP=1, 3 steps; all crashed or would crash
before):
- FSDP=8: qwen3_moe_debug, gpt_oss_debugmodel, deepseek_v3_debugmodel,
  deepseek_v4_debugmodel, kimi_k3_debugmodel
- FSDP=4, PP=2: qwen35_debugmodel_moe, qwen35_debugmodel_moe_float8_lora
- HSDP 2x4: qwen3_moe_debug
- FSDP=2, CP=2, PP=2: deepseek_v3_debugmodel_fsdp2_cp2_pp2_ep4 (EP=1)
- EP path sanity: qwen3_moe_debug FSDP=4, TP=2, EP=2
- CPU: test_moe.py, test_lora.py, test_qwen3_5.py (no new failures)

Follow-up (waits for #4949 to land): graph_trainer simple FSDP's non-EP
path shards the stacked W13 expert weight on dim 2 while core shards
routed
experts on dim 0, so graph_trainer qwen3 MoE EP=1 diverges from eager at
step 1. That fix needs #4949's `param_shard_placements` argument.

* [graph_trainer] Pass one config through GraphRuntime construction (#4983)

Stacked on #4980.

## Why
GraphRuntime construction threaded `compile_config`, `model_config`,
`parallelism` and `trainer_config` side by side. On PP=1 the first three
are always `trainer_config.compile` / `.model` / `.parallelism`, so they
were pure duplication. PP>1 enters through core's generic
`model.pipeline(**kwargs)` API and only has the decomposed fields, which
is why both shapes existed.

## What
- `make_graph_runtime`, `_register_graph_runtime`,
`_make_pipeline_parallel_graph_runtime`,
`GraphTrainerStageGraphProvider`, `_build_stage_graphs` and
`_apply_graph_pp_pre_partition_or_extraction_passes` take a single
`config: GraphTrainer.Config | GraphTrainerConfigView`.
- `_GraphTrainerPassConfigView` is renamed to `GraphTrainerConfigView`
(`compile`, `parallelism`, `model`) and is built once in
`graph_pipeline_llm`. Core's pipelining API is unchanged.
- PP=1-only builders (`make_spmd_graph_runtime`,
`_make_spmd_graph_runtime`, `_build_fwd_bwd_graphs`,
`_build_scheduled_fwd_bwd_graphs`, `_extract_fwd_bwd_action_graphs`)
take only `trainer_config`; the `trainer.py` call drops three arguments.
- The provider selects the PP=1 vs PP>1 path from `plan.pp_enabled`
instead of `trainer_config is not None`.
- Removed the "model_config and parallelism required when passes are
enabled" ValueError; the view makes those fields required.

Helpers that only need compile settings (`apply_graph_passes`,
`_compile_graph_pp_module`, scheduling/compile helpers) still take
`compile_config`.

No behavior change intended; this is a pure plumbing refactor.

## Test plan
- `pytest
torchtitan/experiments/graph_trainer/tests/test_graph_pp_runner.py
torchtitan/experiments/graph_trainer/tests/test_trace_module.py`: 111
passed, 3 skipped
- `pre-commit` clean on changed files; pyrefly reports no errors in
changed files

* [Perf][Compile] Add local compilation for SwiGLU (#4931)

## Summary

- Enable the `swiglu` local-compile target by default for the shared
torch-native SwiGLU activation.
- Fuse SiLU and multiplication in TorchInductor-generated forward and
backward kernels.
- Keep the handwritten Triton override for sparse fixed-capacity expert
buffers.

`LocalCompileConfig()` enables SwiGLU local compile by default.

Stacked on #4928.

## Performance

One H100 with BF16 inputs, 20 warmup iterations, 100 timed
forward+backward iterations per trial, five trials, and synchronized
CUDA events. Values are median trial averages and include gate and up
gradients.

`T` is the token-row count, `R` is grouped-expert buffer capacity, `F`
is the SwiGLU hidden width, and `R_valid = offsets[-1]`. A speedup above
`1.0x` means local compile is faster.

### DeepSeek V3 training shapes

`T = 65,536` comes from four 16,384-token sequences per DP rank.
Balanced routed-expert rows are `R_valid = T * top_k / EP`: 49,152 for
16B EP8 and 262,144 for 671B EP2. Hidden widths come from the model
flavors.

| Workload | Shape `[T/R, F]` | `R_valid` | Eager | Triton | Local
compile | Speedup vs eager | Speedup vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| 16B dense FFN | `[65536, 10944]` | N/A | 8.90 ms | 5.48 ms | 5.09 ms |
**1.75x** | **1.08x** |
| 236B dense FFN | `[65536, 12288]` | N/A | 9.99 ms | 6.01 ms | 5.72 ms
| **1.75x** | **1.05x** |
| 671B dense FFN | `[65536, 18432]` | N/A | 15.00 ms | 8.81 ms | 8.58 ms
| **1.75x** | **1.03x** |
| 16B shared experts | `[65536, 2816]` | N/A | 2.31 ms | 1.36 ms | 1.32
ms | **1.75x** | **1.03x** |
| 236B shared experts | `[65536, 3072]` | N/A | 2.52 ms | 1.46 ms | 1.44
ms | **1.75x** | **1.01x** |
| 671B shared expert | `[65536, 2048]` | N/A | 1.68 ms | 0.97 ms | 0.96
ms | **1.75x** | **1.01x** |
| 16B routed experts, EP8 compact | `[49152, 1408]` | 49,152 | 0.88 ms |
0.51 ms | 0.51 ms | **1.72x** | **0.99x** |
| 671B routed experts, EP2 compact | `[262144, 2048]` | 262,144 | 6.67
ms | 3.85 ms | 3.89 ms | **1.71x** | **0.99x** |
| 671B HybridEP CF=1, 25% utilized | `[1048576, 2048]` | 262,144 | 26.65
ms | 4.07 ms | 15.46 ms | **1.72x** | **0.26x** |

### Grouped-buffer utilization crossover

Local compile evaluates the full buffer, while handwritten Triton reads
`R_valid` on the GPU and skips padded tiles.

| Buffer `[R, F]` | `R_valid` | Utilization | Triton | Local compile |
Speedup vs Triton |
| --- | ---: | ---: | ---: | ---: | ---: |
| `[32768, 2048]` | 8,192 | 25% | 183.49 us | 485.85 us | **0.38x** |
| `[32768, 2048]` | 16,384 | 50% | 251.80 us | 486.28 us | **0.52x** |
| `[32768, 2048]` | 24,576 | 75% | 371.20 us | 485.72 us | **0.76x** |
| `[32768, 2048]` | 32,768 | 100% | 491.07 us | 486.16 us | **1.01x** |

For DeepSeek V3 shapes, local compile is 1.71-1.75x faster than eager.
It is 1.01-1.08x faster than Triton for dense/shared activations and
within about 1% for compact routed experts. Small shapes can regress
versus eager (for example, `[2048, 1792]` measured 0.51x), but the
representative DeepSeek V3 training shapes support enabling the target
by default.

The Triton override remains valuable for sparse fixed-capacity buffers:
it is 3.80x faster for the 25%-utilized 671B HybridEP case. A tensor
mask would still scan the full buffer, while reading `R_valid` on the
host would add synchronization. These are isolated operator
measurements, not end-to-end training results.

## Numerics

BF16 results on one H100:

| Case | Repeated fwd+bwd deterministic | Batch invariant | Maximum
output/gradient difference |
| --- | --- | --- | ---: |
| Dense `[8192, 3584]` | Yes | Yes, full batch vs two half-batches | 0 |
| Grouped `[32768, 2048]`, `R_valid = 8192` | Yes | Yes, fixed-capacity
vs compact valid rows | 0 |

The compiled output, `grad_gate`, and `grad_up` are bitwise identical in
all comparisons.

## Testing

- Inductor emits Triton code for SwiGLU forward and backward.
- Relevant CPU/GPU tests: 27 passed.
- All enabled pre-commit hooks passed; Pyrefly was skipped because of
unrelated environment errors.

* [RL] Preserve per-group KV cache across policy updates (#4761)

## Why

A policy update changes the model weights but does not automatically
invalidate vLLM's cached KV. Letting a newly started rollout hit KV
created by an older policy would give it stale prefix state. Clearing
the entire cache prevents that reuse, but it also preempts every active
request and makes long-running, multi-turn rollouts prefill their
accumulated context again. This change supports two explicit KV-cache
lifecycle modes.

### Mode 1: preserve version-salted KV (default)

With `generator.reset_kv_cache_on_weight_sync=false`:

1. When a generator first admits a rollout (a routing session), rank 0
pins the rollout to the generator's installed policy version. Every
later turn of that rollout on the same generator reuses the pin, and the
generator passes it to vLLM as `cache_salt`.
2. A weight pull runs between `engine.step()` bursts. No request is
admitted or advanced while the new weights are being installed, but
existing requests and their KV blocks remain in vLLM.
3. After the pull, in-flight rollouts resume from their existing KV
instead of being preempted and re-prefilled, and their later turns hit
their own history under the pinned salt.
4. Rollouts first admitted after the pull are pinned to the new version.
They cannot hit old-salt blocks, so their prefixes are computed with the
new weights.
5. Old-salt blocks remain reusable by their original rollouts until vLLM
evicts them normally.

Each completion reports the pinned version as `min_policy_version`,
since the completion may depend on KV cached under that version.
`policy_age` and the `max_offpolicy_steps` check therefore account for
the reused KV.

This mode avoids reset-and-reprefill work and preserves cache locality
across policy updates. Its tradeoff is that the salt is only a
prefix-hash namespace; it does not guarantee that every KV block used by
an in-flight rollout came from one weight version. A rollout can retain
prefix KV produced by its starting policy and append new KV after newer
weights have been installed. Because the salt is the version number,
rollouts pinned at the same version on a generator share one namespace:
they reuse common prefixes such as a system prompt with tool
definitions, and after a pull that namespace can also hold KV computed
under the newer weights.

### Mode 2: reset and re-prefill

With `generator.reset_kv_cache_on_weight_sync=true`:

1. The generator installs the new weights.
2. It clears the prefix cache and the pins, and preempts running
requests.
3. vLLM reschedules those requests and recomputes their accumulated
context with the new weights before decode continues.

**Config change.** `reset_kv_cache_on_weight_sync` replaces main's
`reset_prefix_cache_on_weight_sync` and
`reset_running_requests_on_weight_sync`, and the default flips from
reset to preserve. Configs that set either old field must switch to the
new one. Resetting the prefix cache while keeping running requests' KV
is no longer an option: the version salt already gives new requests
fresh KV without a reset, so a reset only matters as a strict recompute,
which must include running requests.

This mode provides strict recomputation under the latest installed
policy and remains useful for exact trainer/generator comparisons
(`batch_invariant` requires it). The additional prefill compute may also
help overlap FSDP parameter all-gathers. The cost is extra prefill work,
queueing, and latency, especially for long-running multi-turn rollouts.

The default mode follows Prime-RL's behavior: a rollout keeps its start
policy version as the cache salt, and the prefix cache is not cleared on
weight updates. TorchTitan obtains these semantics without calling
vLLM's asynchronous `pause_generation` API because weight pulls are
serialized between `engine.step()` bursts.

## Where the salt lives

The salt only matters inside one engine's KV pool, so each generator
owns its pins: rank 0 keeps `group id -> routing session id -> pinned
version` and fills it at admission. The router stays stateless.

Placement belongs to the routing strategy. Later turns only hit their
history if they return to the same generator, which
`StickySessionRoutingStrategy` guarantees (the alphabet_sort recipes use
it; the router default stays `LeastLoadedRoutingStrategy`, as on main).
Under any strategy the salt is still correct: a turn that lands
elsewhere pins that generator's version and misses the cache.

| Request | Salt | Why |
| --- | --- | --- |
| 1st turn of a rollout | The generator's installed version | Pins the
rollout; it cannot hit KV from older weights. |
| Late…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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.

2 participants