Skip to content

Conversation

@larryliu0820
Copy link
Contributor

@larryliu0820 larryliu0820 commented Dec 22, 2025

torch.cond doesn't take aliasing or mutations. Adding 2 ops for supporting conditionally updating kv cache:

  • executorch::alias: takes 2 tensors and return the same 2 tensors.
  • executorch::update_cross_attn_cache: takes a tensor cache and a tensor value, in place copy value into cache.

With these 2 ops, we can rewrite the model definition from:

if is_cross_attention and past_key_values and is_updated:
    # reuse k,v, cross_attentions
    key_states = past_key_values.layers[self.layer_idx].keys
    value_states = past_key_values.layers[self.layer_idx].values
else:
    key_states = self.k_proj(current_states).view(bsz, -1, self.num_heads, self.head_dim)
    value_states = self.v_proj(current_states).view(bsz, -1, self.num_heads, self.head_dim)
    key_states = key_states.transpose(1, 2).contiguous()
    value_states = value_states.transpose(1, 2).contiguous()
    if past_key_values is not None:
        # save all key/value_states to cache to be re-used for fast auto-regressive generation
        cache_position = cache_position if not is_cross_attention else None
        key_states, value_states = past_key_values.update(
            key_states, value_states, self.layer_idx, {"cache_position": cache_position}
        )

Into:

def use_cached_kv(
    cached_keys: Tensor,
    cached_values: Tensor,
    key_value_states: Tensor,
) -> tuple[Tensor, Tensor]:
    # Just reuse cached K/V
    return torch.ops.executorch.alias(cached_keys, cached_values)

def recompute_kv(
    cached_keys: Tensor,  # unused
    cached_values: Tensor,  # unused
    key_value_states: Tensor,
) -> tuple[Tensor, Tensor]:
    # Compute fresh K/V (export-friendly: use custom op to mutate cache)
    key_states = self.k_proj(key_value_states).view(bsz, -1, self.num_heads, self.head_dim)
    value_states = self.v_proj(key_value_states).view(bsz, -1, self.num_heads, self.head_dim)
    key_states = key_states.transpose(1, 2).contiguous()
    value_states = value_states.transpose(1, 2).contiguous()
    k = torch.ops.executorch.update_cross_attn_cache(key_states, cached_keys)
    v = torch.ops.executorch.update_cross_attn_cache(value_states, cached_values)
    return k, v

if past_key_values is not None and self.layer_idx is not None:
    # Grab cached tensors (these are Tensors, so they are OK for export)
    cached_keys = past_key_values.layers[self.layer_idx].keys
    cached_values = past_key_values.layers[self.layer_idx].values

    # Tensor predicate: True if any element is non-zero
    # Result is a 0-dim bool tensor suitable for torch.cond
    cache_is_initialized = (cached_keys != 0).any()

    # Use torch.cond to select branch in a traceable way.
    # All operands must be (nested) tensors or simple Python values.
    key_states, value_states = torch.cond(
        cache_is_initialized,
        use_cached_kv,
        recompute_kv,
        operands=(cached_keys, cached_values, key_value_states),
    )

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@larryliu0820
Copy link
Contributor Author

larryliu0820 commented Dec 22, 2025

@pytorch-bot
Copy link

pytorch-bot bot commented Dec 22, 2025

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/16366

Note: Links to docs will display an error until the docs builds have been completed.

❌ 3 New Failures, 26 Pending, 1 Unrelated Failure

As of commit a8b20f5 with merge base 1ce615e (image):

NEW FAILURES - The following jobs have failed:

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

larryliu0820 added a commit that referenced this pull request Dec 22, 2025
ghstack-source-id: e3a8c16
ghstack-comment-id: 3683802199
Pull-Request: #16366
@meta-cla meta-cla bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Dec 22, 2025
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
larryliu0820 added a commit that referenced this pull request Dec 22, 2025
ghstack-source-id: c3050a3
ghstack-comment-id: 3683802199
Pull-Request: #16366
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
larryliu0820 added a commit that referenced this pull request Dec 22, 2025
ghstack-source-id: 19f0553
ghstack-comment-id: 3683802199
Pull-Request: #16366
[ghstack-poisoned]
[ghstack-poisoned]
larryliu0820 added a commit that referenced this pull request Dec 23, 2025
ghstack-source-id: a1ca30a
ghstack-comment-id: 3683802199
Pull-Request: #16366
Base automatically changed from gh/larryliu0820/84/head to main December 23, 2025 04:53
# Copy value into the slice
L[aten.copy_.default](cache_slice, value)

return cache
Copy link
Contributor

Choose a reason for hiding this comment

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

This is returning the original cache whereas eager mode returns a copy. Do you want this discrepancy?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yeah. eager has to return a copy to make exported_program runnable. For inductor lowering we need it to be as efficient as possible.

Copy link
Contributor

Choose a reason for hiding this comment

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

Okay then document the discrepancy

[ghstack-poisoned]
@larryliu0820 larryliu0820 added the release notes: desktop for desktop/laptop workstream label Dec 23, 2025
[ghstack-poisoned]
@larryliu0820 larryliu0820 merged commit 44d436b into main Dec 24, 2025
342 of 601 checks passed
@larryliu0820 larryliu0820 deleted the gh/larryliu0820/85/head branch December 24, 2025 00:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. release notes: desktop for desktop/laptop workstream

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants