-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Ascend attention backend(PA&MLA) #7722
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7f54d32
ascend attention backend
Makcum888e 0bfd1f5
add pr-test-npu.yml and some bugfixes
ping1jing2 59d195d
Merge branch 'main' into ascend_attention_backend
Alcanderian 2eec394
merge MLA
VDV1985 4efc1bf
Merge branch 'main' into ascend_attention_backend
ping1jing2 57f683a
Update forward_batch_info.py
ping1jing2 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| name: PR Test (Ascend NPU) | ||
|
|
||
| on: | ||
| push: | ||
| branches: [ main ] | ||
| paths: | ||
| - "python/**" | ||
| - "scripts/**" | ||
| - "test/**" | ||
| - ".github/workflows/pr-test-npu.yml" | ||
| pull_request: | ||
| branches: [ main ] | ||
| paths: | ||
| - "python/**" | ||
| - "scripts/**" | ||
| - "test/**" | ||
| - ".github/workflows/pr-test-npu.yml" | ||
| workflow_dispatch: | ||
|
|
||
| concurrency: | ||
| group: pr-test-npu-${{ github.ref }} | ||
| cancel-in-progress: true | ||
|
|
||
| jobs: | ||
| unit-test-backend-1-npu-ascend: | ||
| if: (github.repository == 'sgl-project/sglang' || github.event_name == 'pull_request') && | ||
| github.event.pull_request.draft == false && contains(github.event.pull_request.labels.*.name, 'npu') | ||
| strategy: | ||
| fail-fast: false | ||
| runs-on: self-hosted | ||
| steps: | ||
| - name: Checkout code | ||
| uses: actions/checkout@v4 | ||
|
|
||
| - name: Run test | ||
| timeout-minutes: 40 | ||
| run: | | ||
| cd test/srt | ||
| python3 run_suite.py --suite per-commit-npu | ||
|
|
||
| finish: | ||
| if: always() | ||
| needs: [ unit-test-backend-1-npu-ascend ] | ||
| runs-on: self-hosted | ||
| steps: | ||
| - name: Check all dependent job statuses | ||
| run: | | ||
| results=(${{ join(needs.*.result, ' ') }}) | ||
| for result in "${results[@]}"; do | ||
| if [ "$result" = "failure" ] || [ "$result" = "cancelled" ]; then | ||
| echo "Job failed with result: $result" | ||
| exit 1 | ||
| fi | ||
| done | ||
| echo "All jobs completed successfully" | ||
| exit 0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from typing import TYPE_CHECKING, Optional | ||
|
|
||
| import torch | ||
| import torch_npu | ||
| from torch.nn.functional import scaled_dot_product_attention | ||
|
|
||
| from sglang.srt.layers.attention.base_attn_backend import AttentionBackend | ||
| from sglang.srt.layers.radix_attention import AttentionType | ||
| from sglang.srt.model_executor.forward_batch_info import ForwardBatch | ||
|
|
||
| if TYPE_CHECKING: | ||
| from sglang.srt.layers.radix_attention import RadixAttention | ||
| from sglang.srt.model_executor.model_runner import ModelRunner | ||
|
|
||
|
|
||
| @dataclass | ||
| class ForwardMetadata: | ||
|
|
||
| # calculated map for kv positions [bs * maxseqlen] | ||
| block_tables: Optional[torch.Tensor] = None | ||
|
|
||
| # seq len inputs | ||
| extend_seq_lens_cpu_int: Optional[torch.Tensor] = None | ||
| seq_lens_cpu_int: Optional[torch.Tensor] = None | ||
|
|
||
|
|
||
| class AscendAttnBackend(AttentionBackend): | ||
|
|
||
| def gen_attention_mask(self, max_seq_len: int, dtype=torch.float16): | ||
| mask_flag = torch.tril( | ||
| torch.ones((max_seq_len, max_seq_len), dtype=torch.bool) | ||
| ).view(max_seq_len, max_seq_len) | ||
| mask_flag = ~mask_flag | ||
| if dtype == torch.float16: | ||
| mask_value = torch.finfo(torch.float32).min | ||
| else: | ||
| mask_value = 1 | ||
| self.mask = ( | ||
| torch.masked_fill( | ||
| torch.zeros(size=(max_seq_len, max_seq_len)), mask_flag, mask_value | ||
| ) | ||
| .to(dtype) | ||
| .to(self.device) | ||
| ) | ||
| self.mask_len = max_seq_len | ||
|
|
||
| def __init__(self, model_runner: ModelRunner): | ||
| super().__init__() | ||
| self.forward_metadata = ForwardMetadata() | ||
| self.device = model_runner.device | ||
| self.gen_attention_mask(128, model_runner.dtype) | ||
ping1jing2 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self.page_size = model_runner.page_size | ||
|
|
||
| def init_forward_metadata(self, forward_batch: ForwardBatch): | ||
| """Init the metadata for a forward pass.""" | ||
| self.forward_metadata.block_tables = ( | ||
| forward_batch.req_to_token_pool.req_to_token[ | ||
| forward_batch.req_pool_indices, : forward_batch.seq_lens.max() | ||
| ][:, :: self.page_size] | ||
| // self.page_size | ||
| ) | ||
| if forward_batch.extend_seq_lens is not None: | ||
| self.forward_metadata.extend_seq_lens_cpu_int = ( | ||
| forward_batch.extend_seq_lens.cpu().int() | ||
| ) | ||
| self.forward_metadata.seq_lens_cpu_int = forward_batch.seq_lens_cpu.int() | ||
ping1jing2 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| def forward_extend( | ||
| self, | ||
| q, | ||
| k, | ||
| v, | ||
| layer: RadixAttention, | ||
| forward_batch: ForwardBatch, | ||
| save_kv_cache=True, | ||
| ): | ||
| if save_kv_cache: | ||
| forward_batch.token_to_kv_pool.set_kv_buffer( | ||
| layer, forward_batch.out_cache_loc, k, v | ||
| ) | ||
|
|
||
| k_cache = forward_batch.token_to_kv_pool.get_key_buffer(layer.layer_id) | ||
| v_cache = forward_batch.token_to_kv_pool.get_value_buffer(layer.layer_id) | ||
|
|
||
| query = q.view(-1, layer.tp_q_head_num * layer.qk_head_dim) | ||
| output = torch.empty( | ||
| (query.shape[0], layer.tp_q_head_num * layer.v_head_dim), | ||
| dtype=query.dtype, | ||
| device=query.device, | ||
| ) | ||
|
|
||
| torch_npu._npu_flash_attention_qlens( | ||
| query=query, | ||
| key_cache=k_cache, | ||
| value_cache=v_cache, | ||
| mask=self.mask, | ||
| block_table=self.forward_metadata.block_tables, | ||
| seq_len=self.forward_metadata.extend_seq_lens_cpu_int, | ||
| context_lens=self.forward_metadata.seq_lens_cpu_int, | ||
| scale_value=layer.scaling, | ||
| num_heads=layer.tp_q_head_num, | ||
| num_kv_heads=layer.tp_k_head_num, | ||
| out=output, | ||
| ) | ||
| return output | ||
|
|
||
| def forward_decode( | ||
| self, | ||
| q: torch.Tensor, | ||
| k: torch.Tensor, | ||
| v: torch.Tensor, | ||
| layer: RadixAttention, | ||
| forward_batch: ForwardBatch, | ||
| save_kv_cache=True, | ||
| ): | ||
| if save_kv_cache: | ||
| forward_batch.token_to_kv_pool.set_kv_buffer( | ||
| layer, forward_batch.out_cache_loc, k, v | ||
| ) | ||
|
|
||
| k_cache = forward_batch.token_to_kv_pool.get_key_buffer(layer.layer_id) | ||
| v_cache = forward_batch.token_to_kv_pool.get_value_buffer(layer.layer_id) | ||
|
|
||
| query = q.view(-1, layer.tp_q_head_num, layer.qk_head_dim) | ||
| num_tokens = query.shape[0] | ||
| output = torch.empty( | ||
| (num_tokens, layer.tp_q_head_num, layer.v_head_dim), | ||
| dtype=query.dtype, | ||
| device=query.device, | ||
| ) | ||
|
|
||
| torch_npu._npu_paged_attention( | ||
| query=query, | ||
| key_cache=k_cache, | ||
| value_cache=v_cache, | ||
| num_heads=layer.tp_q_head_num, | ||
| num_kv_heads=layer.tp_k_head_num, | ||
| scale_value=layer.scaling, | ||
| block_table=self.forward_metadata.block_tables, | ||
| context_lens=self.forward_metadata.seq_lens_cpu_int, | ||
| out=output, | ||
| ) | ||
| return output.view(num_tokens, layer.tp_q_head_num * layer.v_head_dim) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.