Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions python/sgl_kernel_npu/build_tools/third_party.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ def resolve_plan(
if root.resolve() not in config_path.resolve().parents:
raise ValueError("Dependency configuration escapes third_party")
config = read_json(config_path)
# Experimental profiles can be selected explicitly without changing
# the dependency set of existing wheel builds.
if config.pop("opt_in", False) and third_party is None:
continue
# Profile documentation is not part of the build configuration or cache key.
config.pop("_comment", None)
# One upstream profile can require separate regular/experimental vendors.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@
fused_infer_attention_score_v2_out,
)
from .gqa_share_sparse_decode import gqa_share_sparse_decode
from .int8_csa import (
check_int8_csa_support,
int8_csa_attention,
int8_csa_metadata,
int8_csa_write,
)
from .kda import chunk_kda_fwd
from .kv_quant_sparse_attn_sharedkv import kv_quant_sparse_attn_sharedkv
from .kv_quant_sparse_attn_sharedkv_metadata import (
Expand Down Expand Up @@ -63,6 +69,7 @@
"attention_sinks",
"attention_sinks_prefill",
"attention_update",
"check_int8_csa_support",
"chunk_kda_fwd",
"compressor",
"compressor_v2",
Expand All @@ -81,6 +88,9 @@
"get_mixed_quant_sparse_flash_mla_metadata_size",
"get_sparse_flash_mla_metadata_size",
"gqa_share_sparse_decode",
"int8_csa_attention",
"int8_csa_metadata",
"int8_csa_write",
"kv_quant_sparse_attn_sharedkv",
"kv_quant_sparse_attn_sharedkv_metadata_host",
"kv_quant_sparse_flash_attention",
Expand Down
145 changes: 145 additions & 0 deletions python/sgl_kernel_npu/sgl_kernel_npu/operators/attention/int8_csa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"""CANN native INT8 compressed sparse attention for the signed 608-byte cache."""

from functools import lru_cache
from math import isclose

import torch

from ..utils.generation import Generation, get_hardware


@lru_cache(maxsize=1)
def _native_ops():
if get_hardware().generation is not Generation.ARCH22:
raise RuntimeError("INT8 CSA requires the CANN arch22 implementation.")
try:
# Import registers the private Torch namespace and its graph metadata.
from ..._third_party import sgl_ops_transformer_int8_csa # noqa: F401

ops = torch.ops.sgl_ops_transformer_int8_csa
return (
ops.kv_compress_epilog,
ops.mixed_quant_sparse_flash_mla_metadata,
ops.mixed_quant_sparse_flash_mla,
)
except (ImportError, AttributeError) as exc:
raise RuntimeError(
"INT8 CSA requires sgl-kernel-npu built with the ops_transformer_int8_csa profile."
) from exc


def int8_csa_write(cache, x, slot_mapping, *, reserve_page_zero=False):
"""Write post-RoPE BF16 rows in place.

A slot of -1 skips the row. With reserve_page_zero, all slots in the first
page and out-of-range slots are skipped without changing the input shape.
"""
if reserve_page_zero:
x = x.reshape(-1, 512).contiguous()
if x.shape[0] == 0:
return
slot_mapping = slot_mapping.reshape(-1)
if x.shape[0] != slot_mapping.numel() or x.dtype != torch.bfloat16:
raise ValueError("INT8 CSA requires one BF16 latent row per cache slot.")
page_rows = cache.shape[1]
live = (slot_mapping >= page_rows) & (slot_mapping < cache.shape[0] * page_rows)
slot_mapping = torch.where(live, slot_mapping, -1).contiguous()

writer, _, _ = _native_ops()
writer(
cache.view(torch.uint8),
x,
slot_mapping,
quant_group_size=64,
quant_mode="int8_bf16",
round_scale=False,
x_scale=1.0,
)


def int8_csa_metadata(num_heads_q, num_heads_kv, head_dim, **kwargs):
"""Return the CANN scheduler descriptor for a batch of INT8 CSA queries."""
_, metadata, _ = _native_ops()
return metadata(num_heads_q, num_heads_kv, head_dim, 1, rope_head_dim=64, **kwargs)


def int8_csa_attention(q, *, sinks=None, **kwargs):
"""Read both histories as signed INT8 records and return attention and LSE."""
_, _, attention = _native_ops()
if sinks is None:
sinks = torch.full(
(q.shape[1],), -torch.inf, dtype=torch.float32, device=q.device
)
else:
sinks = sinks.reshape(-1).float().contiguous()
return attention(q, 1, rope_head_dim=64, topk_value_mode=1, sinks=sinks, **kwargs)


@lru_cache(maxsize=None)
def check_int8_csa_support(device):
"""Verify the native 608-byte A16C8 contract on an Atlas A3 device."""
import acl

soc_name = acl.get_soc_name()
if not soc_name.startswith("Ascend910_93"):
raise ValueError(f"INT8 CSA requires Atlas A3, got {soc_name}.")

try:
win = torch.zeros((2, 16, 1, 608), dtype=torch.int8, device=device)
cmp = torch.zeros_like(win)
q = torch.zeros((1, 1, 512), dtype=torch.bfloat16, device=device)
kv = torch.zeros_like(q).view(1, 512)
kv[:, -1] = 2
slot = torch.tensor([16], dtype=torch.int32, device=device)
lens = torch.ones(1, dtype=torch.int32, device=device)
common = dict(
cu_seqlens_q=torch.tensor([0, 1], dtype=torch.int32, device=device),
seqused_ori_kv=lens,
seqused_cmp_kv=lens,
cmp_ratio=1,
ori_mask_mode=4,
cmp_mask_mode=3,
ori_win_left=127,
ori_win_right=0,
layout_q="TND",
layout_kv="PA_BBND",
)
int8_csa_write(win, kv, slot)
int8_csa_write(cmp, kv, slot)
page_table = lens.view(1, 1)
metadata = int8_csa_metadata(
1,
1,
512,
batch_size=1,
cmp_topk=16,
has_ori_kv=True,
has_cmp_kv=True,
**common,
)
indices = torch.full((1, 1, 16), -1, dtype=torch.int32, device=device)
indices[..., 0] = 0
out, _ = int8_csa_attention(
q,
ori_kv=win,
cmp_kv=cmp,
cmp_sparse_indices=indices,
ori_block_table=page_table,
cmp_block_table=page_table,
metadata=metadata,
sinks=torch.zeros(1, dtype=torch.float32, device=device),
softmax_scale=512**-0.5,
**common,
)
# Two value-2 rows and one sink have equal logits and yield 4/3.
if out.dtype != torch.bfloat16 or not isclose(
out[0, 0, -1].item(), 4 / 3, abs_tol=0.02
):
raise RuntimeError(
"The native INT8 CSA startup probe returned an invalid result."
)
except (ImportError, AttributeError, RuntimeError, ValueError) as exc:
raise RuntimeError(
f"INT8 CSA failed the native CANN probe on {soc_name}. "
"Use a matching sgl-kernel-npu wheel with the ops_transformer_int8_csa profile."
) from exc
61 changes: 61 additions & 0 deletions tests/python/sgl_kernel_npu/test_int8_csa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import unittest
from unittest.mock import Mock, patch

import torch
from sgl_kernel_npu.operators.attention import (
int8_csa,
int8_csa_attention,
int8_csa_metadata,
int8_csa_write,
)


class TestInt8Csa(unittest.TestCase):
def test_reserved_page_write_preserves_the_paged_storage(self):
backing = torch.zeros((3, 4 * 608 + 32), dtype=torch.int8)
cache = backing[:, :-32].view(3, 4, 1, 608)
slots = torch.tensor([-1, 0, 3, 4, 11, 12], dtype=torch.int32)
latent = torch.zeros((6, 1, 512), dtype=torch.bfloat16)
writer = Mock()
with patch.object(int8_csa, "_native_ops", return_value=(writer, None, None)):
int8_csa_write(cache, latent, slots, reserve_page_zero=True)

dest, rows, valid_slots = writer.call_args.args
self.assertEqual(dest.dtype, torch.uint8)
self.assertEqual(dest.data_ptr(), cache.data_ptr())
self.assertEqual(dest.stride(), cache.stride())
self.assertEqual(rows.shape, (6, 512))
self.assertEqual(valid_slots.tolist(), [-1, -1, -1, 4, 11, -1])

def test_empty_reserved_page_write_skips_dispatch(self):
with patch.object(int8_csa, "_native_ops") as ops:
int8_csa_write(
None,
torch.empty((0, 512), dtype=torch.bfloat16),
torch.empty(0, dtype=torch.int32),
reserve_page_zero=True,
)
ops.assert_not_called()

def test_attention_and_metadata_use_the_same_int8_format(self):
metadata, attention = Mock(), Mock()
q = torch.empty((1, 2, 512), dtype=torch.bfloat16)
with patch.object(
int8_csa, "_native_ops", return_value=(None, metadata, attention)
):
descriptor = int8_csa_metadata(2, 1, 512, cmp_ratio=2)
int8_csa_attention(q, metadata=descriptor, cmp_ratio=2)

metadata.assert_called_once_with(2, 1, 512, 1, rope_head_dim=64, cmp_ratio=2)
self.assertIs(attention.call_args.args[0], q)
self.assertEqual(attention.call_args.args[1], 1)
kwargs = attention.call_args.kwargs
self.assertIs(kwargs["metadata"], descriptor)
self.assertEqual(kwargs["rope_head_dim"], 64)
self.assertEqual(kwargs["topk_value_mode"], 1)
self.assertEqual(kwargs["sinks"].shape, (2,))
self.assertTrue(torch.isneginf(kwargs["sinks"]).all())


if __name__ == "__main__":
unittest.main()
20 changes: 20 additions & 0 deletions third_party/ops_transformer/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,26 @@ def stage_python(wheel, item, package):
'sys.modules["cann_ops_transformer.ops"]',
'sys.modules["{}.ops"]'.format(qualified),
)
if item.get("isolate_torch_namespace", False):
source = source.replace(
"torch.ops.cann_ops_transformer", "torch.ops." + name
)
source = source.replace('"cann_ops_transformer::', '"' + name + "::")
source = source.replace(
'Library("cann_ops_transformer",', 'Library("' + name + '",'
)
if path == destination / "op_builder/builder.py":
dispatcher, marker, jit = source.partition("\n def load(")
if not marker:
raise RuntimeError("Unexpected ops-transformer JIT builder layout")
# Keep schema names intact and separate JIT modules and locks.
source = (
dispatcher
+ "\n @property\n def _jit_name(self):\n"
+ f' return "{name}_" + self.name\n'
+ marker
+ jit.replace("self.name", "self._jit_name")
)
path.write_text(source)
# Do not discover globally installed entry points or import unrelated operators.
(destination / "__init__.py").write_text("from .ops import * # noqa: F403\n")
Expand Down
21 changes: 21 additions & 0 deletions third_party/profiles/cann-9.2.0/ops_transformer_int8_csa.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "sgl_ops_transformer_int8_csa",
"builder": "ops_transformer",
"repository": "https://gitcode.com/cann/ops-transformer.git",
"commit": "d90a9a94d6f6de79111ef7253361b5d898ee0983",
"ops": {
"arch22": [
"kv_compress_epilog",
"mixed_quant_sparse_flash_mla",
"mixed_quant_sparse_flash_mla_metadata"
]
},
"commands": [
["bash", "build.sh", "--pkg", "--soc={soc}", "--vendor_name={vendor_name}", "--ops={ops}", "-j{jobs}"],
["bash", "build.sh", "--torch_extension", "--ops=kv_compress_epilog,mixed_quant_sparse_flash_mla", "--vendor_name={vendor_name}"]
],
"has_aicpu": true,
"license": "LICENSE",
"isolate_torch_namespace": true,
"opt_in": true
}
Loading