
SageAttention2 v2.2.0 ROCm windows版 [AMD Radeon]
/ SageAttention 2 v2.2.0 ROCm windows版 [ AMD Radeon ] /
SageAttention2 v2.2.0 を自ビルドした。
ビルド済みwhlバイナリパッケージの公開は別記事のこちらに分けた。
SageAttention2 whlバイナリパッケージ ROCm 7.13.0 Preview windows版用
https://note.com/lpp/n/nd8a7c80fde81
いろいろと、予想とは違った流れに
いろいろと、予想とは違ったことに
まず一つ目、
Flash Attentionの記事は既にいくつか公開しているが、SageAttentionについては、いろいろと動きがあるのは把握していながらもそれら動きは記事にはせずに、ある程度かたちになるまでSageAttentionの進捗を見ていた。
現在は、既にSageAttention本家にてSageAttentionのV2.2をAMDに対応させるPull request(更新依頼)が出されており、マージされるのを待っているのだが、マージされず、かといって却下もされず、その間もPull requestに機能追加など修正がされ続ける、という状態が続いている。
そこに先週、
当方の記事ではたびたび登場する0xDELUXA氏が、他の人の
Will this branch ever be merged into SA main?
という「これマージされるの?」なコメントに対して、
Unfortunately, that's not very likely. (ダメっぽい)
あー、
当方もそんな感じがしていたので、待つのをやめて、手元でマージして自ビルドすることにした。
二つ目、
SageAttentionは内部で8bitで演算しているぶん、Flash Attentionとの比較で
予想では、
8bitにし品質を代償にしてるぶんだけSageAttentionのほうが速い
と思っていたのだが、
バイナリをビルドして実際に試してみると、
画像生成での比較ではFlash Attention CK版のほうが速かった
この時点でやる気をなくしたのだが、まぁ、SageAttention2.2が威力を発揮するのは動画生成だろう。
というわけで、動画生成で比較となるのだが、、、
そして3つ目、
動画生成ではAttentionが3つで1セットなのがあって、
Radial Attention
SpargeAttn / SpargeAttention
SageAttention
この3つをセットで使うんだけど、
当方の予想では、
まずSageAttention2.2公式のがROCm windows版で動くようになる。
また、tritonはtriton-windowsが既に対応済み。
すると、
SpargeAttn / SpargeAttentionがそれらに対応し、ROCm windows版でSpargeAttn がSageAttention2.2を基に高速で動くようになる。
そしてこれらが揃うと、
Radial AttentionがROCm windows版でそれらを基に高速で動くようになる。
こんな流れで3つセットが使えるようになって、動画生成がより高速/省VRAMで出来ると予想していたのだけれども、どうやら少し先になりそうだ.
これらのうち、SpargeAttn / SpargeAttentionは、いちおうSageAttention2.2を基に動くことは動く。といっても実装がまだこれからというところで、
今現在、2026年6月の時点では、実装済みなのはFP16だけ。PF8やINT8などの8bit系のコードはあるようなのだが未公開。
いわば、SageAttention2.2のAMD版をベータ版としたら、
SpargeAttn / SpargeAttentionのAMD版はアルファ版といったところ。
高速な8bit系はまだこれからだね。
動画については、今現在でも既に Flash Attention CK版で速度が出ているから、動画もFlash Attention CKでよいんじゃないの。
予想とは違ったために前置きが長くなったが、本題に入る。
SageAttention
SageAttentionのgithubのサイト
https://github.com/thu-ml/SageAttention
上記に論文のリンク先がある。
論文を斜め読みした限りだが、
演算を内部で8bitで行うことで、劣化させながらも高速化 / 省VRAM化する技術。
8bit演算ながらも、劣化を抑えながら高速化 / 省VRAM化している。
バージョンの更新で、
V2ではINT4による4bitでの演算も導入、
V3ではFP4による4bitでの演算も導入されるようになった。
ROCm windows版での SageAttention
まずそもそものSageAttentionには大きく3つ、
実態としては4つのバージョンがある。
SageAttention V1
SageAttention V2
SageAttention V2.2
SageAttention V3
そして今現在、2026年6月の時点でROCm windows版で使えるのは、
V1とV2.2。
SageAttention V1
ROCm windows版では、SageAttenttionV1はTriton backendで動く。
Tritonがソースコードからバイナリにコンパイルして動かすので、Sage Attentionはソースコードだけあればよい。
なのでSageAttentionのバイナリは不要。
pipでのインストールコマンドでインストールされるのはコレ。ソースコードがインストールされる。
一般的なAIアプリでpipでインストールする場合は、
venv\scripts\activate
pip install sageattention
pip install triton-windows
こんな感じで、
venv仮想環境をactivateしたのち、
sageattentionと、triton(triton-windows)をインストールする。
これでSageAttentionのソースコードがインストールされ、tritonで動く。
ただ、いちおうソースコード未改変のままそのままでも動くには動くが、最適化がイマイチなため、最適化パッチをあてて使う。
当方の記事ではguinmoon氏が公開している最適化パッチ済みwhlパッケージを多用している。
上記guinmoon氏のwhlパッケージを直インストールする場合はこのコマンド
pip install https://github.com/guinmoon/SageAttention-Rocm7/releases/download/v1.0.6_rocm7/sageattention-1.0.6-py3-none-any.whl
SageAttentionV2
すでにV2.2にとって代わられた。
SageAttentionV2.2
V2の改良版。
動かすにはバイナリが必要。詳細は後述。
SageAttentionV3
ROCm windows版にはまだ未対応。
V3は4bit演算なので、そもそもRX9070XTでは使えない、と思いきや、RX9070XT自体は4bit演算に対応しているようだ。
# もしかして、内部で8bitで演算しているというのかもしれない。
SageAttentionV2 V2.2
SageAttentionV2の、ROCm windows版までの流れとしては、
当方が知る限り、
まず、
2025年秋、
ivandobskygithub氏によりSageAttention_rocmが公開された。
https://github.com/ivandobskygithub/SageAttention_rocm
https://github.com/ivandobskygithub/SageAttention_rocm/tree/rocm-full-port
RDNA3 RX7000に対応。
RNDA4ででも動くことは動くようなのだが、曰く、R9700ではオーバーヘッドが多くてかえって遅くなったようで、非対応扱いになっている。
ちなみにivandobskygithub氏はnunchakuのROCm windows版 nunchaku_rocm_poc も公開している。
https://github.com/ivandobskygithub/nunchaku_rocm_poc
https://github.com/ivandobskygithub/nunchaku_rocm_poc/blob/main/docs/windows_rocm_setup.md
https://github.com/ivandobskygithub/nunchaku_rocm_poc/blob/main/docs/rocm7_windows_setup.md
同じく2025年秋、
eliotwang氏がgithubでSageAttentionのAMD ROCm版を公開。
データセンター用機器のGFX942 MI300系向けLinux版のよう。
2025年末で一区切りがついたようなのだが、コード見るとデータセンター用のGFX942の他にGFX1100の文字もあるので、もしかしたらRX7900 XT/XTXなら動くのかもしれない。Linux限定のままかもしれないけど。
GFX12は無いので、RX9070XTででは使えないだろう。
次に、
2025年12月、
SageAttention本家githubでAMD対応化のPull request(更新依頼)が出た。
ただしこの段階ではまだLinux用で、windowsには非対応。
また対応しているのはRDNA4 RX9000シリーズのみ。
2026年5月、
先のLinuxだけのとは別に、ROCm windows版にも対応させたPull request(更新依頼)が出た。
ただしgfx12とあるので、おそらく対応しているのはRDNA4 RX9000のみ。
そこではビルドして動いたという報告もアリ。
それで、マージされるのを待っているのだが、マージされず、かといって却下もされず、という状態が続いている。
待っている間もコードに追加や修正がおこなわれている。
そして先週、
2026年6月第4週、
当方の記事ではたびたび登場する0xDELUXA氏が、他の人の
Will this branch ever be merged into SA main?
という「これマージされるの?」なコメントに対して、
Unfortunately, that's not very likely. (ダメっぽい)
これは、マージされそうにないねぇ。
当方では、コードに追加や修正が行われていることから、マージされるまで見ているだけであったが、このコメントを見て自ビルドすることにした。
自ビルドして手元のRX9070XT搭載windowsPCでSageAttention2.2のバイナリが動くことを確認。
ビルド方法 ザックリとだけ
SageAttentionV2 V2.2のビルド方法はザックリとだけ。
既に Flash Attention2のCK版のビルド方法は載せてあるので、基本的にそれと変わらない。
Flash Attention CK Composable Kernel backend windows版 ビルド
https://note.com/lpp/n/nf24da8645c3c
SageAttentionV2 V2.2のROCm windows版のビルド方法は、ここ Pull request # 368 に書かれている。
https://github.com/thu-ml/SageAttention/pull/368
コマンド部分はコレ。
# Activate Visual Studio environment
cmd /c '"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1 && set' | ForEach-Object { if ($_ -match '^([^=]+)=(.*)$') { [System.Environment]::SetEnvironmentVariable($matches[1], $matches[2], 'Process') } }
# Activate the virtual environment
.\venv\Scripts\Activate.ps1
pip install --no-build-isolation -v .
まず、
git clone後、
ビルドをおこなう前に、
上記 Pull request # 368 は現在2026年6月最終週時点まだマージされていないので、手元でgitコマンド打ってマージする。
マージが出来たら、
次に、
そのままビルドするとファイル名にTorchやROCmのバージョンが含まれなくて、それだとのちのち困ることになるので、これらがwhlパッケージ名に含まれるように
setup.py
を改変する。
当方は各種ビルドするため環境変数を参照するように改変したが、それよりも単純な書き換えのほうがよいだろう。
setup.py の最後尾付近に
version='2.2.0',とあるので、これを
version=version='2.2.0+rocm7.13torch2.11.0gfx1201',のように書き換える。
* ROCmとtorchの部分はビルド時のバージョンに修正のこと。
これ以外にソースコードを書き換える必要は無い。そのままビルド出来る。
あとは上記Pull request #368 に書かれているコマンドをなぞるだけ。
順に実行していく。
まずMicrosoft Visual StudioのDevCmdモードにする。
cmd /c '"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1 && set' | ForEach-Object { if ($_ -match '^([^=]+)=(.*)$') { [System.Environment]::SetEnvironmentVariable($matches[1], $matches[2], 'Process') } }ここのMicrosoft Visual StudioのDevCmdモードの部分は各自PCのMSVCインストール先のPATHに修正する。
次にvenv仮想環境をactivate。Powershellの場合、
.\venv\Scripts\Activate.ps1ここで、当方のFlash Attention CK版のビルドの記事ではvenv仮想環境を別途構築しているが、もしComfyUIなどのvenvを間借りするならそのvenvをactivateする。というか、そのほうが手っ取り早いし、楽。
そしてビルドコマンドは、上記では、
pip install --no-build-isolation -v .となっている。通常はこのコマンドでインストールしたあとさらにwheel作成コマンドを実行してwhlパッケージを作成する。
ちなみに当方では上記ビルドコマンドではなく下記にて最初からwheelを作成するようにした。
python -m pip wheel --no-build-isolation --no-deps -v . --wheel-dir=dist/ビルド時間はそれなりにかかる。でもFlash Attention2 CK版より全然短い。
RAMの使用量もそれなりに多いが、Flash Attention2 CK版よりは全然少ない.
ちなみに当方の場合はRX9070XTのgfx1201だけでなく対応機種全部入りの全機種版whlもビルドしているので数倍の時間がかかっており、
そしてFlash Attention CK版の場合は対応gfxの数が7なのに対し、
今回のSageAttention2.2はgfx1201とgfx1200の2つだけなので、
この違いで圧倒的に短時間でビルドが終わった。
# 数あるAi関連ビルドの中でもFlash Attention CK版のビルドは飛びぬけて
# CPUとRAMを消費し、とても時間がかかる。
# SageAttentionも、今後対応機種が増えるとそれに伴って長時間に
# なっていくんだけどね。
実測
手元のRX9070XT搭載windowsPCにて、sage attention2.2のwhlバイナリを用いて実測。
SDXLとAnimaで実測した。
ForgeNeoとComfyUIで以前試した際、生成時間もVRAM消費量も変わらなかったため、ForgeNeoで実測している。(ForgeNeoはbackendがComfyUIだし)
測定条件は他の記事と同じにそろえてある。
1024x1024 20steps
実測の際のスクリーンショットと生成画はまとめて後述。
SDXL
SageAttention2.2 Automatic(FP16): 4.0sec
参考までに、
ノーマル(PyTorch Attention): 4.3sec
SageAttention1 Automatic(FP16): 4.3sec
Flash Attention CK版 Automatic(FP16): 4.0sec
ここで「ノーマル」は、RX9070XTでは「内蔵Flash Attention」になる。
SDXLはRX9070XTにとっては負荷が軽いためSDXLは比較用には適さないね.
Anima
SageAttention2.2 (BF16): 11.3sec
SageAttention2.2 FP8(e4m3fn): 11.4sec
SageAttention2.2 INT8: 9.8sec
FP8は、Automatic(BF16)よりも遅い結果に。
またFP8では生成画も他との違いが大きいが、これはFlash Attention でもノーマルのPyTorch AttentionでもFP8では違いが大きいので、そんなもの。
参考までに、
ノーマル (BF16): 12.4-12.6sec
ノーマル FP8(e4m3fn): 12.6sec
ノーマル INT8: 11.0sec
SageAttention1 (BF16): 12.0-12.2sec
SageAttention1 FP8(e4m3fn): 12.1sec
SageAttention1 INT8: 10.5sec
Flash Attention CK版 (BF16): 11.2sec
Flash Attention CK版 FP8(e4m3fn): 10.9sec
Flash Attention CK版 INT8: 9.7sec
SageAttention2.2はSageAttention1よりちゃんと速い。
しかし、Flash Attentin2 CK版のほうがさらに速いな。
2026年6月現在のSageAttention2.2.0の制約
ソースコードの解析および実測での裏付けから、
2026年6月現時点では、
モデルはfp16、もしくはモデルをINT8化して使うのならSageAttention2.2.0は速い。
BF16は、なんとも言えず。
FP8は遅い。FP8は、モデルサイズが大きいものだとFP8化されたのを使うことが良くあるが、そういうFP8化されたモデルだとSageAttention2.2.0は遅い。
また、ComfyUIなどでworkflow中でFP8化が挟まるとそこで遅くなる。
今後はFP8ででも速度が出るようになるだろうが、現状はFlash Attention CK版があるのだから、いまはそちらを使ったほうが良い。
SageAttention2.2.0 対 Flash Attention2 CK
SageAttention2.2.0 と Flash Attention2 CK版を比較したんだけど、
原理的には、SageAttention2.2は、品質は劣るが速度は速い、と思うのだが、実際に比較すると、Flash Attention2 CK版のほうが速かった。
これは、
勝手に推測すると、
SageAttention2.2ではオーバーヘッドが多い
最適化がまだ途上
と思っていて、FP8だとコードを調べた限りそのようで、そもそもSageAttention2.2のAMD対応はまだ正式リリースではないものを勝手に自ビルドしているわけだから、このあたりはこれからなのだろう。
ただ、FP16(とINT8)は最速ルートに乗っているはずで、にもかかわらず、
つまり、SageAttention2.2にて8bitで演算することで品質を落として速度を上げているにもかかわらず、それでもFlash Attention2 CK版より遅いのは、これは予想外だ。
そこで、
AIに訊いてみると、
SageAttentionが遅いのではなく、AMDのCK版は極限まで最適化されているため、CK版が速いのだ。
との答えだった。
たしかに、SageAttention2.2はSageAttentionV1からはそれなりに大きく速度が向上しており、SageAttention2.2だけで見ればかなり速い。
Flash Attention2 CK版を使っていなければ、最速である。
それで、
nVIDIA機の場合はSageAttention2.2のほうがFlash Attentionより速かったりするが、AMD ROCmでは逆にSageAttention2.2よりもFlash Attention2のほうが速いのは、CK版であるためだからだそうな。
CK版ことComposable Kernelは、今年2026年になって消費者向けGPUであるRX9070XTなどでも使えるようになったけど、もともとはデータセンター向け機器用であり、そこはAIの世界で一番競争が激しいところ。
そういうのが使えるというのが大きいのかもしれない。
そういえば、Flash Attention2 CK版のビルド負荷はnVIDIAのそれよりもさらに負荷が高くて、ビルド時間がより長くかかるのだが、それは、それだけ最適化をしているからなんだそうな。データセンター用だしな。
以上が静止画での比較であるが、SageAttention2.2が威力を発揮するのは動画生成、なのだけれど、
Radial Attentionを使ってSpargeAttn / SpargeAttentionにてSageAttention2.2を基に動画を生成すると威力を発揮しそうだが、現状は先にふれたようにSpargeAttn / SpargeAttentionの実装はまだ途上といったとこなので、
動画生成でSageAttention2.2が活きるのはもう少し先になりそうだ。
おまけ SpargeAttn / SpargeAttention
SpargeAttn / SpargeAttentionのRX9070XT gfx1201用whlバイナリパッケージ
8bit対応のが非公開なので、8bitのは無しで16bitのだけでビルドした。なので当然遅い。
まだベータ版どころかアルファ版といったところ。
速度が出ないだけでなく、なにか不具合があるかもしれず。
ROCm Preview版用whlバイナリパッケージ
ROCm7.13 Torch2.11.0 python3.13 gfx1201限定
spas_sage_attn-0.1.0+rocm7.13torch2.11.0gfx1201-cp313-cp313-win_amd64.whl
ROCm7.13 Torch2.11.0 python3.12 gfx1201限定
spas_sage_attn-0.1.0+rocm7.13torch2.11.0gfx1201-cp312-cp312-win_amd64.whl
ビルド自体はpython3.10やpython3.11ででもしてあるけど、試すだけならこの2つあれば十分でしょ。
実装が本格化したら個別に記事にしようかと。
参考資料: 実測のスクリーンショット
sage attention2.2のwhlバイナリを用いて実測
SDXLとAnimaで実測した。
測定条件は他の記事と同じにそろえてある。
1024x1024 20steps
SDXL
SageAttention2.2 Automatic(FP16): 4.0sec
参考までに、
ノーマル(PyTorch Attention): 4.3sec
SageAttention1 Automatic(FP16): 4.3sec
Flash Attention CK版 Automatic(FP16): 4.0sec
SDXLだと負荷が軽すぎて比較に適さないね。

Anima Automatic(BF16)
SageAttention2.2(BF16): 11.3seec


参考用に、Flash Attention2 CK版で再測もした
Flash Attention2 CK (BF16):11.2sec


Anima INT8
SageAttention2.2 INT8: 9.8sec
INT8についてはこちらの記事参照。
Forge Neo その8 Anima INT8で高速生成
https://note.com/lpp/n/n31674a7c6974


Anima FP8(e4m3fn)
SageAttention2.2 FP8 (e4m3fn): 11.4sec
FP8は、Automatic(BF16)よりも遅い結果に。
また生成画も他との違いが大きいが、これはFlash Attention でも、またノーマルのPyTorch Attentionでも違いが大きいので、そんなもの。


#AI #RX9070XT #Radeon #ROCm #rocm #sage #sageattn #sageattention #sageattention2 #sage -attention #sage_attention #flash-attn #flash_attn #gfx1201 #build #ビルド #SpargeAttn #SpargeAttention #spas_sage_attn
自分用メモ
SageAttention2.2バイナリの中身
python -c "import sageattention; import inspect; print(inspect.getsource(sageattention))"結果:
ネイティブの
sageattn_qk_int8_pv_gfx12_native
が入っている。RX9070XTのgfx1201がちゃんとある。
from .core import sageattn, sageattn_varlen
from .core import sageattn_qk_int8_pv_fp16_triton
from .core import sageattn_qk_int8_pv_fp16_cuda
from .core import sageattn_qk_int8_pv_fp8_cuda
from .core import sageattn_qk_int8_pv_fp8_cuda_sm90
from .core import sageattn_qk_int8_pv_gfx12_nativesageattention.coreの中身
python -c "import sageattention.core as c; import inspect; print(inspect.getsource(c.sageattn))"結果:
ネイティブの
sageattn_qk_int8_pv_gfx12_native
がだたあるだけでなく、ちゃんと選択されるようになっている。
def sageattn(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
tensor_layout: str = "HND",
is_causal: bool = False,
sm_scale: Optional[float] = None,
return_lse: bool = False,
**kwargs: Any,
):
"""
Automatically selects the appropriate implementation of the SageAttention kernel based on the GPU compute capability.
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]``.
v : torch.Tensor
The value 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]``.
tensor_layout : str
The tensor layout, either "HND" or "NHD".
Default: "HND".
is_causal : bool
Whether to apply causal mask to the attention matrix. Only applicable when qo_len == kv_len.
Default: False.
sm_scale : Optional[float]
The scale used in softmax, if not provided, will be set to ``1.0 / sqrt(head_dim)``.
return_lse : bool
Whether to return the log sum of the exponentiated attention weights. Used for cases like Ring Attention.
Default: False.
Returns
-------
torch.Tensor
The output 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]``.
torch.Tensor
The logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax normalization factor).
Shape: ``[batch_size, num_qo_heads, qo_len]``.
Only returned if `return_lse` is True.
Note
----
- ``num_qo_heads`` must be divisible by ``num_kv_heads``.
- The tensors `q`, `k`, and `v` must have the dtype ``torch.float16`` or ``torch.bfloat16``
- All tensors must be on the same cuda device.
"""
arch = get_cuda_arch_versions()[q.device.index]
if arch.startswith("gfx12"):
fast_path_keys = {"value_dtype", "smooth_k", "qk_quant_gran", "pv_accum_dtype", "smooth_v"}
value_dtype = kwargs.get("value_dtype", "auto")
value_dtype = value_dtype.lower() if isinstance(value_dtype, str) else value_dtype
gfx12_fast_common = (
not return_lse
and tensor_layout == "NHD"
and set(kwargs).issubset(fast_path_keys)
and kwargs.get("smooth_k", True)
and kwargs.get("qk_quant_gran", "per_warp") == "per_warp"
and not kwargs.get("smooth_v", False)
and q.is_cuda
and k.is_cuda
and v.is_cuda
and q.device == k.device == v.device
and q.dtype == k.dtype == v.dtype == torch.float16
and q.is_contiguous()
and k.is_contiguous()
and v.is_contiguous()
and q.dim() == 4
and k.dim() == 4
and v.dim() == 4
and q.size(0) == k.size(0) == v.size(0)
and q.size(1) == k.size(1) == v.size(1)
and q.size(2) == k.size(2) == v.size(2)
and q.size(3) == k.size(3) == v.size(3)
and q.size(1) in (512, 1024, 2048, 4096, 8192)
and q.size(3) in (64, 128)
)
if (
gfx12_fast_common
and value_dtype in {"auto", "fp8"}
and kwargs.get("pv_accum_dtype", None) in {None, "fp32+fp16"}
):
fast_sm_scale = float(sm_scale if sm_scale is not None else q.size(-1) ** -0.5)
out = _try_gfx12_fp8_nhd_short_mha(
q, k, v, is_causal, fast_sm_scale, _GFX12_FP8_VALUE_SCALE_MAX_FP32_FP16
)
if out is not None:
return out
return sageattn_qk_int8_pv_gfx12_native(
q, k, v, tensor_layout=tensor_layout, is_causal=is_causal,
sm_scale=sm_scale, return_lse=return_lse, **kwargs)
if arch == "sm80":
return sageattn_qk_int8_pv_fp16_cuda(q, k, v, tensor_layout=tensor_layout, is_causal=is_causal, sm_scale=sm_scale, return_lse=return_lse, pv_accum_dtype="fp32")
elif arch == "sm86":
return sageattn_qk_int8_pv_fp16_triton(q, k, v, tensor_layout=tensor_layout, is_causal=is_causal, sm_scale=sm_scale, return_lse=return_lse)
elif arch == "sm89":
return sageattn_qk_int8_pv_fp8_cuda(q, k, v, tensor_layout=tensor_layout, is_causal=is_causal, sm_scale=sm_scale, return_lse=return_lse, pv_accum_dtype="fp32+fp16")
elif arch == "sm90":
return sageattn_qk_int8_pv_fp8_cuda_sm90(q, k, v, tensor_layout=tensor_layout, is_causal=is_causal, sm_scale=sm_scale, return_lse=return_lse, pv_accum_dtype="fp32+fp32")
elif arch == "sm120":
return sageattn_qk_int8_pv_fp8_cuda(q, k, v, tensor_layout=tensor_layout, is_causal=is_causal, qk_quant_gran="per_warp", sm_scale=sm_scale, return_lse=return_lse, pv_accum_dtype="fp32+fp16") # sm120 has accurate fp32 accumulator for fp8 mma and triton kernel is currently not usable on sm120.
elif arch == "sm121":
return sageattn_qk_int8_pv_fp8_cuda(q, k, v, tensor_layout=tensor_layout, is_causal=is_causal, qk_quant_gran="per_warp", sm_scale=sm_scale, return_lse=return_lse, pv_accum_dtype="fp32+fp16") # sm121 has accurate fp32 accumulator for fp8 mma and triton kernel is currently not usable on sm121.
else:
raise ValueError(f"Unsupported CUDA architecture: {arch}")
sageattn_qk_int8_pv_gfx12_nativeの中身
import sageattention.core as c
import inspect
print(inspect.getsource(c.sageattn_qk_int8_pv_gfx12_native))結果:
最高速を出せるネイティブの
sageattn_qk_int8_pv_gfx12_native
が使われる条件。
この条件にあうとネイティブが使われて速い。
条件に合わない場合は、合うように変換処理が入り、そのオーバーヘッドのぶんだけ遅くなる、ということか?
これ、条件からFP8が漏れているな?
モデルがFP8だと遅いのは、コレが原因か?
漏らしたのではなく、これから実装するところなのかな?
まぁ、まだ正式リリースでもないものを勝手にビルドしてるだけだからなぁ.
def sageattn_qk_int8_pv_gfx12_native(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
tensor_layout: str = "HND",
is_causal: bool = False,
qk_quant_gran: str = "per_warp",
sm_scale: Optional[float] = None,
pv_accum_dtype: Optional[str] = None,
value_dtype: str = "fp8",
smooth_k: bool = True,
smooth_v: bool = False,
return_lse: bool = False,
**kwargs: Any,
) -> torch.Tensor:
"""
ROCm gfx12 native SageAttention path.
Supports fixed-length attention. The default smooth-K path follows the
CUDA quantization flow; NHD inputs use native NHD quantization to avoid an
extra layout conversion when possible.
Current gfx12 constraints:
- q, k, and v must be fp16 or bf16.
- value_dtype="fp8" supports head_dim 16, 64, 128, or 256.
- value_dtype="fp16" supports head_dim 16, 64, 128, or 256.
- Causal masking requires q_len == kv_len.
- smooth_k is enabled by default to match the CUDA and Triton paths.
- return_lse uses an exact PyTorch logsumexp side computation and does
not affect the default return_lse=False fast path.
"""
if qk_quant_gran not in {"per_warp", "per_thread"}:
raise ValueError("qk_quant_gran must be either 'per_warp' or 'per_thread'.")
value_dtype_normalized, pv_accum_dtype, smooth_v, fp8_value_scale_max = (
_gfx12_normalize_v2_options(value_dtype, pv_accum_dtype, smooth_v)
)
pv_accum_mode = _gfx12_pv_accum_mode(value_dtype_normalized, pv_accum_dtype)
gfx12_native = _get_gfx12_native_extension()
gfx12_prepare_attn_hnd = _qattn_gfx12_prepare_attn_hnd
assert q.is_cuda, "Input tensors must be on cuda/HIP."
assert q.device == k.device == v.device, "All tensors must be on the same device."
assert q.dtype == k.dtype == v.dtype, "All tensors must have the same dtype."
assert q.dtype in [torch.float16, torch.bfloat16], "gfx12 native path supports fp16/bf16 inputs."
assert tensor_layout in ["HND", "NHD"], "tensor_layout must be either 'HND' or 'NHD'."
input_dtype = q.dtype
if smooth_v:
q_heads = q.size(2) if tensor_layout == "NHD" else q.size(1)
v, smooth_v_mean = _gfx12_apply_smooth_v(v, tensor_layout, q_heads)
else:
smooth_v_mean = None
lse_q = q
lse_k = k
lse_sm_scale = float(sm_scale if sm_scale is not None else q.size(-1) ** -0.5)
def _with_lse(out: torch.Tensor):
out = _gfx12_add_smooth_v_mean(out, smooth_v_mean, tensor_layout)
if not return_lse:
return out
return out, _attention_lse_reference(
lse_q, lse_k, tensor_layout, bool(is_causal), lse_sm_scale
)
torch.cuda.set_device(v.device)
assert v.dtype in [torch.float16, torch.bfloat16], "gfx12 native path supports fp16/bf16 value inputs."
value_dtype = value_dtype_normalized
if sm_scale is None and q.dim() == 4:
sm_scale = q.size(-1) ** -0.5
if tensor_layout == "HND" and q.dim() == 4 and 128 < q.size(-1) <= 256:
out_nhd = sageattn_qk_int8_pv_gfx12_native(
q.transpose(1, 2).contiguous(),
k.transpose(1, 2).contiguous(),
v.transpose(1, 2).contiguous(),
tensor_layout="NHD",
is_causal=is_causal,
qk_quant_gran=qk_quant_gran,
sm_scale=sm_scale,
pv_accum_dtype=pv_accum_dtype,
value_dtype=value_dtype,
smooth_k=smooth_k,
smooth_v=False,
return_lse=False,
**kwargs,
)
return _with_lse(out_nhd.transpose(1, 2).contiguous())
if (
tensor_layout == "HND"
and not smooth_k
and q.dim() == 4
and k.dim() == 4
and v.dim() == 4
and q.dtype == k.dtype == v.dtype
and q.is_contiguous()
and k.is_contiguous()
and v.is_contiguous()
and q.size(-1) in (16, 64, 128)
and value_dtype == "fp16"
and q.size(-1) in (16, 64)
and q.size(2) % 64 == 0
and k.size(2) % 64 == 0
):
use_raw_f16_value = (
value_dtype == "fp16"
and input_dtype == torch.float16
and is_causal
and q.size(-1) == 64
and q.size(2) <= 512
)
out = gfx12_prepare_attn_hnd(
q,
k,
v,
int(is_causal),
int(value_dtype == "fp8"),
int(use_raw_f16_value),
float(sm_scale),
0,
pv_accum_mode,
)
if input_dtype == torch.bfloat16:
out = out if out.dtype == torch.bfloat16 else gfx12_native.convert_f16_to_bf16(out)
return _with_lse(out)
if tensor_layout == "NHD" and smooth_k and qk_quant_gran == "per_warp":
q_nhd = q.contiguous()
k_nhd = k.contiguous()
v_nhd = v.contiguous()
_, qo_len, h_qo, head_dim_og = q_nhd.shape
_, kv_len, h_kv, _ = k_nhd.shape
if h_qo % h_kv != 0:
raise ValueError("num_qo_heads must be divisible by num_kv_heads.")
if is_causal and qo_len != kv_len:
raise ValueError("gfx12 causal path currently requires q_len == kv_len.")
head_dim = head_dim_og
if head_dim < 64:
pad = 64 - head_dim
q_nhd = F.pad(q_nhd, (0, pad))
k_nhd = F.pad(k_nhd, (0, pad))
v_nhd = F.pad(v_nhd, (0, pad))
head_dim = 64
elif 64 < head_dim < 128:
pad = 128 - head_dim
q_nhd = F.pad(q_nhd, (0, pad))
k_nhd = F.pad(k_nhd, (0, pad))
v_nhd = F.pad(v_nhd, (0, pad))
head_dim = 128
elif 128 < head_dim < 256:
pad = 256 - head_dim
q_nhd = F.pad(q_nhd, (0, pad))
k_nhd = F.pad(k_nhd, (0, pad))
v_nhd = F.pad(v_nhd, (0, pad))
head_dim = 256
if value_dtype == "fp16" and head_dim not in (16, 64, 128, 256):
raise ValueError("gfx12 fp16 value path currently supports head_dim 16, 64, 128, or 256.")
if value_dtype == "fp8" and head_dim not in (16, 64, 128, 256):
raise ValueError("gfx12 fp8 value path currently supports head_dim 16, 64, 128, or 256.")
use_gfx12_fp8_nhd_mha_wrapper = (
value_dtype == "fp8"
and input_dtype == torch.float16
and qo_len == kv_len
and kv_len in (512, 1024, 2048, 4096, 8192)
and head_dim in (64, 128)
)
use_short_nhd_fp8_prep = (
value_dtype == "fp8"
and input_dtype == torch.float16
and qo_len == kv_len
and kv_len in (512, 1024)
and head_dim in (64, 128)
)
if use_gfx12_fp8_nhd_mha_wrapper and head_dim_og in (64, 128) and h_qo == h_kv:
out = _try_gfx12_fp8_nhd_short_mha(
q_nhd, k_nhd, v_nhd, is_causal, float(sm_scale), fp8_value_scale_max
)
if out is not None:
return _with_lse(out)
value_native = None
value_scale = None
if use_short_nhd_fp8_prep:
k_mean_flat, value_native, value_scale = (
gfx12_native.mean_and_fp8_value_nhd_short(
k_nhd, v_nhd, float(fp8_value_scale_max)
)
)
k_mean = k_mean_flat.unsqueeze(1)
elif value_dtype == "fp16" and head_dim in (64, 128, 256):
use_d64_causal_seq32_mean = (
input_dtype == torch.float16
and is_causal
and head_dim == 64
and qo_len == kv_len
and kv_len in (2048, 4096, 8192)
)
if use_d64_causal_seq32_mean:
k_mean_flat = gfx12_native.mean_nhd_d64_seq32(k_nhd)
else:
k_mean_flat = gfx12_native.mean_nhd(k_nhd)
k_mean = k_mean_flat.unsqueeze(1)
else:
k_mean = k_nhd.mean(dim=1, keepdim=True)
k_mean_flat = k_mean.squeeze(1)
use_rawq_tail = value_dtype == "fp8" and not is_causal and head_dim == 128
use_mixed_key_hnd = value_dtype == "fp8" and (
(
is_causal
and (
(head_dim == 64 and qo_len >= 8192)
or (head_dim == 128 and qo_len >= 4096)
)
)
)
use_rawq_f16_value = (
value_dtype == "fp16"
and input_dtype == torch.float16
and head_dim in (64, 128, 256)
and qk_quant_gran == "per_warp"
and (
not is_causal
or (
qo_len == kv_len
and (head_dim == 256 or (qo_len % 64 == 0 and kv_len % 64 == 0))
)
)
)
if use_rawq_tail or use_rawq_f16_value:
if is_causal and (qo_len % 64 != 0 or kv_len % 64 != 0):
q_nhd, k_nhd, v_nhd = _pad_gfx12_nhd_sequence(
q_nhd, k_nhd, v_nhd, qo_len, kv_len, True, k_mean
)
q_attn = q_nhd
q_out_len = q_nhd.size(1)
else:
q_attn = q_nhd
q_out_len = ((qo_len + 127) // 128) * 128 if use_rawq_tail else qo_len
kv_pad_len = ((kv_len + 63) // 64) * 64 - kv_len
if kv_pad_len > 0:
k_nhd = torch.cat([k_nhd, k_mean.expand(-1, kv_pad_len, -1, -1)], dim=1)
v_nhd = F.pad(v_nhd, (0, 0, 0, 0, 0, kv_pad_len))
else:
q_nhd, k_nhd, v_nhd = _pad_gfx12_nhd_sequence(
q_nhd, k_nhd, v_nhd, qo_len, kv_len, bool(is_causal), k_mean
)
q_attn = q_nhd
q_out_len = q_nhd.size(1)
if use_mixed_key_hnd:
k_attn = k_nhd.transpose(1, 2).contiguous()
k_mean_attn = k_mean.transpose(1, 2).contiguous()
k_int8 = torch.empty_like(k_attn, dtype=torch.int8)
k_scale = torch.empty(
(k_attn.size(0), k_attn.size(1), (k_attn.size(2) + 63) // 64),
device=k_attn.device,
dtype=torch.float32,
)
_quant_fused.quant_per_block_int8_fuse_sub_mean_cuda(
k_attn, k_mean_attn.squeeze(2), k_int8, k_scale, 64, 1
)
else:
k_int8 = torch.empty_like(k_nhd, dtype=torch.int8)
k_scale = torch.empty(
(k_nhd.size(0), k_nhd.size(2), (k_nhd.size(1) + 63) // 64),
device=k_nhd.device,
dtype=torch.float32,
)
_quant_fused.quant_per_block_int8_fuse_sub_mean_cuda(
k_nhd, k_mean_flat, k_int8, k_scale, 64, 0
)
if value_dtype == "fp8":
if value_native is None:
value_native, value_scale = _gfx12_fp8_value_native(
gfx12_native, v_nhd, fp8_value_scale_max, "NHD"
)
else:
value_native = v_nhd if input_dtype == torch.float16 else v_nhd.to(torch.float16)
out = torch.empty(
(q_nhd.size(0), q_out_len, q_nhd.size(2), q_nhd.size(3)),
device=q_nhd.device,
dtype=torch.float16,
)
if value_dtype == "fp8":
gfx12_native.qk_rawq_int8_sv_f8_scaled_native_attn(
q_attn,
k_int8,
value_native,
out,
k_scale,
value_scale,
0,
int(is_causal),
float(sm_scale),
kv_len,
1,
int(use_mixed_key_hnd),
)
else:
if use_rawq_f16_value:
gfx12_native.qk_rawq_int8_sv_f16_native_attn(
q_attn,
k_int8,
value_native,
out,
k_scale,
0,
int(is_causal),
float(sm_scale),
kv_len,
pv_accum_mode,
)
else:
q_int8, q_scale = gfx12_native.quant_q_nhd_per_warp(q_attn)
gfx12_native.qk_int8_sv_f16_d64_native_attn(
q_int8,
k_int8,
value_native,
out,
q_scale,
k_scale,
0,
int(is_causal),
float(sm_scale),
kv_len,
0,
pv_accum_mode,
)
if q_out_len != qo_len or head_dim != head_dim_og:
out = out[:, :qo_len, :, :head_dim_og]
if input_dtype == torch.bfloat16 and out.dtype != torch.bfloat16:
out = gfx12_native.convert_f16_to_bf16(out.contiguous() if not out.is_contiguous() else out)
elif input_dtype != torch.float16:
out = out.to(input_dtype)
return _with_lse(out)
if tensor_layout == "NHD":
q_hnd = q.transpose(1, 2).contiguous()
k_hnd = k.transpose(1, 2).contiguous()
v_hnd = v.transpose(1, 2).contiguous()
else:
q_hnd = q.contiguous()
k_hnd = k.contiguous()
v_hnd = v.contiguous()
_, h_qo, qo_len, head_dim_og = q_hnd.shape
_, h_kv, kv_len, _ = k_hnd.shape
if h_qo % h_kv != 0:
raise ValueError("num_qo_heads must be divisible by num_kv_heads.")
if is_causal and qo_len != kv_len:
raise ValueError("gfx12 causal path currently requires q_len == kv_len.")
head_dim = head_dim_og
if head_dim < 64 and (
smooth_k or head_dim != 16 or value_dtype == "fp8" or q_hnd.dtype != v_hnd.dtype
):
pad = 64 - head_dim
q_hnd = F.pad(q_hnd, (0, pad))
k_hnd = F.pad(k_hnd, (0, pad))
v_hnd = F.pad(v_hnd, (0, pad))
head_dim = 64
elif 64 < head_dim < 128:
pad = 128 - head_dim
q_hnd = F.pad(q_hnd, (0, pad))
k_hnd = F.pad(k_hnd, (0, pad))
v_hnd = F.pad(v_hnd, (0, pad))
head_dim = 128
elif 128 < head_dim < 256:
pad = 256 - head_dim
q_hnd = F.pad(q_hnd, (0, pad))
k_hnd = F.pad(k_hnd, (0, pad))
v_hnd = F.pad(v_hnd, (0, pad))
head_dim = 256
if value_dtype == "fp16" and head_dim not in (16, 64, 128, 256):
raise ValueError("gfx12 fp16 value path currently supports head_dim 16, 64, 128, or 256.")
if value_dtype == "fp8" and head_dim not in (16, 64, 128, 256):
raise ValueError("gfx12 fp8 value path currently supports head_dim 16, 64, 128, or 256.")
k_mean = None
if smooth_k:
if value_dtype == "fp16" and qk_quant_gran == "per_warp" and head_dim in (64, 128):
k_mean = gfx12_native.mean_hnd(k_hnd).unsqueeze(2)
else:
k_mean = k_hnd.mean(dim=2, keepdim=True)
q_hnd, k_hnd, v_hnd = _pad_gfx12_hnd_sequence(
q_hnd, k_hnd, v_hnd, qo_len, kv_len, bool(is_causal), k_mean)
padded_qo_len = q_hnd.size(2)
use_raw_f16_value = (
value_dtype == "fp16"
and input_dtype == torch.float16
and is_causal
and head_dim == 64
and padded_qo_len <= 512
)
def _quant_qk_hnd(q_src: torch.Tensor, k_src: torch.Tensor, km_src: Optional[torch.Tensor]):
if qk_quant_gran == "per_thread":
return per_thread_int8_triton(
q_src, k_src, km_src, BLKQ=128,
WARPQ=(16 if (head_dim == 128 and pv_accum_dtype == "fp16+fp32") else 32),
BLKK=64, WARPK=64, tensor_layout="HND"
)
return per_warp_int8_cuda(
q_src, k_src, km_src, BLKQ=128, WARPQ=32, BLKK=64, tensor_layout="HND"
)
if not smooth_k:
if value_dtype == "fp8":
q_int8, q_scale, k_int8, k_scale = _quant_qk_hnd(q_hnd, k_hnd, None)
value_native, value_scale = _gfx12_fp8_value_native(
gfx12_native, v_hnd, fp8_value_scale_max, "HND"
)
out = torch.empty_like(q_hnd, dtype=torch.float16)
gfx12_native.qk_int8_sv_f8_scaled_native_attn(
q_int8, k_int8, value_native, out, q_scale, k_scale, value_scale,
1, int(is_causal), float(sm_scale), kv_len
)
else:
if qk_quant_gran == "per_warp" and q_hnd.dtype == k_hnd.dtype == v_hnd.dtype:
out = gfx12_prepare_attn_hnd(
q_hnd,
k_hnd,
v_hnd,
int(is_causal),
0,
int(use_raw_f16_value),
float(sm_scale),
kv_len,
pv_accum_mode,
)
else:
q_int8, q_scale, k_int8, k_scale = _quant_qk_hnd(q_hnd, k_hnd, None)
value_native = gfx12_native.transpose_value_f16_hnd(v_hnd)
out = torch.empty_like(q_hnd, dtype=torch.float16)
gfx12_native.qk_int8_sv_f16_d64_native_attn(
q_int8, k_int8, value_native, out, q_scale, k_scale,
1, int(is_causal), float(sm_scale), kv_len, 1,
pv_accum_mode
)
else:
use_rawq_hnd_fp8 = (
value_dtype == "fp8"
and head_dim in (64, 128)
and (
not is_causal
or head_dim == 64
or padded_qo_len <= 1024
or padded_qo_len >= 8192
)
)
if use_rawq_hnd_fp8 and qk_quant_gran == "per_warp":
k_int8 = torch.empty_like(k_hnd, dtype=torch.int8)
k_scale = torch.empty(
(k_hnd.size(0), k_hnd.size(1), (k_hnd.size(2) + 63) // 64),
device=k_hnd.device,
dtype=torch.float32,
)
_quant_fused.quant_per_block_int8_fuse_sub_mean_cuda(
k_hnd, k_mean.squeeze(2), k_int8, k_scale, 64, 1
)
value_native, value_scale = _gfx12_fp8_value_native(
gfx12_native, v_hnd, fp8_value_scale_max, "HND"
)
out = torch.empty_like(
q_hnd,
dtype=torch.bfloat16 if input_dtype == torch.bfloat16 else torch.float16,
)
gfx12_native.qk_rawq_int8_sv_f8_scaled_native_attn(
q_hnd, k_int8, value_native, out, k_scale, value_scale,
1, int(is_causal), float(sm_scale), kv_len, 1
)
out = out[..., :qo_len, :head_dim_og]
if input_dtype != torch.float16 and out.dtype != input_dtype:
out = out.to(input_dtype)
if tensor_layout == "NHD":
out = out.transpose(1, 2).contiguous()
return _with_lse(out)
use_rawq_hnd_f16 = (
value_dtype == "fp16"
and input_dtype == torch.float16
and qk_quant_gran == "per_warp"
and head_dim in (64, 128)
and qo_len == kv_len
and is_causal
and qo_len == 512
and q_hnd.dtype == k_hnd.dtype == v_hnd.dtype
)
if use_rawq_hnd_f16:
k_int8 = torch.empty_like(k_hnd, dtype=torch.int8)
k_scale = torch.empty(
(k_hnd.size(0), k_hnd.size(1), (k_hnd.size(2) + 63) // 64),
device=k_hnd.device,
dtype=torch.float32,
)
_quant_fused.quant_per_block_int8_fuse_sub_mean_cuda(
k_hnd, k_mean.squeeze(2).contiguous(), k_int8, k_scale, 64, 1
)
out = torch.empty_like(q_hnd, dtype=torch.float16)
gfx12_native.qk_rawq_int8_sv_f16_native_attn(
q_hnd, k_int8, v_hnd, out, k_scale,
1, int(is_causal), float(sm_scale), kv_len, pv_accum_mode
)
out = out[..., :qo_len, :head_dim_og]
if input_dtype != torch.float16 and out.dtype != input_dtype:
out = out.to(input_dtype)
if tensor_layout == "NHD":
out = out.transpose(1, 2).contiguous()
return _with_lse(out)
use_smooth_hnd_f16_prep = (
value_dtype == "fp16"
and qk_quant_gran == "per_warp"
and head_dim in (64, 128)
and not is_causal
and qo_len == kv_len
and qo_len in (512, 1024)
and q_hnd.dtype == k_hnd.dtype == v_hnd.dtype
)
value_native = None
if use_smooth_hnd_f16_prep:
q_int8, q_scale, k_int8, k_scale, value_native = (
gfx12_native.prepare_qkv_hnd_smooth_f16(
q_hnd, k_hnd, v_hnd, k_mean.squeeze(2).contiguous()
)
)
else:
q_int8, q_scale, k_int8, k_scale = _quant_qk_hnd(q_hnd, k_hnd, k_mean)
out = torch.empty_like(q_hnd, dtype=torch.float16)
if value_dtype == "fp8":
value_native, value_scale = _gfx12_fp8_value_native(
gfx12_native, v_hnd, fp8_value_scale_max, "HND"
)
gfx12_native.qk_int8_sv_f8_scaled_native_attn(
q_int8, k_int8, value_native, out, q_scale, k_scale, value_scale,
1, int(is_causal), float(sm_scale), kv_len
)
else:
if value_native is None:
value_native = gfx12_native.transpose_value_f16_hnd(v_hnd)
gfx12_native.qk_int8_sv_f16_d64_native_attn(
q_int8, k_int8, value_native, out, q_scale, k_scale,
1, int(is_causal), float(sm_scale), kv_len, 1,
pv_accum_mode
)
out = out[..., :qo_len, :head_dim_og]
if input_dtype == torch.bfloat16 and out.dtype != torch.bfloat16:
out = gfx12_native.convert_f16_to_bf16(out.contiguous() if not out.is_contiguous() else out)
elif input_dtype != torch.float16:
out = out.to(input_dtype)
if tensor_layout == "NHD":
out = out.transpose(1, 2).contiguous()
return _with_lse(out)