Skip to content

DSv4 static cache - #46384

Open
IlyasMoutawwakil wants to merge 21 commits into
mainfrom
dsv4-static-cache
Open

IlyasMoutawwakil wants to merge 21 commits into
mainfrom
dsv4-static-cache

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Jun 3, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

probably still ugly, but works, still needs benching. made with claude's help.

Code Agent Policy

The Transformers repo is currently being overwhelmed by a large number of PRs and issue comments written by
code agents. We are currently bottlenecked by our ability to review and respond to them. As a result,
we ask that new users do not submit pure code agent PRs at this time.
You may use code agents in drafting or to help you diagnose issues. We'd also ask autonomous "OpenClaw"-like agents
not to open any PRs or issues for the moment.

PRs that appear to be fully agent-written will probably be closed without review, and we may block users who do this
repeatedly or maliciously.

This is a rapidly-evolving situation that's causing significant shockwaves in the open-source community. As a result,
this policy is likely to be updated regularly in the near future. For more information, please read CONTRIBUTING.md.

  • I confirm that this is not a pure code agent PR.

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline,
    Pull Request section?
  • Was this discussed/approved via a Github issue or the forum? Please add a link
    to it if that's the case.
  • Did you make sure to update the documentation with your changes? Here are the
    documentation guidelines, and
    here are tips on formatting docstrings.
  • Did you write any new necessary tests?

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Comment thread src/transformers/modeling_utils.py Outdated
):
self._last_compile_config = compile_config
mark_repeated_decoder_layers_as_compile_regions(self)
install_compile_patches()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

many patches need to land in torch before this can work natively, in torch 2.13 maybe, but for now torch.compiler.nested_compile_region doesn't seem worth it (the compile speedup is also not that crazy)

@Suraj-1207

Copy link
Copy Markdown

The diff adds two new classes, DeepseekV4HCAStaticCache and DeepseekV4CSAStaticCache, which are static counterparts to DeepseekV4HCACache and DeepseekV4CSACache respectively. These classes add compressor-state API on top of pre-allocated buffers to make the whole forward dynamo-traceable. The diff also sets _can_compile_fullgraph to True in DeepseekV4PreTrainedModel. The changes are related to the integration of DeepSeek V4 with the Transformers library.

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice! Can you spend some time on the doc so its more human! Otherwise LGTM, we can default the max compress lenght by dividing max_new_tokens by the compression rate, probably already done?

# ``"compressor"`` entry, at ``head_dim`` for both the rolling source-token buffer
# and the compressed-entry storage. CSA adds an ``"indexer"`` entry with different
# widths (see :class:`DeepseekV4CSAStaticCache` which overrides these tables).
self._buffer_feat_by_name: dict[str, int] = {"compressor": config.head_dim}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

let's find better names!

Comment on lines +347 to +348
self.buffer_kv: dict[str, torch.Tensor | None] = dict.fromkeys(self._buffer_feat_by_name)
self.buffer_gate: dict[str, torch.Tensor | None] = dict.fromkeys(self._buffer_feat_by_name)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this is a bitweird / looks wasteful

Comment on lines +382 to +393
"""Static analogue of :meth:`DeepseekV4HCACache.store_compression_weights`.

Decode (``new_n == 1``): shifts the rolling buffer left by 1, appends the new
token at the rightmost slot, returns the full ``(B, compress_rate, head_dim)``
buffer — always one window's worth, even when the window isn't yet full
(left slots are zeros). The compressor emits one candidate entry; the
attention mask hides it until the window actually closes.

Prefill (``new_n > 1``): re-uses the dynamic logic — concat buffer's real tail
with the new kv, peel off the window-aligned prefix, and refresh the rolling
buffer with the last ``compress_rate`` tokens of the combined stream.
"""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

let's make this human redable / human made :) :)

return prior_kv, prior_gate


class DeepseekV4HCAStaticCache(StaticSlidingWindowLayer):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

we might want to add to generation_deepseek_v4.py its not core modeling!

Comment on lines +470 to +479
r"""Static counterpart to :class:`DeepseekV4CSACache`: adds the ``"indexer"`` name
and per-name overlap state (Ca slice of the previous window's chunk) on top of
the HCA static buffers.

Overlap state is fixed-shape ``(B, compress_rate, head_dim)`` per name and starts
as zeros — the existing consumer ``new_kv[:, 0, :ratio] = prior_kv`` is a write,
not an add, so handing back zeros on the first call is observationally identical
to the dynamic cache's ``None`` (the slot was already zeros from ``new_zeros``).

Note: no ``layer_type`` is set on this class — see :class:`DeepseekV4HCAStaticCache`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

same let's put effort in making this human like !

@IlyasMoutawwakil
IlyasMoutawwakil marked this pull request as ready for review June 15, 2026 13:04

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice! can you put the benches here as well! 🤗

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

to remove no?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

it's more practical for testing than a long string

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: deepseek_v4

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants