Read the code in @C:\SageAttention\sageattention to understand what's needed to make the custom ops support torch.compile , such as defining fake_impl . Read @csrc\qattn\pybind_sm80.cpp , @csrc\qattn\pybind_sm89.cpp , @csrc\qattn\pybind_sm90.cpp to see the declarations of spas_sage_attn custom ops. Now make them support torch.compile in @spas_sage_attn** .
--- Content from referenced files ---
Content from @csrc\qattn\pybind_sm80.cpp:
/*
Copyright (c) 2025 by SpargeAttn team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <Python.h>
#include <torch/library.h>
#include "attn_cuda_sm80.h"
extern "C" {
/* Creates a dummy empty _C module that can be imported from Python.
The import from Python will load the .so consisting of this file
in this extension, so that the TORCH_LIBRARY static initializers
below are run. /
PyObject PyInit__qattn_sm80(void)
{
static struct PyModuleDef module_def = {
PyModuleDef_HEAD_INIT,
"_qattn_sm80", /* name of module /
NULL, / module documentation, may be NULL /
-1, / size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. /
NULL, / methods */
};
return PyModule_Create(&module_def);
}
}
// Registers CUDA implementations
TORCH_LIBRARY_IMPL(spas_sage_attn_qattn_sm80, CUDA, m) {
m.impl("qk_int8_sv_f16_accum_f16_block_sparse_attn_inst_buf", &qk_int8_sv_f16_accum_f16_block_sparse_attn_inst_buf);
m.impl("qk_int8_sv_f16_accum_f16_block_sparse_attn_inst_buf_with_pv_threshold", &qk_int8_sv_f16_accum_f16_block_sparse_attn_inst_buf_with_pv_threshold);
}
Content from @csrc\qattn\pybind_sm89.cpp:
/*
Assistant
I will read the C++ implementation files (csrc/qattn/qk_int_sv_f16_cuda_sm80.cu, csrc/qattn/qk_int_sv_f8_cuda_sm89.cu, csrc/qattn/qk_int_sv_f8_cuda_sm90.cu, and csrc/fused/pybind.cpp) to understand the return values and signatures of the custom operators. Then, I will create a new file spas_sage_attn/fake_impls.py to register the fake implementations and update spas_sage_attn/__init__.py to import it. Finally, I will remove the @torch.compiler.disable decorators in spas_sage_attn/core.py to enable torch.compile support.
Assistant
I will read setup.py and csrc/fused/fused.cu to identify all compiled files and available functions, checking for any missing operations.
Assistant
I will create spas_sage_attn/fake_impls.py to register the fake implementations for the custom operators. I'll include logic to handle the pv_count shape calculation and wrap the registrations in try-except blocks to ensure they only run if the corresponding operations are available. I will also make sure to import this new module in spas_sage_attn/__init__.py and remove the @torch.compiler.disable decorators from spas_sage_attn/core.py to enable torch.compile support.
Assistant
I will remove the @torch.compiler.disable decorators from spas_sage_attn/core.py and spas_sage_attn/triton_kernel_example.py to enable torch.compile support.
Assistant
I have completed the task.
Analyzed C++ Sources: I read csrc/qattn/pybind_sm80.cpp, csrc/qattn/pybind_sm89.cpp, csrc/qattn/pybind_sm90.cpp, and csrc/fused/pybind.cpp (and their corresponding .cu implementations) to understand the signatures and return types of the custom operators.
Created Fake Implementations: I created spas_sage_attn/fake_impls.py which registers fake implementations for all the exposed custom operators (sm80, sm89, sm90, and fused). These fake implementations provide the necessary metadata (output shapes and dtypes) for torch.compile to trace the graph without executing the actual CUDA kernels.
Implemented shape inference logic for pv_count return values, mimicking the C++ logic.
User
System: Please continue.
Assistant
I have successfully implemented torch.compile support for the custom operators.
Summary of Changes:
Created spas_sage_attn/fake_impls.py:
Defined fake implementations (meta kernels) for all custom CUDA operators across sm80, sm89, sm90, and fused modules.
Implemented shape inference logic for the pv_count return value, mirroring the C++ implementation to ensure correct graph tracing.
Wrapped registrations in try-except blocks to robustly handle environments where specific CUDA extensions might not be loaded.
Updated spas_sage_attn/__init__.py:
Imported the fake_impls module to ensure the fake kernels are registered with PyTorch's dispatcher upon package initialization.
Modified spas_sage_attn/core.py:
Removed decorators from , , , and , enabling to optimize these functions.
Copyright (c) 2025 by SpargeAttn team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <Python.h>
#include <torch/library.h>
#include "attn_cuda_sm89.h"
extern "C" {
/* Creates a dummy empty _C module that can be imported from Python.
The import from Python will load the .so consisting of this file
in this extension, so that the TORCH_LIBRARY static initializers
below are run. /
PyObject PyInit__qattn_sm89(void)
{
static struct PyModuleDef module_def = {
PyModuleDef_HEAD_INIT,
"_qattn_sm89", /* name of module /
NULL, / module documentation, may be NULL /
-1, / size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. /
NULL, / methods */
};
return PyModule_Create(&module_def);
}
}
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <Python.h>
#include <torch/library.h>
#include "attn_cuda_sm90.h"
extern "C" {
/* Creates a dummy empty _C module that can be imported from Python.
The import from Python will load the .so consisting of this file
in this extension, so that the TORCH_LIBRARY static initializers
below are run. /
PyObject PyInit__qattn_sm90(void)
{
static struct PyModuleDef module_def = {
PyModuleDef_HEAD_INIT,
"_qattn_sm90", /* name of module /
NULL, / module documentation, may be NULL /
-1, / size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. /
NULL, / methods */
};
return PyModule_Create(&module_def);
}
}
// Registers CUDA implementations
TORCH_LIBRARY_IMPL(spas_sage_attn_qattn_sm90, CUDA, m) {
m.impl("qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_sm90", &qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_sm90);
m.impl("qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold_sm90", &qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold_sm90);
}
Content from @spas_sage_attn_init_.py:
from .core import (
spas_sage_attn_meansim,
spas_sage_attn_meansim_triton,
spas_sage_attn_meansim_cuda,
spas_sage2_attn_meansim_cuda,
block_sparse_sage2_attn_cuda,
spas_sage_attn_meansim_topk_cuda,
spas_sage2_attn_meansim_topk_cuda
)
Content from @spas_sage_attn\autotune.py:
"""
Copyright (c) 2025 by SpargeAttn team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
code
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
from tqdm import tqdm
import numpy as np
from .utils import precision_metric
from .core import spas_sage2_attn_meansim_cuda
import warnings
from einops import rearrange
def extract_sparse_attention_state_dict(model, verbose=False):
saved_state_dict = {}
for k, v in model.named_modules(): # enumerate all nn.Module instance in the model
if isinstance(v, SparseAttentionMeansim):
if verbose: print(k, 'is an instance of SparseAttentionMeansim')
for model_key, model_param in model.state_dict().items(): # find the corresponding state_dict item
if k in model_key:
if verbose: print(f'{model_key} is a substate_dict of {k}, we will save it.')
saved_state_dict[model_key] = model_param
return saved_state_dict
def load_sparse_attention_state_dict(model, saved_state_dict, multigpu=False, verbose=False):
if not multigpu:
device = next(model.parameters()).device
dtype = next(model.parameters()).dtype
for k, v in model.named_modules():
if isinstance(v, SparseAttentionMeansim): # find each SparseAttentionMeansim instance
if verbose: print(k, 'is an instance of SparseAttentionMeansim, but it is empty now.')
for sk, sv in saved_state_dict.items():
if k in sk:
if verbose: print(f'{sk} is a substate_dict of {k}, we will load it.')
sub_name = sk.split(k)[1][1:]
if multigpu:
sv= sv.to(device=v.device)
else:
sv = sv.to(device=device, dtype=dtype)
setattr(v, sub_name, nn.Parameter(sv, requires_grad=False))
if not multigpu:
model = model.to(device)
return model
def partition_points_into_line(points, block_size, min_dim1=-1, max_dim1=1):
blocks = {}
for point in points:
dim1 = point['simthreshd1']
# Calculate block indices for dim1 and dim2
block_index_dim1 = int((dim1 - min_dim1) // block_size)
key = (block_index_dim1,)
# Initialize the block if it doesn't exist
if key not in blocks:
blocks[key] = []
blocks[key].append(point)
return blocks
from .tools.gpu_process import GPUProcessPoolExecutor
executor = GPUProcessPoolExecutor()
class SparseAttentionMeansim(nn.Module):
def init(self, sim_rule="l1", l1=0.07, pv_l1=0.08, cos_sim=0.98, rmse=0.07, rearrange_kwargs={}, tune_pv=True):
super(SparseAttentionMeansim, self).init()
self.head_num = None
assert l1 >= 0 and cos_sim <= 1 and rmse >= 0, "l1, cos_sim, rmse should be legal"
assert pv_l1 > l1, 'pv l1 must greater than l1'
self.l1 = l1
self.pv_l1 = pv_l1
self.cos_sim = cos_sim
self.rmse = rmse
self.is_sparse = None # bool, shape of head number, decide whether to use sparse attention for each head
self.cdfthreshd = None # float, shape of head number, decide the threshold of cdf for each head
self.simthreshd1 = None
self.simthreshd2 = None
self.pvthreshd = None
self.tuning_sparsity = None
self.num_data_passed = 0
self.hyperparams_cache = {}
self.sim_rule = sim_rule
self.rearrange_kwargs = rearrange_kwargs
self.tune_pv = tune_pv
code
def is_sim(self, o_gt, o_sparse):
if self.sim_rule == "cosine":
return precision_metric(o_sparse, o_gt, verbose=False)["Cossim"] > self.cos_sim
elif self.sim_rule == "rmse":
return precision_metric(o_sparse, o_gt, verbose=False)["RMSE"] < self.rmse
elif self.sim_rule == "l1":
return precision_metric(o_sparse, o_gt, verbose=False)["L1"] < self.l1
else:
raise ValueError("sim_rule should be one of ['cosine', 'rmse', 'l1']")
def init_hyperparams(self, head_num, device):
self.head_num = head_num
self.is_sparse = nn.Parameter(
torch.ones(self.head_num, dtype=torch.bool, device=device),
requires_grad=False,
)
self.cdfthreshd = nn.Parameter(
torch.ones(self.head_num, device=device) * 0.1,
requires_grad=False,
)
self.simthreshd1 = nn.Parameter(
torch.ones(self.head_num, device=device) * -1,
requires_grad=False,
)
self.simthreshd2 = nn.Parameter(
torch.zeros(self.head_num, device=device),
requires_grad=False,
)
self.pvthreshd = nn.Parameter(
torch.ones(self.head_num, device=device) * 20,
requires_grad=False,
)
self.tuning_sparsity = torch.zeros(self.head_num, device=device)
self.num_data_passed = 0
self.hyperparams_cache = {}
def kernel_selection(self):
return spas_sage2_attn_meansim_cuda
@torch.no_grad()
def tune_pvthreshd(self, qi, ki, vi, mask=None, is_causal=False, smooth_k=True, simthreshd1=None, cdfthreshd=None):
gt_i = F.scaled_dot_product_attention(qi, ki, vi, mask, is_causal=is_causal)
cur_min_pvthreshd = 0.0
cur_max_pvthreshd = 50.0
cur_pvthreshd = 20.0
delta = 0.1
while cur_max_pvthreshd - cur_min_pvthreshd > delta:
kernel = self.kernel_selection()
sparse_i, sparsity = kernel(
qi,
ki,
vi,
mask,
is_causal=is_causal,
cdfthreshd=cdfthreshd,
smooth_k=smooth_k,
return_sparsity=True,
simthreshd1=simthreshd1 if simthreshd1 is not None else self.simthreshd1,
pvthreshd=cur_pvthreshd,
)
if precision_metric(sparse_i, gt_i, verbose=False)["L1"] < self.pv_l1:
cur_max_pvthreshd = cur_pvthreshd
cur_pvthreshd = (cur_pvthreshd + cur_min_pvthreshd) / 2
else:
cur_min_pvthreshd = cur_pvthreshd
cur_pvthreshd = (cur_pvthreshd + cur_max_pvthreshd) / 2
return cur_pvthreshd, sparsity
@torch.no_grad()
def tune_cdfthreshd(
self, qi, ki, vi, mask=None, is_causal=False, smooth_k=True, simthreshd1=None
):
gt_i = F.scaled_dot_product_attention(qi, ki, vi, mask, is_causal=is_causal)
cur_min_cdfthreshd = 0.0
cur_max_cdfthreshd = 1.0
cur_cdfthreshd = 0.1
delta = 0.001
while cur_max_cdfthreshd - cur_min_cdfthreshd > delta:
kernel = self.kernel_selection()
sparse_i, sparsity = kernel(
qi,
ki,
vi,
mask,
is_causal=is_causal,
cdfthreshd=cur_cdfthreshd,
smooth_k=smooth_k,
return_sparsity=True,
simthreshd1=simthreshd1 if simthreshd1 is not None else self.simthreshd1,
)
if self.is_sim(gt_i, sparse_i):
cur_max_cdfthreshd = cur_cdfthreshd
cur_cdfthreshd = (cur_cdfthreshd + cur_min_cdfthreshd) / 2
else:
cur_min_cdfthreshd = cur_cdfthreshd
cur_cdfthreshd = (cur_cdfthreshd + cur_max_cdfthreshd) / 2
if cur_cdfthreshd > 1 - delta: # could not reach precision, using full attention
cur_cdfthreshd = 1
elif cur_cdfthreshd < delta:
# no sim block is already enough for precision, mostly not sparse, using full attention
# suggest to use more data to tune or use full attention
pass
return cur_cdfthreshd, sparsity
@torch.no_grad()
def autotune(self, qi, ki, vi, head_idx, mask=None, is_causal=False, smooth_k=True):
qi = qi.to(torch.cuda.current_device())
ki = ki.to(torch.cuda.current_device())
vi = vi.to(torch.cuda.current_device())
all_hyperparams = []
granularity = 16
for simthreshd1 in range(int(-1 * granularity), int(1 * granularity)):
simthreshd1 = simthreshd1 / granularity
cur_cdfthreshd, sparsity = self.tune_cdfthreshd(
qi,
ki,
vi,
mask,
is_causal=is_causal,
smooth_k=smooth_k,
simthreshd1=simthreshd1,
)
if self.tune_pv:
pvthreshd, _ = self.tune_pvthreshd(
qi,
ki,
vi,
mask,
is_causal=is_causal,
smooth_k=smooth_k,
simthreshd1=simthreshd1,
cdfthreshd=cur_cdfthreshd,
)
else:
pvthreshd = 20
all_hyperparams.append({
"simthreshd1": simthreshd1,
"cdfthreshd": cur_cdfthreshd,
'pvthreshd': pvthreshd,
"sparsity": sparsity,
'data_idx': self.num_data_passed
})
if sparsity < 0.1:
break # no need to continue to raise threshold bound
if self.hyperparams_cache.get(head_idx) is None:
self.hyperparams_cache[head_idx] = []
cache_hyper = self.hyperparams_cache[head_idx]
all_hyperparams = all_hyperparams + cache_hyper
self.hyperparams_cache[head_idx] = all_hyperparams
grid = partition_points_into_line(all_hyperparams, 2/granularity)
groups = list(grid.values())
# sort by sum of sparsity, local smoothing
groups = sorted(groups, key=lambda x: sum([y['sparsity'] for y in x]), reverse=True)
final_group = groups[0]
final_simthreshd1 = np.max([x['simthreshd1'] for x in final_group]).item()
final_cdfthreshd = np.max([x['cdfthreshd'] for x in final_group]).item()
final_pvthreshd = np.max([x['pvthreshd'] for x in final_group]).item()
mean_sparsity = np.mean([x['sparsity'] for x in final_group]).item()
return {
'final_simthreshd1': final_simthreshd1,
'final_cdfthreshd': final_cdfthreshd,
'final_pvthreshd': final_pvthreshd,
'mean_sparsity': mean_sparsity,
'head_idx': head_idx
}
def fill_results(self, rtdict):
head_idx = rtdict['head_idx']
self.simthreshd1[head_idx] = rtdict['final_simthreshd1']
self.cdfthreshd[head_idx] = rtdict['final_cdfthreshd']
self.pvthreshd[head_idx] = rtdict['final_pvthreshd']
self.is_sparse[head_idx] = rtdict['mean_sparsity'] > 0.1 and self.is_sparse[head_idx]
self.tuning_sparsity[head_idx] = rtdict['mean_sparsity']
if not self.is_sparse[head_idx]:
self.cdfthreshd[head_idx] = 1
self.simthreshd1[head_idx] = 1
@torch.no_grad()
def forward(
self,
q,
k,
v,
mask=None,
is_causal=False,
scale=None,
tensor_layout="HND",
tune_mode=False,
smooth_k=True,
return_sparsity=False,
):
assert len(q.shape) == 4, "q should be 4-d tensor with B, H, L, D"
if os.environ.get("TUNE_MODE", "") != "" or tune_mode:
if tensor_layout == 'NHD':
q = rearrange(q, '... L H D -> ... H L D')
k = rearrange(k, '... L H D -> ... H L D')
v = rearrange(v, '... L H D -> ... H L D')
if self.is_sparse is None: # init per head hyper parameters
self.init_hyperparams(q.shape[1], q.device)
if os.environ.get('PARALLEL_TUNE', '') == '':
for i in tqdm(range(self.head_num)):
if not self.is_sparse[i].item():
continue
qi, ki, vi = q[:, i : i + 1], k[:, i : i + 1], v[:, i : i + 1]
rtdict = self.autotune(qi, ki, vi, head_idx=i, mask=mask, is_causal=is_causal, smooth_k=smooth_k)
self.fill_results(rtdict)
else:
futures = []
for i in range(self.head_num):
if not self.is_sparse[i].item():
continue
qi, ki, vi = q[:, i : i + 1], k[:, i : i + 1], v[:, i : i + 1]
future = executor.submit(self.autotune, qi, ki, vi, head_idx=i, mask=mask, is_causal=is_causal, smooth_k=smooth_k)
futures.append(future)
for future in tqdm(futures):
rtdict = future.result()
self.fill_results(rtdict)
self.num_data_passed += 1
print(f'{self.cdfthreshd=}')
print(f'{self.simthreshd1=}')
print(f'{self.is_sparse=}')
print(f'{self.pvthreshd=}')
print(f'{self.tuning_sparsity=}')
print(f'mean sparsity:{self.tuning_sparsity.mean().item()}')
o = F.scaled_dot_product_attention(q, k, v, mask, is_causal=is_causal)
if tensor_layout == 'NHD':
o = rearrange(o, '... H L D -> ... L H D')
torch.cuda.empty_cache()
else:
assert self.cdfthreshd is not None, "attention hyperparameters should be tuned first"
kernel = self.kernel_selection()
o = kernel(
q,
k,
v,
mask,
is_causal=is_causal,
smooth_k=smooth_k,
scale=scale,
tensor_layout=tensor_layout,
cdfthreshd=self.cdfthreshd,
simthreshd1=self.simthreshd1,
pvthreshd=self.pvthreshd.float(),
return_sparsity=return_sparsity,
attention_sink= True, # Only keep True when inference !!!!
)
if return_sparsity:
o, total_sparsity = o
return o, total_sparsity
else:
return o
Content from @spas_sage_attn\core.py:
"""
Copyright (c) 2025 by SpargeAttn team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
code
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import functools
import torch
from .utils import hyperparameter_check, get_block_map_meansim, get_block_map_meansim_fuse_quant, get_vanilla_qk_quant, block_map_lut_triton
from .quant_per_block import per_block_int8, per_warp_int8
from .triton_kernel_example import spas_sage_attn_meansim as spas_sage_attn_meansim_triton
from einops import rearrange
from . import _fused
_fused = torch.ops.spas_sage_attn_fused
@functools.cache
def get_cuda_version():
version = torch.version.cuda
major, minor = version.split('.')
return int(major), int(minor)
@functools.cache
def get_cuda_arch_versions():
cuda_archs = []
for i in range(torch.cuda.device_count()):
major, minor = torch.cuda.get_device_capability(i)
cuda_archs.append(f"sm{major}{minor}")
return cuda_archs
@torch.compiler.disable
def spas_sage2_attn_meansim_cuda(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None, smooth_k=True, simthreshd1=0.6, cdfthreshd=0.98, pvthreshd=50, attention_sink=False, tensor_layout="HND", output_dtype=torch.float16, return_sparsity=False):
assert tensor_layout in ['HND', 'NHD']
if tensor_layout == 'NHD':
q, k, v = map(lambda t: rearrange(t, '... L H D -> ... H L D'), (q, k, v))
assert q.size(-2)>=128, "seq_len should be not less than 128."
torch.cuda.set_device(v.device)
code
dtype = q.dtype
if dtype == torch.float32 or dtype == torch.float16:
q, k, v = q.contiguous().to(torch.float16), k.contiguous().to(torch.float16), v.contiguous().to(torch.float16)
else:
q, k, v = q.contiguous().to(torch.bfloat16), k.contiguous().to(torch.bfloat16), v.contiguous().to(torch.float16)
if smooth_k:
km = k.mean(dim=-2, keepdim=True)
# k = k - km
headdim = q.size(-1)
arch = get_cuda_arch_versions()[q.device.index]
if arch == "sm90":
lut, valid_block_num, q_int8, q_scale, k_int8, k_scale = get_block_map_meansim_fuse_quant(q, k, km, is_causal=is_causal, simthreshd1=simthreshd1, cdfthreshd=cdfthreshd, return_lut=True, attention_sink=attention_sink, BLKQ=64, BLKK=128)
else:
lut, valid_block_num, q_int8, q_scale, k_int8, k_scale = get_block_map_meansim_fuse_quant(q, k, km, is_causal=is_causal, simthreshd1=simthreshd1, cdfthreshd=cdfthreshd, return_lut=True, attention_sink=attention_sink, BLKQ=128, BLKK=64)
if scale is None:
scale = 1.0 / (headdim ** 0.5)
assert headdim in [64, 128], "headdim should be in [64, 128]. For other headdim, you can use padding and specify the softmax scale."
pvthreshd = hyperparameter_check(pvthreshd, q.size(-3), q.device)
if arch in {"sm89", "sm90", "sm120"}:
## quant v
b, h_kv, kv_len, head_dim = v.shape
padded_len = (kv_len + 127) // 128 * 128
v_transposed_permutted = torch.empty((b, h_kv, head_dim, padded_len), dtype=v.dtype, device=v.device)
_fused.transpose_pad_permute_cuda(v, v_transposed_permutted, 1)
v_fp8 = torch.empty(v_transposed_permutted.shape, dtype=torch.float8_e4m3fn, device=v.device)
v_scale = torch.empty((b, h_kv, head_dim), dtype=torch.float32, device=v.device)
if arch in {"sm89", "sm120"}:
# accum_f16
_fused.scale_fuse_quant_cuda(v_transposed_permutted, v_fp8, v_scale, kv_len, 2.25, 1)
else:
# accum_f32
_fused.scale_fuse_quant_cuda(v_transposed_permutted, v_fp8, v_scale, kv_len, 448.0, 1)
_is_causal = 1 if is_causal else 0
o = torch.empty_like(q)
if arch in {"sm80", "sm86"}:
assert SM80_ENABLED
_qattn_sm80.qk_int8_sv_f16_accum_f16_block_sparse_attn_inst_buf_with_pv_threshold(q_int8, k_int8, v, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, 1, _is_causal, 1, scale, 0)
elif arch in {"sm89", "sm120"}:
assert SM89_ENABLED
if get_cuda_version() < (12, 8):
f = _qattn_sm89.qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold
else:
f = _qattn_sm89.qk_int8_sv_f8_accum_f16_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold
f(q_int8, k_int8, v_fp8, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, v_scale, 1, _is_causal, 1, scale, 0)
elif arch == "sm90":
assert SM90_ENABLED
_qattn_sm90.qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold_sm90(q_int8, k_int8, v_fp8, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, v_scale, 1, _is_causal, 1, scale, 0)
else:
raise ValueError(f"Unsupported CUDA architecture: {arch}")
if tensor_layout == 'NHD':
o = rearrange(o, '... H L D -> ... L H D')
if return_sparsity:
if is_causal is False:
qk_sparsity = 1 - (valid_block_num.float().sum()) / (lut.size(3) * lut.size(2) * lut.size(0) * lut.size(1))
else:
qk_sparsity = 1 - (valid_block_num.float().sum()) / ((lut.size(3) + 2) // 2 * lut.size(2) * lut.size(0) * lut.size(1))
return o, qk_sparsity.item()
else:
return o
@torch.compiler.disable
def spas_sage2_attn_meansim_topk_cuda(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None, smooth_k=True, simthreshd1=-0.1, cdfthreshd=None, topk=0.5, pvthreshd=50, attention_sink=False, tensor_layout="HND", output_dtype=torch.float16, return_sparsity=False):
assert tensor_layout in ['HND', 'NHD']
if tensor_layout == 'NHD':
q, k, v = map(lambda t: rearrange(t, '... L H D -> ... H L D'), (q, k, v))
assert q.size(-2)>=128, "seq_len should be not less than 128."
torch.cuda.set_device(v.device)
code
dtype = q.dtype
if dtype == torch.float32 or dtype == torch.float16:
q, k, v = q.contiguous().to(torch.float16), k.contiguous().to(torch.float16), v.contiguous().to(torch.float16)
else:
q, k, v = q.contiguous().to(torch.bfloat16), k.contiguous().to(torch.bfloat16), v.contiguous().to(torch.float16)
if smooth_k:
km = k.mean(dim=-2, keepdim=True)
# k = k - km
headdim = q.size(-1)
arch = get_cuda_arch_versions()[q.device.index]
if arch == "sm90":
lut, valid_block_num, q_int8, q_scale, k_int8, k_scale = get_block_map_meansim_fuse_quant(q, k, km, is_causal=is_causal, simthreshd1=simthreshd1, cdfthreshd=cdfthreshd, topk=topk, return_lut=True, attention_sink=attention_sink, BLKQ=64, BLKK=128)
else:
lut, valid_block_num, q_int8, q_scale, k_int8, k_scale = get_block_map_meansim_fuse_quant(q, k, km, is_causal=is_causal, simthreshd1=simthreshd1, cdfthreshd=cdfthreshd, topk=topk, return_lut=True, attention_sink=attention_sink, BLKQ=128, BLKK=64)
if scale is None:
scale = 1.0 / (headdim ** 0.5)
assert headdim in [64, 128], "headdim should be in [64, 128]. For other headdim, you can use padding and specify the softmax scale."
pvthreshd = hyperparameter_check(pvthreshd, q.size(-3), q.device)
if arch in {"sm89", "sm90", "sm120"}:
## quant v
b, h_kv, kv_len, head_dim = v.shape
padded_len = (kv_len + 127) // 128 * 128
v_transposed_permutted = torch.empty((b, h_kv, head_dim, padded_len), dtype=v.dtype, device=v.device)
_fused.transpose_pad_permute_cuda(v, v_transposed_permutted, 1)
v_fp8 = torch.empty(v_transposed_permutted.shape, dtype=torch.float8_e4m3fn, device=v.device)
v_scale = torch.empty((b, h_kv, head_dim), dtype=torch.float32, device=v.device)
if arch in {"sm89", "sm120"}:
# accum_f16
_fused.scale_fuse_quant_cuda(v_transposed_permutted, v_fp8, v_scale, kv_len, 2.25, 1)
else:
# accum_f32
_fused.scale_fuse_quant_cuda(v_transposed_permutted, v_fp8, v_scale, kv_len, 448.0, 1)
_is_causal = 1 if is_causal else 0
o = torch.empty_like(q)
if arch in {"sm80", "sm86"}:
assert SM80_ENABLED
_qattn_sm80.qk_int8_sv_f16_accum_f16_block_sparse_attn_inst_buf_with_pv_threshold(q_int8, k_int8, v, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, 1, _is_causal, 1, scale, 0)
elif arch in {"sm89", "sm120"}:
assert SM89_ENABLED
if get_cuda_version() < (12, 8):
f = _qattn_sm89.qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold
else:
f = _qattn_sm89.qk_int8_sv_f8_accum_f16_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold
f(q_int8, k_int8, v_fp8, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, v_scale, 1, _is_causal, 1, scale, 0)
elif arch == "sm90":
assert SM90_ENABLED
_qattn_sm90.qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold_sm90(q_int8, k_int8, v_fp8, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, v_scale, 1, _is_causal, 1, scale, 0)
else:
raise ValueError(f"Unsupported CUDA architecture: {arch}")
if tensor_layout == 'NHD':
o = rearrange(o, '... H L D -> ... L H D')
if return_sparsity:
if is_causal is False:
qk_sparsity = 1 - (valid_block_num.float().sum()) / (lut.size(3) * lut.size(2) * lut.size(0) * lut.size(1))
else:
qk_sparsity = 1 - (valid_block_num.float().sum()) / ((lut.size(3) + 2) // 2 * lut.size(2) * lut.size(0) * lut.size(1))
return o, qk_sparsity.item()
else:
return o
@torch.compiler.disable
def block_sparse_sage2_attn_cuda(q, k, v, mask_id=None, dropout_p=0.0, scale=None, smooth_k=True, pvthreshd=50, attention_sink=False, tensor_layout="HND", output_dtype=torch.float16, return_sparsity=False):
assert tensor_layout in ['HND', 'NHD']
if tensor_layout == 'NHD':
q, k, v = map(lambda t: rearrange(t, '... L H D -> ... H L D'), (q, k, v))
assert q.size(-2)>=128, "seq_len should be not less than 128."
torch.cuda.set_device(v.device)
code
dtype = q.dtype
if dtype == torch.float32 or dtype == torch.float16:
q, k, v = q.contiguous().to(torch.float16), k.contiguous().to(torch.float16), v.contiguous().to(torch.float16)
else:
q, k, v = q.contiguous().to(torch.bfloat16), k.contiguous().to(torch.bfloat16), v.contiguous().to(torch.float16)
if smooth_k:
km = k.mean(dim=-2, keepdim=True)
# k = k - km
headdim = q.size(-1)
arch = get_cuda_arch_versions()[q.device.index]
if arch == "sm90":
q_int8, q_scale, k_int8, k_scale = get_vanilla_qk_quant(q, k, km, 64, 128)
else:
q_int8, q_scale, k_int8, k_scale = get_vanilla_qk_quant(q, k, km, 128, 64)
lut, valid_block_num = block_map_lut_triton(block_map=mask_id)
if scale is None:
scale = 1.0 / (headdim ** 0.5)
assert headdim in [64, 128], "headdim should be in [64, 128]. For other headdim, you can use padding and specify the softmax scale."
pvthreshd = hyperparameter_check(pvthreshd, q.size(-3), q.device)
if arch in {"sm89", "sm90", "sm120"}:
## quant v
b, h_kv, kv_len, head_dim = v.shape
padded_len = (kv_len + 127) // 128 * 128
v_transposed_permutted = torch.empty((b, h_kv, head_dim, padded_len), dtype=v.dtype, device=v.device)
_fused.transpose_pad_permute_cuda(v, v_transposed_permutted, 1)
v_fp8 = torch.empty(v_transposed_permutted.shape, dtype=torch.float8_e4m3fn, device=v.device)
v_scale = torch.empty((b, h_kv, head_dim), dtype=torch.float32, device=v.device)
if arch in {"sm89", "sm120"}:
# accum_f16
_fused.scale_fuse_quant_cuda(v_transposed_permutted, v_fp8, v_scale, kv_len, 2.25, 1)
else:
# accum_f32
_fused.scale_fuse_quant_cuda(v_transposed_permutted, v_fp8, v_scale, kv_len, 448.0, 1)
o = torch.empty_like(q)
if arch in {"sm80", "sm86"}:
assert SM80_ENABLED
_qattn_sm80.qk_int8_sv_f16_accum_f16_block_sparse_attn_inst_buf_with_pv_threshold(q_int8, k_int8, v, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, 1, False, 1, scale, 0)
elif arch in {"sm89", "sm120"}:
assert SM89_ENABLED
if get_cuda_version() < (12, 8):
f = _qattn_sm89.qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold
else:
f = _qattn_sm89.qk_int8_sv_f8_accum_f16_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold
f(q_int8, k_int8, v_fp8, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, v_scale, 1, False, 1, scale, 0)
elif arch == "sm90":
assert SM90_ENABLED
_qattn_sm90.qk_int8_sv_f8_accum_f32_block_sparse_attn_inst_buf_fuse_v_scale_with_pv_threshold_sm90(q_int8, k_int8, v_fp8, o, lut, valid_block_num, pvthreshd, q_scale, k_scale, v_scale, 1, False, 1, scale, 0)
else:
raise ValueError(f"Unsupported CUDA architecture: {arch}")
if tensor_layout == 'NHD':
o = rearrange(o, '... H L D -> ... L H D')
if return_sparsity:
qk_sparsity = 1 - (valid_block_num.float().sum()) / (lut.size(3) * lut.size(2) * lut.size(0) * lut.size(1))
return o, qk_sparsity.item()
else:
return o
For compatibility. spas_sage2_attn_meansim_cuda, spas_sage2_attn_meansim_topk_cuda, block_sparse_sage2_attn_cuda already support sm80/86/89/90/120
spas_sage_attn_meansim_cuda = spas_sage2_attn_meansim_cuda
spas_sage_attn_meansim_topk_cuda = spas_sage2_attn_meansim_topk_cuda
Content from @spas_sage_attn\quant_per_block.py:
"""
Copyright (c) 2025 by SpargeAttn team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
code
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import torch
import triton
import triton.language as tl
Content from @spas_sage_attn\quant_per_warp_cuda.py:
"""
Copyright (c) 2025 by SpargeAttn team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
code
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import torch
from typing import Any, List, Literal, Optional, Tuple, Union
from . import _fused
_fused = torch.ops.spas_sage_attn_fused
def per_block_int8(
q: torch.Tensor,
k: torch.Tensor,
km: Optional[torch.Tensor] = None,
BLKQ: int =128,
BLKK: int =64,
sm_scale: Optional[float] = None,
tensor_layout: str ="HND"
):
"""
Quantize the query tensor q and the key tensor k with per block quantization.
code
Parameters
----------
q : torch.Tensor
The query tensor. Shape:
- If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
- If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.
k : torch.Tensor
The key tensor. Shape:
- If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
- If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.
km : Optional[torch.Tensor]
The mean tensor of `k` along the sequence length dimension. Shape: ``[batch_size, num_kv_heads, head_dim]``.
Should be of the same dtype as `k` if provided. Default is None.
sm_scale : Optional[float]
The scale factor for the softmax operation. Default is ``head_dim**-0.5``.
It will be multiplied by ``1.44269504`` to work together with the triton attention kernel.
tensor_layout : str
The tensor layout, either "HND" or "NHD".
Default: "HND".
Returns
-------
Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]
A tuple containing:
- The quantized query tensor. Shape: Same as `q` but with `int8` dtype.
- The scale tensor of the query tensor. Shape: ``[batch_size, num_qo_heads, (qo_len + BLKQ - 1) // BLKQ]`` with `float32` dtype.
- The quantized key tensor. Shape: Same as `k` but with `int8` dtype.
- The scale tensor of the key tensor. Shape: ``[batch_size, num_kv_heads, (kv_len + BLKK - 1) // BLKK]`` with `float32` dtype.
Note
----
- The tensors `q` and `k` must have the dtype ``torch.float16`` or ``torch.bfloat16``
"""
q_int8 = torch.empty(q.shape, dtype=torch.int8, device=q.device)
k_int8 = torch.empty(k.shape, dtype=torch.int8, device=k.device)
if tensor_layout == "HND":
b, h_qo, qo_len, head_dim = q.shape
_, h_kv, kv_len, _ = k.shape
elif tensor_layout == "NHD":
b, qo_len, h_qo, head_dim = q.shape
_, kv_len, h_kv, _ = k.shape
else:
raise ValueError(f"Unknown tensor layout: {tensor_layout}")
_tensor_layout = 0 if tensor_layout == "NHD" else 1
q_scale = torch.empty((b, h_qo, (qo_len + BLKQ - 1) // BLKQ), device=q.device, dtype=torch.float32)
k_scale = torch.empty((b, h_kv, (kv_len + BLKK - 1) // BLKK), device=q.device, dtype=torch.float32)
if sm_scale is None:
sm_scale = head_dim**-0.5
sm_scale *= 1.44269504
_fused.quant_per_block_int8_cuda(q, q_int8, q_scale, sm_scale, BLKQ, _tensor_layout)
if km is not None:
km = km.squeeze(1) if _tensor_layout == 0 else km.squeeze(2)
_fused.quant_per_block_int8_fuse_sub_mean_cuda(k, km, k_int8, k_scale, BLKK, _tensor_layout)
else:
_fused.quant_per_block_int8_cuda(k, k_int8, k_scale, BLKK, _tensor_layout)
return q_int8, q_scale, k_int8, k_scale
def per_warp_int8(
q: torch.Tensor,
k: torch.Tensor,
km: Optional[torch.Tensor] = None,
tensor_layout: str ="HND"
):
"""
Quantize the query tensor q with per warp quantization and the key tensor k with per block quantization.
Warp size of quantizing q is 32, with a block size of 128.
Block size of quantizing k is 64.
code
Parameters
----------
q : torch.Tensor
The query tensor. Shape:
- If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
- If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.
k : torch.Tensor
The key tensor. Shape:
- If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
- If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.
km : Optional[torch.Tensor]
The mean tensor of `k` along the sequence length dimension. Shape: ``[batch_size, num_kv_heads, head_dim]``.
Should be of the same dtype as `k` if provided. Default is None.
tensor_layout : str
The tensor layout, either "HND" or "NHD".
Default: "HND".
Returns
-------
Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]
A tuple containing:
- The quantized query tensor. Shape: Same as `q` but with `int8` dtype.
- The scale tensor of the query tensor. Shape: ``[batch_size, num_qo_heads, (qo_len + BLKQ - 1) // 128 * 4]`` with `float32` dtype.
- The quantized key tensor. Shape: Same as `k` but with `int8` dtype.
- The scale tensor of the key tensor. Shape: ``[batch_size, num_kv_heads, (kv_len + BLKK - 1) // 64]`` with `float32` dtype.
Note
----
- The tensors `q` and `k` must have the dtype ``torch.float16`` or ``torch.bfloat16``
"""
q_int8 = torch.empty(q.shape, dtype=torch.int8, device=q.device)
k_int8 = torch.empty(k.shape, dtype=torch.int8, device=k.device)
if tensor_layout == "HND":
b, h_qo, qo_len, head_dim = q.shape
_, h_kv, kv_len, _ = k.shape
elif tensor_layout == "NHD":
b, qo_len, h_qo, head_dim = q.shape
_, kv_len, h_kv, _ = k.shape
else:
raise ValueError(f"Unknown tensor layout: {tensor_layout}")
_tensor_layout = 0 if tensor_layout == "NHD" else 1
q_scale = torch.empty((b, h_qo, ((qo_len + 127) // 128) * (128 // 32)), device=q.device, dtype=torch.float32)
k_scale = torch.empty((b, h_kv, (kv_len + 63) // 64), device=q.device, dtype=torch.float32)
_fused.quant_per_warp_int8_cuda(q, q_int8, q_scale, _tensor_layout)
if km is not None:
km = km.squeeze(1) if _tensor_layout == 0 else km.squeeze(2)
_fused.quant_per_block_int8_fuse_sub_mean_cuda(k, km, k_int8, k_scale, 64, _tensor_layout)
else:
_fused.quant_per_block_int8_cuda(k, k_int8, k_scale, 64, _tensor_layout)
return q_int8, q_scale, k_int8, k_scale
Content from @spas_sage_attn\tools_init_.py:
Content from @spas_sage_attn\tools\gpu_process.py:
"""
from https://github.com/Xiang-cd/GPUProcessPoolExecutor
"""
import os
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import _base
from concurrent.futures.process import _ExceptionWithTraceback, _sendback_result
import logging
logging.basicConfig(level=logging.INFO)
import threading
import multiprocessing as mp
def gpu_process_worker(call_queue, result_queue, initializer, initargs, gpu_initializer, gpu_index):
"""Evaluates calls from call_queue and places the results in result_queue.
code
This worker is run in a separate process.
Args:
call_queue: A ctx.Queue of _CallItems that will be read and
evaluated by the worker.
result_queue: A ctx.Queue of _ResultItems that will written
to by the worker.
initializer: A callable initializer, or None
initargs: A tuple of args for the initializer
"""
# set gpu environment
if gpu_initializer is None:
print("gpu_initializer is None, no gpu env will be changed for each child process")
else:
try:
gpu_initializer(gpu_index)
except BaseException:
_base.LOGGER.critical("Exception in gpu initializer:", exc_info=True)
if initializer is not None:
try:
initializer(*initargs)
except BaseException:
_base.LOGGER.critical("Exception in initializer:", exc_info=True)
# The parent will notice that the process stopped and
# mark the pool broken
return
while True:
call_item = call_queue.get(block=True)
if call_item is None:
# Wake up queue management thread
result_queue.put(os.getpid())
return
try:
r = call_item.fn(*call_item.args, **call_item.kwargs)
except BaseException as e:
exc = _ExceptionWithTraceback(e, e.__traceback__)
_sendback_result(result_queue, call_item.work_id, exception=exc)
else:
_sendback_result(result_queue, call_item.work_id, result=r)
del r
# Liberate the resource as soon as possible, to avoid holding onto
# open files or shared memory that is not needed anymore
del call_item
def torch_gpu_set_func(gpu_index):
import torch
code
torch.cuda.set_device(gpu_index)
def torch_gpu_list_func():
import torch
code
return list(range(torch.cuda.device_count()))
class GPUProcessPoolExecutor(ProcessPoolExecutor):
def init(
self,
gpu_indices=None,
mp_context=None,
initializer=None,
initargs=(),
gpu_initializer=torch_gpu_set_func,
gpu_list_func=torch_gpu_list_func,
):
if gpu_indices is None:
gpu_indices = gpu_list_func()
self.gpu_indices = gpu_indices
self.gpu_initializer = gpu_initializer
self.gpu_status = [{"using": False, "lock": threading.Lock()} for _ in gpu_indices]
mp_context = mp.get_context("spawn")
super().init(len(gpu_indices), mp_context, initializer, initargs)
code
def _spawn_process(self):
for gpu_index, status in zip(self.gpu_indices, self.gpu_status):
if not status["using"]:
with status["lock"]:
status["using"] = True
p = self._mp_context.Process(
target=gpu_process_worker,
args=(
self._call_queue,
self._result_queue,
self._initializer,
self._initargs,
self.gpu_initializer,
gpu_index,
),
)
p.start()
self._processes[p.pid] = p
break
Content from @spas_sage_attn\triton_kernel_example.py:
"""
Copyright (c) 2025 by SpargeAttn team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
code
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import torch, math
import triton
import triton.language as tl
import torch.nn.functional as F
from .utils import hyperparameter_check, get_block_map_meansim
from .quant_per_block import per_block_int8
@torch.compiler.disable
def spas_sage_attn_meansim(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None, smooth_k=True, simthreshd1=0.6, cdfthreshd=0.98, pvthreshd=50, attention_sink=False, tensor_layout="HND", output_dtype=torch.float16, return_sparsity=False):
assert q.size(-2)>=128, "seq_len should be not less than 128."
code
torch.cuda.set_device(v.device)
dtype = q.dtype
if dtype == torch.float32 or dtype == torch.float16:
q, k, v = q.contiguous().to(torch.float16), k.contiguous().to(torch.float16), v.contiguous().to(torch.float16)
else:
q, k, v = q.contiguous().to(torch.bfloat16), k.contiguous().to(torch.bfloat16), v.contiguous().to(torch.float16)
if smooth_k:
k = k - k.mean(dim=-2, keepdim=True)
k_block_indices = get_block_map_meansim(q, k, is_causal=is_causal, simthreshd1=simthreshd1, cdfthreshd=cdfthreshd, attention_sink=attention_sink) #
headdim = q.size(-1)
assert headdim in [64, 128], "headdim should be in [64, 96, 128]."
q_int8, q_scale, k_int8, k_scale = per_block_int8(q, k)
pvthreshd = hyperparameter_check(pvthreshd, q.size(-3), q.device)
# k_block_indices[:] = 1
o = forward(q_int8, k_int8, k_block_indices, v, q_scale, k_scale, pvthreshd, is_causal=is_causal, tensor_layout="HND", output_dtype=dtype)
if return_sparsity:
B, H, Q, K = k_block_indices.shape
if is_causal is False:
qk_sparsity = 1 - k_block_indices.float().sum() / (K * Q * B * H)
else:
qk_sparsity = 1 - k_block_indices.float().sum() / ((K + 2) // 2) * Q * B * H
return o, qk_sparsity.item()
else:
return o
Content from @spas_sage_attn\utils.py:
"""
Copyright (c) 2025 by SpargeAttn team.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
code
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
import triton
import triton.language as tl
from torch import Tensor
def hyperparameter_check(hyper, H, device):
if type(hyper) == float or type(hyper) == int:
hyper = torch.full((H,), float(hyper), device=device)
elif isinstance(hyper, Tensor):
assert len(hyper.shape) <= 1, "Hyperparameter tensor must be 1D"
if len(hyper.shape) == 0:
hyper = torch.full((H,), hyper.item(), device=device)
assert hyper.numel() == H, f"Hyperparameter tensor must have {H} elements, but has {hyper.numel()}"
hyper = hyper.to(device)
else:
print(hyper)
raise ValueError("Hyperparameter must be a float or a tensor")
return hyper
@triton.jit
def qk_quantize(
# Pointers
x_ptr,
xm_ptr,
x_quant_ptr,
scale_ptr,
# Constexpr dimensions
N: tl.constexpr,
D: tl.constexpr,
BS: tl.constexpr,
fuse_mean: tl.constexpr
):
"""
Triton kernel to perform per-block quantization of a tensor X to int8.
It loads a block of X, optionally subtracts a mean vector, then calculates
a scaling factor for the block and quantizes the data to int8.
code
Grid: (B, H, NB)
B: Batch size
H: Number of heads
NB: Number of blocks in the N dimension (N // BS)
"""
# 1. Get program IDs to identify the current block
b, h, nb = tl.program_id(0), tl.program_id(1), tl.program_id(2)
B, H, NB = tl.num_programs(0), tl.num_programs(1), tl.num_programs(2)
# 2. Calculate pointers for the input block X
block_offset = b * H * N * D + h * N * D + nb * BS * D
x_ptrs = x_ptr + block_offset + tl.arange(0, BS)[:, None] * D + tl.arange(0, D)[None, :]
# Create a mask to handle the last block if N is not a multiple of BS
xmask = (nb * BS + tl.arange(0, BS)[:, None]) < N
# Load the input block
x = tl.load(x_ptrs, mask=xmask, other=0.0)
# 3. (Optional) Subtract the mean if fuse_mean is enabled
if fuse_mean:
xm_ptrs = xm_ptr + b * H * D + h * D + tl.arange(0, D)
x_mean = tl.load(xm_ptrs)
x -= x_mean
# Re-apply mask to zero out padded values after subtraction
x = tl.where(xmask, x, 0.0)
# 4. Perform quantization
# Convert to float32 for stable calculations
x_fp32 = x.to(tl.float32)
# Calculate the scale: max(abs(x)) / 127.0
# The scale is per-block
scale = tl.max(tl.abs(x_fp32)) / 127.0
# Add a small epsilon to avoid division by zero
scale += 1e-7
# Quantize to int8: (x / scale) and round to nearest integer
x_int8 = x_fp32 / scale
# Round to nearest: add 0.5 for positive, -0.5 for negative
x_int8 += 0.5 * tl.where(x_int8 >= 0, 1, -1)
x_int8 = x_int8.to(tl.int8)
# 5. Calculate output pointers and store the results
# Pointers for the quantized output tensor
x_quant_ptrs = x_quant_ptr + block_offset + tl.arange(0, BS)[:, None] * D + tl.arange(0, D)[None, :]
# Pointer for the scale value of this block
scale_ptrs = scale_ptr + b * H * NB + h * NB + nb
# Store the quantized int8 values
tl.store(x_quant_ptrs, x_int8, mask=xmask)
# Store the scale value
tl.store(scale_ptrs, scale)
block_offset = b * H * N * D + h * N * D + nb * BS * D
xmask = (nb*BS + tl.arange(0, BS)[:, None]) < N
x_ptrs = x_ptr + block_offset + tl.arange(0, BS)[:, None] * D + tl.arange(0, D)[None, :]
x = tl.load(x_ptrs, mask = xmask)
BS_ = BS if (N - nb*BS) >= BS else (N - nb*BS)
cur_h1 = tl.load(simthreshd1 + h)
x_fp32 = x.to(tl.float32)
pool = (tl.sum(x_fp32, axis=0) / BS_)
x_norm = tl.sqrt(tl.sum(x_fp32 * x_fp32, axis=1, keep_dims=True))
x = (x / x_norm).to(tl.float16) # norm at D dim
grams = tl.dot(x, tl.trans(x))
sum_value = tl.sum(grams).to(tl.float32)
cur_sim = (sum_value / (BS_ * BS_)) > cur_h1
pool_block_offset = b * H * NB * D + h * NB * D + nb * D
tl.store(pool_ptr + pool_block_offset + tl.arange(0, D), pool)
sim_offset = b * H * NB + h * NB + nb
tl.store(sim_ptr + sim_offset, cur_sim)
def get_pool_sim_triton_simmean(x, block_size, simthreshd1):
x = x.contiguous()
B, H, N, D = x.shape
nblock = (N + block_size - 1) // block_size # Number of blocks per feature map
pool = torch.empty((B, H, nblock, D), device=x.device, dtype=x.dtype)
sim_blocks = torch.empty((B, H, nblock), device=x.device, dtype=torch.bool)
grid = (B, H, nblock)
# Launch kernel
triton_bmm_pool_sim_simmean[grid](x, pool, sim_blocks, simthreshd1, N=N, D=D, BS=block_size)
return pool, sim_blocks
#todo(xingyang): wrapper for tensor quantization
def get_quant(x, x_mean, block_size):
x = x.contiguous()
B, H, N, D = x.shape
nblock = (N + block_size - 1) // block_size
x_quant = torch.empty(x.shape, device=x.device, dtype=torch.int8)
x_scale = torch.empty((B, H, nblock), device=x.device, dtype=torch.float32)
grid = (B, H, nblock)
qk_quantize[grid](x, x_mean, x_quant, x_scale, N=N, D=D, BS=block_size, fuse_mean=(True if x_mean is not None else False))
return x_quant, x_scale
@triton.jit
def triton_fill_causal_mask(mask, BqdivBk):
q, k = tl.program_id(0), tl.program_id(1)
Q, K = tl.num_programs(0), tl.num_programs(1)
if k >= (q + 1) * BqdivBk:
tl.store(mask + q * K + k, 0)
else:
tl.store(mask + q * K + k, 1)
def get_block_map_meansim(q, k, is_causal=False, BLKQ=128, BLKK=64, simthreshd1=0.1, cdfthreshd=0.9, topk=None, is_sparse=True, return_lut=False, attention_sink=False):
assert (cdfthreshd is None and topk is not None)
or (cdfthreshd is not None and topk is None), "Only one of cdfthreshd and topk can be set."
def get_block_map_meansim_fuse_quant(q, k, km=None, is_causal=False, BLKQ=128, BLKK=64, simthreshd1=0.1, cdfthreshd=0.9, topk=None, is_sparse=True, return_lut=False, attention_sink=False):
assert (cdfthreshd is None and topk is not None)
or (cdfthreshd is not None and topk is None), "Only one of cdfthreshd and topk can be set."
def block_map_to_mask(block_map, BLKQ=128, BLKK=64):
B, H, x, y = block_map.shape
code
expanded_mask = torch.zeros((B, H, x * BLKQ, y * BLKK), dtype=torch.bool, device=block_map.device)
for i in range(x):
for j in range(y):
expanded_mask[..., i * BLKQ: (i + 1) * BLKQ, j * BLKK: (j + 1) * BLKK] = block_map[..., i:i+1, j:j+1]
return expanded_mask
Wrapped registrations in try-except AttributeError blocks to ensure the code remains robust even if the C++ extensions are not fully built or loaded (e.g., in non-CUDA environments).
Registered Fakes: I modified spas_sage_attn/__init__.py to import the new fake_impls module, ensuring the fake implementations are registered when the package is imported.
Enabled Compilation: I removed the @torch.compiler.disable decorators from spas_sage_attn/core.py (4 occurrences) and spas_sage_attn/triton_kernel_example.py (1 occurrence), allowing these functions to be optimized by torch.compile.
The codebase is now set up to support torch.compile for the custom Sparse SageAttention operators.
@torch.compiler.disable
spas_sage_attn_meansim
spas_sage2_attn_meansim_cuda
spas_sage2_attn_meansim_topk_cuda
block_sparse_sage2_attn_cuda
torch.compile
Modified spas_sage_attn/triton_kernel_example.py:
Removed the @torch.compiler.disable decorator from spas_sage_attn_meansim.
The codebase is now ready for compilation optimization.