Skip to content

[DeepSeek-V4] Implement Compressed Attention Layers - #3866

Merged
copybara-service[bot] merged 1 commit into
mainfrom
deepseek_v4_compressed_attention
Jun 9, 2026
Merged

copybara-service[bot] merged 1 commit into
mainfrom
deepseek_v4_compressed_attention

Conversation

@parambole

@parambole parambole commented May 11, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Implement compressed attention mechanisms and indexer modules required for DeepSeek-V4 integration into MaxText.

  • CSACompressor & HCACompressor: Long-range attention compressors. Overlapping 2m-window compression logic is abstracted into a shared csa_overlap_pooling.
  • DeepseekV4Indexer: Indexer module that leverages the shared overlapping compression logic. It identifies the top-k most relevant blocks and constructs a dynamic compressed_mask to enforce sparsity natively inside AttentionOp.
  • Configuration: Registered attention compression hyperparameters (compress_ratios, compressed_rope_max_timescale, o_lora_rank, etc.) directly into the base Config class in types.py.

Tests

Tested on CPU

pytest tests/unit/deepseek_v4_vs_reference_test.py
======================= 9 passed, 111 warnings in 18.56s =======================
tests/unit/deepseek_v4_vs_reference_test.py .........                    [100%]

Checklist

Before submitting this PR, please make sure (put X in square brackets):

  • I have performed a self-review of my code. For an optional AI review, add the gemini-review label.
  • I have necessary comments in my code, particularly in hard-to-understand areas.
  • I have run end-to-end tests tests and provided workload links above if applicable.
  • I have made or will make corresponding changes to the doc if needed, including adding new documentation pages to the relevant Table of Contents (toctree directive) as explained in our documentation.

@codecov

codecov Bot commented May 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 5.57769% with 237 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/maxtext/layers/attention_compressed.py 0.00% 232 Missing ⚠️
src/maxtext/layers/attention_op.py 72.22% 2 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

@parambole
parambole force-pushed the deepseek_v4_compressed_attention branch from 5f54827 to 07eb3e2 Compare May 11, 2026 19:39
@parambole
parambole changed the base branch from deepseek_v4_core_primitives to dsv4-moe-routing-primitives May 11, 2026 20:29
@parambole
parambole force-pushed the dsv4-moe-routing-primitives branch from 37ee811 to 31329c5 Compare May 11, 2026 20:38
@parambole
parambole force-pushed the deepseek_v4_compressed_attention branch from 07eb3e2 to 4520166 Compare May 11, 2026 20:43
@parambole
parambole force-pushed the dsv4-moe-routing-primitives branch from 31329c5 to 22a57ff Compare May 12, 2026 17:23
@parambole
parambole force-pushed the deepseek_v4_compressed_attention branch from 4520166 to 10ca4f6 Compare May 12, 2026 17:23
@parambole
parambole force-pushed the dsv4-moe-routing-primitives branch from 22a57ff to 32869e5 Compare May 12, 2026 21:12
@parambole
parambole force-pushed the deepseek_v4_compressed_attention branch from 10ca4f6 to 31a5932 Compare May 12, 2026 21:13
@parambole
parambole force-pushed the dsv4-moe-routing-primitives branch from 32869e5 to c92f2e0 Compare May 14, 2026 17:51
@parambole
parambole force-pushed the deepseek_v4_compressed_attention branch from 31a5932 to c98a34e Compare May 14, 2026 17:53
@parambole parambole changed the title Implement DeepSeek-V4 Compressed Attention Layers [DeepSeek-V4] Implement Compressed Attention Layers May 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🤖 Hi @parambole, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@parambole
parambole changed the base branch from dsv4-moe-routing-primitives to deepseek_v4_core_primitives June 4, 2026 22:21
@parambole
parambole requested a review from darisoy as a June 4, 2026 22:21
@parambole
parambole force-pushed the deepseek_v4_core_primitives branch 3 times, most recently from d39e334 to 86e251f Compare June 4, 2026 22:32
@parambole
parambole force-pushed the deepseek_v4_compressed_attention branch from fb88300 to 42ad560 Compare June 4, 2026 22:33
@parambole
parambole force-pushed the deepseek_v4_core_primitives branch 3 times, most recently from 5a4f487 to 7555c61 Compare June 4, 2026 22:44
@parambole
parambole force-pushed the deepseek_v4_compressed_attention branch from 42ad560 to b9900b8 Compare June 4, 2026 22:44
@parambole

Copy link
Copy Markdown
Collaborator Author

Thanks for the implementation! Here are my high-level comments:

  1. Please replace nnx.Linear with MaxText DenseGeneral
  2. I recommend reusing some common logic from Indexer of V3.2, perhaps by abstracting into a base class
  3. It unclear to me how "Additional Branch of Sliding Window Attention" from Section 2.3.3 in paper is implemented. Could you explain?

Thanks for the review! Here is how we addressed these:

nnx.Linear replaced: Fixed. All occurrences of nnx.Linear across the compressors, indexer, and projections have been replaced with MaxText's native DenseGeneral.

Indexer reuse vs Base class: While I strongly considered a unified BaseIndexer, DeepSeek-V4's indexer requires complex 2m-overlapping window compression logic to pool KV states before scoring them. V3.2's indexer doesn't do this compression. Merging them into a single base class created too much structural friction. Instead, to remove redundancy, we extracted the overlapping compression math into a shared standalone function (csa_overlap_pooling) which is now cleanly reused by both CSACompressor and DeepseekV4Indexer.

"Additional Branch of Sliding Window Attention": This simply means that the recent sliding window tokens are preserved uncompressed alongside the sparse compressed blocks. We implement this by appending the uncompressed KV entries and passing them down to AttentionOp, relying on generate_attention_mask to construct a banded causal sliding window mask over those recent entries.

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

🤖 Hi @parambole, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

🤖 I'm sorry @parambole, but I was unable to process your request. Please see the logs for more details.

@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

🤖 Hi @RissyRan, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

🤖 I'm sorry @RissyRan, but I was unable to process your request. Please see the logs for more details.

@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

🤖 I'm sorry @RissyRan, but I was unable to process your request. Please see the logs for more details.

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

Thanks for the change! From the conversation, I guess it's still non-trivial to re-use existing codebase (which was my hope). Left a few comments, and happy to chat more!

Comment thread src/maxtext/configs/base.yml Resolved
num_kv_heads=1,
max_target_length=128,
mesh=None,
attention_kernel="dot_product",

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.

Will you support flash attention in next step in the bringup?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes. It will be supported as part of Phase 2

@RissyRan

RissyRan commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator

🤖 I'm sorry @RissyRan, but I was unable to process your request. Please see the logs for more details.

Hmm..Attempt 1 failed with status 500. Retrying with backoff... _ApiError: {"error":{"code":500,"message":"Internal error encountered.","status":"INTERNAL"}}, Will take a look next week.

# DeepSeek-V4 uses a mathematical attention sink (a learnable scalar per-head added to the
# attention logits prior to softmax, rather than a physical key/value token). We unconditionally
# initialize it here, overriding the base Attention class which disables it by default.
self.sinks = nnx.data(nnx.Param(jnp.zeros((self.num_query_heads,), dtype=self.dtype)))

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.

Maybe can remove nnx.data, and directly use self.sinks=nnx.Param(...). Should use dtype=self.weight_dtype.

Actually, why not hard-code attention_sink=True in super().__init__ to use this:

if self.config.attention_sink:
self.sinks = nnx.Param(
default_bias_init(self.rngs.params(), (self.config.num_query_heads,), self.weight_dtype),
sharding=(None,),
)
else:
self.sinks = None

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@shuningjin I originally tried removing nnx.data(...), but it actually causes the tests to fail with a ValueError. Because self.sinks = None in the base Attention class, Flax NNX strictly infers it as a static attribute. When we try to dynamically assign an nnx.Param to it in this subclass, Flax throws an exception for assigning a dynamic data value to a static attribute. Wrapping it in nnx.data(...) is currently the only way to explicitly override that static status! We'll need to keep the wrapper for now.

return final_out


def compressed_attention(

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.

For new modules, do we need to_linen wrapper? can we remove these? @bvandermoon

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

We still need the compressed_attention free function and its to_linen wrapper for backwards compatibility with the legacy pipeline in our internal testing infrastructure. Even though we are actively migrating to NNX, we can't safely deprecate the Linen wrappers on this module just yet. Let's leave them in for now!

cc: @bvandermoon please correct me if I am wrong

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

Thanks for the refactor! Approve to unblock. Please address the other comments.

Agree with @RissyRan for reuse when possible. Ideally we hope to overlap these as much as possible: (1) hca & csa, (2) dsv4_indexer & dsv32_indexer, (3) attention_compressed & attention. For (1), the initialization seems very similar; see inline comment.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants