Skip to content

refactor triton decode att kernel.#1242

Open
hiworldwzj wants to merge 3 commits intomainfrom
wzj_fix
Open

refactor triton decode att kernel.#1242
hiworldwzj wants to merge 3 commits intomainfrom
wzj_fix

Conversation

@hiworldwzj
Copy link
Collaborator

No description provided.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on refactoring the Triton decode attention kernel to enhance its performance and code structure. The changes include adjustments to grid configurations, memory allocation strategies, and kernel logic to optimize the decoding process, particularly for varying batch sizes. The refactor aims to improve the balance between memory consumption and computational efficiency.

Highlights

  • Refactoring: The primary goal is to refactor the Triton decode attention kernel for improved efficiency and maintainability.
  • Performance Optimization: Changes aim to balance memory consumption and performance, especially for different batch sizes.
  • Code Structure: The refactor involves restructuring the kernel's logic and grid configuration for better parallelization.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the Triton kernel for int4kv decode attention. The key changes include using tl.dot for improved performance with GQA, and moving to a fixed-size grid for the kernel launch, which is beneficial for CUDA graphing. However, the implementation of the grid-stride loop in _fwd_kernel_flash_decode_stage1 has a critical bug that can lead to incorrect attention results when the sequence length requires more blocks than the fixed grid size. My review includes a comment with a suggested fix to address this issue by making the kernel's assumptions explicit and preventing incorrect behavior.

Comment on lines +85 to 132
for iter_block_index in range(block_index, req_total_block_num, grid_block_num):
cur_batch_start_index = iter_block_index * BLOCK_SEQ
cur_batch_end_index = tl.minimum(cur_batch_seq_len, cur_batch_start_index + BLOCK_SEQ)
block_n_size = tl.cdiv(cur_batch_end_index - cur_batch_start_index, BLOCK_N)

offs_n = cur_batch_start_index + tl.arange(0, BLOCK_N)

for start_n in range(0, block_n_size, 1):
offs_n_new = start_n * BLOCK_N + offs_n
k_loc = tl.load(
Req_to_tokens + stride_req_to_tokens_b * cur_batch_req_idx + offs_n_new,
mask=offs_n_new < cur_batch_end_index,
other=0,
)
k_loc = k_loc.to(tl.int64)
off_k = k_loc[:, None] * stride_kbs + cur_kv_head * stride_kh + offs_d[None, :] // 2
off_k_scale = off_k // (quant_group_size // 2)
k_int8 = tl.load(K + off_k, mask=offs_n_new[:, None] < cur_batch_end_index, other=0)
k_scale = tl.load(K_scale + off_k_scale, mask=offs_n_new[:, None] < cur_batch_end_index, other=0.0)
k = int4_to_float(k_int8, k_scale, offs_d)

att_value = tl.dot(q, k.T)
att_value *= sm_scale
att_value = tl.where((offs_n_new[None, :] < cur_batch_end_index), att_value, float("-inf"))
v_int8 = tl.load(V + off_k, mask=offs_n_new[:, None] < cur_batch_end_index, other=0)
v_scale = tl.load(V_scale + off_k_scale, mask=offs_n_new[:, None] < cur_batch_end_index, other=0.0)
v = int4_to_float(v_int8, v_scale, offs_d)

cur_max_logic = tl.max(att_value, axis=1)
new_max_logic = tl.maximum(cur_max_logic, max_logic)

exp_logic = tl.exp(att_value - new_max_logic[:, None])
logic_scale = tl.exp(max_logic - new_max_logic)
acc *= logic_scale[:, None]
acc += tl.dot(exp_logic.to(v.dtype), v)

sum_exp = sum_exp * logic_scale + tl.sum(exp_logic, axis=1)
max_logic = new_max_logic

off_mid_o = (
cur_batch * stride_mid_ob
+ off_head[:, None] * stride_mid_oh
+ block_index * stride_mid_os
+ offs_d[None, :]
)
k_loc = k_loc.to(tl.int64)
off_k = k_loc[:, None] * stride_kbs + cur_kv_head * stride_kh + offs_d[None, :] // 2
off_k_scale = off_k // (quant_group_size // 2)
k_int8 = tl.load(K + off_k, mask=offs_n_new[:, None] < cur_batch_end_index, other=0)
k_scale = tl.load(K_scale + off_k_scale, mask=offs_n_new[:, None] < cur_batch_end_index, other=0.0)
k = int4_to_float(k_int8, k_scale, offs_d)

att_value = tl.sum(q[None, :] * k, 1)
att_value *= sm_scale
att_value = tl.where((offs_n_new < cur_batch_end_index), att_value, float("-inf"))
v_int8 = tl.load(V + off_k, mask=offs_n_new[:, None] < cur_batch_end_index, other=0)
v_scale = tl.load(V_scale + off_k_scale, mask=offs_n_new[:, None] < cur_batch_end_index, other=0.0)
v = int4_to_float(v_int8, v_scale, offs_d)

cur_max_logic = tl.max(att_value, axis=0)
new_max_logic = tl.maximum(cur_max_logic, max_logic)

exp_logic = tl.exp(att_value - new_max_logic)
logic_scale = tl.exp(max_logic - new_max_logic)
acc *= logic_scale
acc += tl.sum(exp_logic[:, None] * v, axis=0)

sum_exp = sum_exp * logic_scale + tl.sum(exp_logic, axis=0)
max_logic = new_max_logic

need_store = tl.where(block_n_size == 0, 0, 1)
for _ in range(0, need_store, 1):
off_mid_o = cur_batch * stride_mid_ob + cur_head * stride_mid_oh + seq_start_block * stride_mid_os + offs_d
off_mid_o_logexpsum = cur_batch * stride_mid_o_eb + cur_head * stride_mid_o_eh + seq_start_block
tl.store(Mid_O + off_mid_o, acc / sum_exp)
off_mid_o_logexpsum = cur_batch * stride_mid_o_eb + off_head * stride_mid_o_eh + block_index
tl.store(Mid_O + off_mid_o, acc / sum_exp[:, None])
tl.store(Mid_O_LogExpSum + off_mid_o_logexpsum, max_logic + tl.log(sum_exp))
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The grid-stride loop for iter_block_index in ... is implemented incorrectly. The accumulator variables (sum_exp, max_logic, acc) are not re-initialized for each iteration of the loop. Furthermore, the results are always stored at an offset calculated from block_index, not iter_block_index.

If this loop were to execute more than once (i.e., if req_total_block_num > grid_block_num), it would lead to incorrect results by accumulating attention scores from unrelated sequence blocks and repeatedly overwriting the same output slot.

Given that the intermediate buffers Mid_O and Mid_O_LogExpSum are sized by grid_block_num on the host, it implies that req_total_block_num should not exceed grid_block_num. The loop is therefore misleading and creates a risk of bugs.

I suggest removing the loop to make the kernel's assumption clear and prevent incorrect behavior. This change assumes each program instance is responsible for exactly one output block. It would also be wise to add a tl.device_assert(req_total_block_num <= grid_block_num) after req_total_block_num is calculated to enforce this constraint.

        cur_batch_start_index = block_index * BLOCK_SEQ
        cur_batch_end_index = tl.minimum(cur_batch_seq_len, cur_batch_start_index + BLOCK_SEQ)
        block_n_size = tl.cdiv(cur_batch_end_index - cur_batch_start_index, BLOCK_N)

        offs_n = cur_batch_start_index + tl.arange(0, BLOCK_N)

        for start_n in range(0, block_n_size, 1):
            offs_n_new = start_n * BLOCK_N + offs_n
            k_loc = tl.load(
                Req_to_tokens + stride_req_to_tokens_b * cur_batch_req_idx + offs_n_new,
                mask=offs_n_new < cur_batch_end_index,
                other=0,
            )
            k_loc = k_loc.to(tl.int64)
            off_k = k_loc[:, None] * stride_kbs + cur_kv_head * stride_kh + offs_d[None, :] // 2
            off_k_scale = off_k // (quant_group_size // 2)
            k_int8 = tl.load(K + off_k, mask=offs_n_new[:, None] < cur_batch_end_index, other=0)
            k_scale = tl.load(K_scale + off_k_scale, mask=offs_n_new[:, None] < cur_batch_end_index, other=0.0)
            k = int4_to_float(k_int8, k_scale, offs_d)

            att_value = tl.dot(q, k.T)
            att_value *= sm_scale
            att_value = tl.where((offs_n_new[None, :] < cur_batch_end_index), att_value, float("-inf"))
            v_int8 = tl.load(V + off_k, mask=offs_n_new[:, None] < cur_batch_end_index, other=0)
            v_scale = tl.load(V_scale + off_k_scale, mask=offs_n_new[:, None] < cur_batch_end_index, other=0.0)
            v = int4_to_float(v_int8, v_scale, offs_d)

            cur_max_logic = tl.max(att_value, axis=1)
            new_max_logic = tl.maximum(cur_max_logic, max_logic)

            exp_logic = tl.exp(att_value - new_max_logic[:, None])
            logic_scale = tl.exp(max_logic - new_max_logic)
            acc *= logic_scale[:, None]
            acc += tl.dot(exp_logic.to(v.dtype), v)

            sum_exp = sum_exp * logic_scale + tl.sum(exp_logic, axis=1)
            max_logic = new_max_logic

        off_mid_o = (
            cur_batch * stride_mid_ob
            + off_head[:, None] * stride_mid_oh
            + block_index * stride_mid_os
            + offs_d[None, :]
        )
        off_mid_o_logexpsum = cur_batch * stride_mid_o_eb + off_head * stride_mid_o_eh + block_index
        tl.store(Mid_O + off_mid_o, acc / sum_exp[:, None])
        tl.store(Mid_O_LogExpSum + off_mid_o_logexpsum, max_logic + tl.log(sum_exp))

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.

1 participant