Skip to content

[Linear Attention] Update fused_recurrent.py for inference with nomalization=true #268

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 19 commits into
base: main
Choose a base branch
from

Conversation

yiyousong
Copy link

@yiyousong yiyousong commented Apr 1, 2025

the current linear attention can save a $KV$ state cache. This works when normalization is not enabled. When normalization is enabled. the output should be $\frac{QKV}{QK1}$. we can see that $QK1$ or Q@sum(K) is missing earlier Keys

last pull request only modified one file, not sure why this happen, re-opened this, hope this version does contain two changes

Summary by CodeRabbit

  • New Features
    • Enhanced attention processing by adding an optional cumulative tensor input. This update refines the output normalization logic, offering increased flexibility and precision in the computation without altering the overall control flow.

Copy link

coderabbitai bot commented Apr 1, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes introduce an additional optional parameter in three functions to support cumulative tensor handling. The function fused_recurrent_linear_attn now accepts a tensor parameter cum_k (defaulting to None), and its call to normalize_output is updated accordingly. The normalize_output function also accepts an optional parameter cum_k and conditionally adds its value to k if provided. Similarly, the fused_chunk_linear_attn function is updated to include cum_k, affecting its normalization process. The changes adjust the function signatures and update internal computations without altering the overall control flow.

Changes

File(s) Change Summary
fla/ops/linear_attn/fused_recurrent.py Modified fused_recurrent_linear_attn to add an optional cum_k parameter (torch.Tensor, default None) and updated its call to normalize_output.
fla/ops/linear_attn/utils.py Updated normalize_output to include an optional cum_k parameter (default None) and conditionally add this value to k during normalization.
fla/ops/linear_attn/fused_chunk.py Modified fused_chunk_linear_attn to add an optional cum_k parameter (torch.Tensor, default None) and updated its call to normalize_output.

Sequence Diagram(s)

sequenceDiagram
    participant FR as fused_recurrent_linear_attn
    participant NO as normalize_output

    FR->>NO: Call normalize_output(q * scale, k, o, cum_k)
    alt cum_k provided
        NO->>NO: Compute k = k + cum_k
    else No cum_k
        NO->>NO: Proceed without modifying k
    end
    NO->>FR: Return normalized output

    participant FC as fused_chunk_linear_attn
    FC->>NO: Call normalize_output(q * scale, k, o, cum_k)
    alt cum_k provided
        NO->>NO: Compute k = k + cum_k
    else No cum_k
        NO->>NO: Proceed without modifying k
    end
    NO->>FC: Return normalized output
Loading

Poem

I'm a rabbit with a hop and a bound,
Celebrating changes that are newly found.
A tiny tensor tip adds a little spark,
In our code garden, lighting up the dark.
With cum_k on board, our functions sing—
A joyful leap forward, oh what a spring!
🐰✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
fla/ops/linear_attn/fused_recurrent.py (2)

238-238: Consider consistent naming convention across files

The parameter here is named cum_K with uppercase K, while in normalize_output it's named cum_k with lowercase k. Consider using consistent naming across the codebase to avoid confusion.

-    cum_K: torch.Tensor = None,
+    cum_k: torch.Tensor = None,

249-249: Fix parameter case and formatting

  1. The parameter case should match between the function definition and where it's used.
  2. Add a space after the comma for better readability.
-        o = normalize_output(q * scale, k, o,cum_K)
+        o = normalize_output(q * scale, k, o, cum_K)

If you choose to update the parameter name for consistency:

-        o = normalize_output(q * scale, k, o,cum_K)
+        o = normalize_output(q * scale, k, o, cum_k)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7da5e7a and 30d5606.

📒 Files selected for processing (2)
  • fla/ops/linear_attn/fused_recurrent.py (2 hunks)
  • fla/ops/linear_attn/utils.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
fla/ops/linear_attn/utils.py

10-10: Undefined name cum_K

(F821)

@zhiyuan1i zhiyuan1i requested review from yzhangcs and zhiyuan1i April 1, 2025 02:43
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
fla/ops/linear_attn/fused_chunk.py (1)

279-279: Add parameter documentation in the docstring.

The new cum_k parameter has been added to the function signature, but its description is missing from the docstring. For better maintainability and clarity, please update the docstring to explain the purpose of cum_k, its expected type, and when it should be provided.

Consider adding a description like:

cum_k (Optional[torch.Tensor]):
    Cumulative key tensor used during normalization when inference with saved state.
    Defaults to `None`.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1c6ea0c and b5d64ba.

📒 Files selected for processing (1)
  • fla/ops/linear_attn/fused_chunk.py (2 hunks)
🔇 Additional comments (1)
fla/ops/linear_attn/fused_chunk.py (1)

316-316:

✅ Verification successful

Fix for normalization with KV cache.

This change correctly addresses the issue described in the PR where QK1 (or Q@sum(K)) is missing earlier Keys when normalization is enabled. By passing the cumulative cum_k parameter to the normalize_output function, the normalization process can now properly calculate the output as QKV/QK1 including all previous keys in the cache.


🏁 Script executed:

#!/bin/bash
# Check if normalize_output has been updated to accept cum_k parameter
cat fla/ops/linear_attn/utils.py | grep -A 10 "def normalize_output"

Length of output: 247


Normalization with KV Cache Fix Confirmed

The updated implementation of normalize_output now correctly accepts the cum_k parameter, ensuring that earlier keys (the cumulative key values) are incorporated into the normalization process. This resolves the issue where QK1 (or Q @ sum(K)) was missing contributions from previous keys when normalization was enabled.

  • Location: fla/ops/linear_attn/utils.py
  • Key Change: In normalize_output, the cumulative keys are now added to the cumsum of k when cum_k is not None.

@zhiyuan1i
Copy link
Collaborator

Thanks for contributing, can you @yiyousong add tests to your contribution? This will improve the robustness of the code

@yzhangcs could you please give some comments?
tests: https://github.com/fla-org/flash-linear-attention/blob/main/tests/ops/test_linear_attn.py
layers: https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/linear_attn.py

@yiyousong
Copy link
Author

Thanks for contributing, can you @yiyousong add tests to your contribution? This will improve the robustness of the code

@yzhangcs could you please give some comments? tests: https://github.com/fla-org/flash-linear-attention/blob/main/tests/ops/test_linear_attn.py layers: https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/linear_attn.py

Sorry, I don't think I understand how the tests works.

@zhiyuan1i
Copy link
Collaborator

Thanks for contributing, can you @yiyousong add tests to your contribution? This will improve the robustness of the code
@yzhangcs could you please give some comments? tests: https://github.com/fla-org/flash-linear-attention/blob/main/tests/ops/test_linear_attn.py layers: https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/linear_attn.py

Sorry, I don't think I understand how the tests works.

You could have a try:)

pip install pytest
export COMPILER_MODE=1 # to speed up
pytest tests/ops/test_linear_attn.py
pytest tests/layers/test_linearatten_layer.py

You can see it will test function automatically. The thing you need to do is to test your cum_k and see if there is a need to change fla/layers/linear_attn.py because I see you only change the kernel.

@yiyousong yiyousong marked this pull request as draft April 1, 2025 06:03
@yzhangcs
Copy link
Member

yzhangcs commented Apr 1, 2025

@yiyousong Hello, could you please explain more on what does this arg mean and what's the purpose of imposing this arg

@yiyousong
Copy link
Author

@yiyousong Hello, could you please explain more on what does this arg mean and what's the purpose of imposing this arg

Linear attention without normalization equals to $\phi(Q)\phi(K)V$ or $\Sigma (q_i \Sigma (k_j v_j))$.
$\Sigma_{j=1}^N (k_j v_j)=\Sigma_{j=c}^N (k_j v_j)+\Sigma_{j=1}^c (k_j v_j)=\Sigma_{j=c}^N (k_j v_j)+cache$
this is your code when initial_state!=None
The inputs $K$ should now contain tokens from position c to N (only tokens after cached positions)

Linear attention with normalization equals to $\frac{\phi(Q)\phi(K)V}{\phi(Q)\phi(K)1}$ or $\Sigma_{i=1}^N (\frac{q_i \Sigma (k_j v_j)}{q_i \Sigma k_j})$.
Focus on the $\Sigma k_j$. During generation, the inputs to the function is probably only just the last token (shorter than total when initial_state is not None). In this case the function will calculate the sum of K as $k_N$ which is significantly smaller than the sum of all Keys. To solve this, we need to cache the sum of the previous keys ($\Sigma_{i=1}^c k_i$). In this case the $\Sigma k_j$ can be recovered by add the cached sum ($\Sigma_{i=1}^c k_i$ ,shape [B,H,1,D]) to the cumulative sum of the current inputs ($\Sigma_{i=c}^N k_i$ ,shape [B,H,S,D]).
From the math, you can see that this issue only happens when both cache and normalization are used at the same time.

However, implementation was harder than I thought, as the compiled function does not take if statement. So I cannot just simply add a few parameters.

Maybe you need to change all the code involving normalization and cache

@yzhangcs
Copy link
Member

yzhangcs commented Apr 1, 2025

@yiyousong Thank you, good point! We do need to suuport this. But I dont think cum_k is a good name, some better APIs designs could be considered.
How about making normalization as a part of initial/final-state?

@yzhangcs yzhangcs changed the title Update fused_recurrent.py for inference with nomalization=true [Linear Attention] Update fused_recurrent.py for inference with nomalization=true Apr 1, 2025
@@ -4,7 +4,9 @@


@torch.jit.script
def normalize_output(q, k, o):
def normalize_output(q, k, o, cum_k=None):
Copy link
Member

Choose a reason for hiding this comment

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

@yiyousong Maybe we could pass initial_state as an arg with cum_k included for API consistency.

Copy link
Author

Choose a reason for hiding this comment

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

I only use ops, so I like passing in separately. However, your code you choice. I believe it doesn't matter as long as you don't merge them into one tensor

@@ -235,6 +235,7 @@ def fused_recurrent_linear_attn(
v: torch.Tensor,
scale: Optional[float] = None,
initial_state: torch.Tensor = None,
cum_k: torch.Tensor = None,
Copy link
Member

Choose a reason for hiding this comment

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

@yiyousong I think we could make initial_state a Tuple if normalize is True. What do you think?

@@ -235,6 +235,7 @@ def fused_recurrent_linear_attn(
v: torch.Tensor,
scale: Optional[float] = None,
initial_state: torch.Tensor = None,
cum_k: torch.Tensor = None,
output_final_state: bool = False,
normalize: bool = False,
Copy link
Member

Choose a reason for hiding this comment

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

@yiyousong Could you please add some docstrings BTW.

@yzhangcs
Copy link
Member

yzhangcs commented Apr 3, 2025

@yiyousong Hello r u still working on this PR?

@yiyousong
Copy link
Author

@yiyousong Hello r u still working on this PR?

I was evaluating using my own code. (only used fla.ops, not fla.layers).
Based on my experience, I believe although the "Z-state"(following naming from original linear attention) can be merged with the "memory-state", I would not recommend it, as "Z-state" is only needed when normalization is True. Changes on the lower-api is unavoidable.

@yiyousong
Copy link
Author

These changes are based on the code I changed to work for my model. I probably won't work on this further.
Maybe after May 15th I may continue to update this, but currently I am too busy to debug code I won't use.

o = normalize_output(q * scale, k, o)
if z_state is None:
k_shape = list(k.shape)
k_shape[-2 ]= 1
Copy link
Member

Choose a reason for hiding this comment

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

Removing the space in [-2] would be better.
How about directly init z_state by

z_state =  torch.zeros_like(k[..., 0, :]) if z_state is None else z_state 

Copy link
Member

Choose a reason for hiding this comment

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

also I think [B, H, K, 1] could be confusing, would [B, H, K] be better.
There's no cost for unsqueeze when updating z state

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.

3 participants