Skip to content

Commit b040a6a

Browse files
authored
[_sunrise] update commits of sunrise backend. [till 20260812] (#5478)
* #19382 tang -> ptpu * add sunrise's mode. use sunrise's sort * [#19375] update attention * #11009, #11010, #11012, #10976 optimize performence
1 parent cc30f92 commit b040a6a

13 files changed

Lines changed: 1208 additions & 248 deletions

File tree

src/flag_gems/runtime/backend/_sunrise/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
vendor_name="sunrise",
2424
device_name="ptpu",
2525
device_query_cmd="pt_smi",
26-
triton_extra_name="tang",
26+
triton_extra_name="ptpu",
2727
dispatch_key="PrivateUse1",
2828
fp64_enabled=False,
2929
bf16_enabled=False,
@@ -102,6 +102,8 @@ def _sunrise_monkey_patch_enabled():
102102
"log_sigmoid",
103103
"margin_ranking_loss",
104104
"max_pool3d_with_indices_backward",
105+
"mm",
106+
"mm_out",
105107
"nonzero_numpy",
106108
"pad",
107109
"prelu",
@@ -111,6 +113,7 @@ def _sunrise_monkey_patch_enabled():
111113
"repeat_interleave.self_Tensor",
112114
"resolve_conj",
113115
"resolve_neg",
116+
"router_gemm",
114117
"selu",
115118
"selu_",
116119
"square",

src/flag_gems/runtime/backend/_sunrise/fused/sparse_attention.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,10 @@ def sparse_attn_triton(
134134
b, m, h, d = q.shape
135135
topk = topk_idxs.shape[-1]
136136
o = torch.empty_like(q)
137-
BLOCK = 64
137+
# A 64-wide KV tile exceeds the 128 KiB shared-memory limit on PTPU
138+
# for the D=512 sparse-attention shapes. The single pipeline stage is
139+
# also required for correct results with the smaller tile on PTPU.
140+
BLOCK = 16
138141

139142
grid = (m, b) # each program handles ALL h heads
140143
if h < 8:
@@ -169,6 +172,7 @@ def sparse_attn_triton(
169172
D=d,
170173
H=8,
171174
num_warps=8, # 256 threads, matching tilelang
175+
num_stages=1,
172176
)
173177
o = o_new[:, :, :h].contiguous()
174178
return o
@@ -199,5 +203,6 @@ def sparse_attn_triton(
199203
D=d,
200204
H=h,
201205
num_warps=8, # 256 threads, matching tilelang
206+
num_stages=1,
202207
)
203208
return o

src/flag_gems/runtime/backend/_sunrise/monkey_patch.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,78 @@ def randn_with_ptpu_complex_cpu_fallback(*args, **kwargs):
637637
setattr(torch, patched_attr, True)
638638

639639

640+
def _patch_torch_abs_long_runtime_error():
641+
"""Run ``torch.abs`` on CPU for PTPU int64 eager helper tensors.
642+
643+
Sunrise's eager ``UNARY_ABS`` kernel raises a plain ``RuntimeError`` for
644+
``torch.long`` inputs. Keep the workaround outside ``use_gems()`` so it
645+
only covers setup/reference helpers such as flash-attention ALiBi bias
646+
construction and cannot hide a missing FlagGems ``abs`` implementation.
647+
"""
648+
patched_attr = "_flag_gems_sunrise_abs_long_runtime_error_patched"
649+
if getattr(torch, patched_attr, False):
650+
return
651+
652+
original_fn = torch.abs
653+
runtime_marker = "unary_op<ptpu_kernel::UNARY_ABS>"
654+
dtype_marker = "failed to dispatch data type Long"
655+
656+
@functools.wraps(original_fn)
657+
def abs_with_ptpu_long_cpu_fallback(*args, **kwargs):
658+
tensor = args[0] if args else kwargs.get("input")
659+
try:
660+
return original_fn(*args, **kwargs)
661+
except RuntimeError as exc:
662+
message = str(exc)
663+
if (
664+
_flag_gems_use_gems_active()
665+
or not _is_ptpu_tensor(tensor)
666+
or tensor.dtype != torch.long
667+
or runtime_marker not in message
668+
or dtype_marker not in message
669+
):
670+
raise
671+
return _torch_function_cpu_fallback(tensor, args, kwargs, original_fn)
672+
673+
torch.abs = abs_with_ptpu_long_cpu_fallback
674+
setattr(torch, patched_attr, True)
675+
676+
677+
def _patch_torch_all_keepdim_runtime_error():
678+
"""Run unsupported PTPU bool ``torch.all(..., keepdim=True)`` on CPU.
679+
680+
Sunrise eager reduction raises a plain ``RuntimeError`` for this form.
681+
Limit the fallback to the exact runtime message and reference/setup code
682+
outside ``use_gems()`` so FlagGems' real ``all`` kernel remains visible.
683+
"""
684+
patched_attr = "_flag_gems_sunrise_all_keepdim_runtime_error_patched"
685+
if getattr(torch, patched_attr, False):
686+
return
687+
688+
original_fn = torch.all
689+
runtime_marker = "all_out with keepdim true is not implemented yet."
690+
691+
@functools.wraps(original_fn)
692+
def all_with_ptpu_keepdim_cpu_fallback(*args, **kwargs):
693+
tensor = args[0] if args else kwargs.get("input")
694+
keepdim = args[2] if len(args) > 2 else kwargs.get("keepdim", False)
695+
try:
696+
return original_fn(*args, **kwargs)
697+
except RuntimeError as exc:
698+
if (
699+
_flag_gems_use_gems_active()
700+
or not _is_ptpu_tensor(tensor)
701+
or tensor.dtype != torch.bool
702+
or keepdim is not True
703+
or runtime_marker not in str(exc)
704+
):
705+
raise
706+
return _torch_function_cpu_fallback(tensor, args, kwargs, original_fn)
707+
708+
torch.all = all_with_ptpu_keepdim_cpu_fallback
709+
setattr(torch, patched_attr, True)
710+
711+
640712
def _patch_torch_cudnn_convolution():
641713
"""Run `torch.cudnn_convolution(...)` on CPU via `F.conv{1,2,3}d` for PTPU.
642714
@@ -3365,6 +3437,7 @@ def apply_sunrise_monkey_patches():
33653437
_patch_torch_function("logsumexp", "aten::amax.out")
33663438
_patch_tensor_method("mean", "aten::mean")
33673439
_patch_torch_function("mean", "aten::mean")
3440+
_patch_torch_all_keepdim_runtime_error()
33683441
_patch_torch_function("norm", "aten::linalg_vector_norm.out")
33693442
_patch_torch_linalg_function("vector_norm", "aten::linalg_vector_norm.out")
33703443
_patch_torch_linalg_function("qr", "aten::linalg_qr.out")
@@ -3403,6 +3476,7 @@ def apply_sunrise_monkey_patches():
34033476
_patch_torch_nn_functional("logsigmoid", "aten::log_sigmoid_forward")
34043477
_patch_torch_nn_functional_one_hot_cpu_reference()
34053478
_patch_torch_randn_complex_dtype()
3479+
_patch_torch_abs_long_runtime_error()
34063480
_patch_torch_cudnn_convolution()
34073481
_patch_conv_depthwise2d_cpu_reference()
34083482
_patch_thnn_fused_lstm_cell_cpu_reference()

src/flag_gems/runtime/backend/_sunrise/ops/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,8 @@
127127
from .max_pool3d_with_indices import max_pool3d_backward, max_pool3d_with_indices
128128
from .mean import mean, mean_dim
129129
from .median import median, median_dim, median_dim_values, median_out
130+
from .mm import mm, mm_out, router_gemm
131+
from .mode import mode
130132
from .mul import mul, mul_
131133
from .multinomial import multinomial
132134
from .multiply_ import multiply_
@@ -329,6 +331,9 @@
329331
"median_dim",
330332
"median_dim_values",
331333
"median_out",
334+
"mode",
335+
"mm",
336+
"mm_out",
332337
"mul",
333338
"mul_",
334339
"multiply_",
@@ -360,6 +365,7 @@
360365
"rms_norm",
361366
"rms_norm_forward",
362367
"rms_norm_backward",
368+
"router_gemm",
363369
"scaled_grouped_mm",
364370
"scaled_dot_product_attention",
365371
"scaled_dot_product_attention_backward",

0 commit comments

Comments
 (0)