MSLK、Transformer 向け GPU カーネルライブラリを公開
本文の状態
日本語全文を表示中
詳細モードで約28分の本文を読めます。
同じ出来事の情報源
この情報源を基点に整理
TLDR AI
MSLK は Transformer 推論向けの融合 GPU カーネルライブラリであり、PyTorch を介してアテンションや低精度 GEMM などの機能を提供し、NVIDIA と AMD の最新ハードウェアに対応している。
AI深層分析を開く2026年8月3日 23:48
AI深層分析
キーポイント
Transformer 専用カーネルライブラリの提供
MSLK はアテンション、低精度 GEMM、量子化、MoE ルーティング、畳み込みを含む Transformer 負荷向けの融合 GPU カーネルライブラリであり、torch.ops.mslk.*を介してアクセス可能である。
主要ハードウェアとフレームワークの対応状況
同ライブラリは PyTorch 2.13、Python 3.10〜3.14 をサポートし、NVIDIA の CUDA 13.0/13.2(SM80, 90a, 100a, 120a)および AMD の ROCm 7.1/7.2(gfx942)に対応している。
7 つの主要ドメインによる機能分類
Attention、GEMM、Quantization、MoE、Convolution、Runtime、C++ の 7 ドメインに機能が整理されており、各カテゴリで特定の演算や最適化手法が提供されている。
ルートの選択と最適化
Transformer コアでは自動ディスパッチから始め、特定のアーキテクチャや paged KV レイアウトが必要な場合のみ明示的なバックエンドを選択する。
量子化と GEMM の整合性
線形レイヤーでは、テンソル、行、ブロック、グループ、MXFP4、NVFP4、またはパッキングされた INT4 など、GEMM ファミリに一致するスケーリング粒度を選択する。
重要な引用
MSLK is a library of fused GPU kernels for transformer workloads: attention, low-precision GEMM, quantization, MoE routing, and convolution.
Most of it is reached through torch.ops.mslk.* after import mslk.
Begin with automatic dispatch. Reach for explicit backends only when you need a specific architecture, paged KV layout, split-K, or deterministic behavior.
MSLK exposes the routing pieces independently and also includes baseline and Meta-shuffling MoE layers for composed execution.
編集コメントを表示
編集コメント
MSLK は Transformer 推論の最適化において、NVIDIA と AMD の両プラットフォームをカバーする重要なツールとして注目される。特に低精度計算や MoE 構造への対応は、大規模モデルの実用化におけるコスト削減と速度向上に直結する要素である。
Source Article
元記事を日本語で読む
本文に関係しない購読案内、埋め込み通知、サイト内プロモーションは除いています。
ソースコードから生成 · CUDA + ROCm
MSLK は、トランスフォーマーワークロード向けの融合 GPU カーネルライブラリです。アテンション計算、低精度 GEMM、量子化、MoE ルーティング、畳み込みなどが含まれます。import mslk 後に torch.ops.mslk.* を通じて利用可能です。このページでは公開 API のすべてを網羅し、さらに「どの関数を呼ぶべきか」を実践的に解説します。
最新バージョン:MSLK 1.3.0 · PyTorch 2.13
NVIDIA CUDA 13.0 / 13.2 · SM80 · 90a · 100a · 120a
AMD ROCm 7.1 / 7.2 · gfx942
Python 3.10 – 3.14
カーネルマップ
7 つのドメイン
ご自身のワークロードファミリーを選択してください。各カードをクリックすると、該当ドメインに絞ったリファレンスが開きます。
Attention fMHA 分散処理、マスク、アーキテクチャバックエンド、ツリーアテンション、MLA、ページド KV
156 シンボル →
GEMM BF16, FP8, FP4, MX, INT8, INT4 のグループ化・バッチ処理・混合入力行列積
70 シンボル →
Quantization FP8, MXFP4, NVFP4, INT4, MXFP6 への変換、パッキング、スケーリング、デクォンタイズ
54 シンボル →
MoE ルーティング、シャッフル、トークンの gather/scatter、融合活性化、構成されたエキスパート層
27 シンボル →
Convolution 低精度 FP8 の 3D コンボリューション演算子
1 シンボル →
Runtime FlyDSL JIT/AOT、デバイス検出、アーキテクチャチェック、テストデコレーター
32 シンボル →
C++ カーネル起動、アクセッサ、チューニング、タイミング、ソースコンテキスト、CUTLASS ヘルパー
84 シンボル →
ルートを選択してください
最適なカーネルへの最短経路
01 · TRANSFORMER CORE
Fused attention
まずは自動分散処理から始めましょう。特定のアーキテクチャやページド KV レイアウト、split-K、あるいは決定論的な動作が必要となる場合のみ、明示的なバックエンドを選択してください。
memory_efficient_attention へ進む →
02 · LINEAR LAYERS
Quantize, then GEMM
GEMM ファミリに合わせたスケール粒度(テンソル、行、ブロック、グループ、MXFP4、NVFP4、パッキング済み INT4)を選択してください。
03 · スパースモデル
ルート、ガザー、計算、スキャター
MSLK はルーティング機能を独立して公開するとともに、組み合わせた実行のためにベースラインおよび Meta-shuffling の MoE レイヤーも用意しています。
クイックスタート
インストールから出力まで。
これらは、主要な公開インターフェースを横断する、あえて小さく設計されたコピー可能なパスです。
# CUDA 13.0 wheel
pip install mslk --index-url https://download.pytorch.org/whl/cu130
# ROCm 7.1 wheel
pip install mslk \
--index-url https://download.pytorch.org/whl/rocm7.1/ \
--extra-index-url https://pypi.org/simpleレジスタ演算子のインポート
import mslk で mslk.so が読み込まれます。torch.ops.mslk を呼び出す前に、mslk.gemm や mslk.moe などのドメインをインポートしてください。
Python 側の登録がインストールされるようにエントリを追加します。
import torch
from mslk.attention import fmha
B, M, H, K = 2, 2048, 32, 128
q = torch.randn(B, M, H, K, device="cuda", dtype=torch.bfloat16)
k = torch.randn_like(q)
v = torch.randn_like(q)
out = fmha.memory_efficient_attention(
q, k, v,
attn_bias=fmha.LowerTriangularMask(),
)
# out: [B, M, H, K]ディスパッチ処理を有効にする
自動ディスパッチは、入力データ型、ヘッド次元、マスク、ドロップアウト、勾配の要件、およびハードウェアを評価します。バックエンドを意図的に固定する場合のみ、op=(FwOp, BwOp) を指定してください。
import torch
import mslk.gemm
from mslk.quantize.triton.fp8_quantize import quantize_fp8_row
x = torch.randn(1024, 4096, device="cuda", dtype=torch.bfloat16)
w = torch.randn(4096, 4096, device="cuda", dtype=torch.bfloat16)
xq, x_scale = quantize_fp8_row(x)
wq, w_scale = quantize_fp8_row(w)
out = torch.ops.mslk.f8f8bf16_rowwise(
xq, wq, x_scale, w_scale
)
# Conceptually: dequant(xq) @ dequant(wq).T → BF16重みは N × K の形状
MSLK の GEMM(一般行列積)演算では、通常、活性化値を [M,K]、重みを [N,K] とし、X @ W.T を計算します。計算結果のスケールレイアウトは、それを生成した量子化器と対応付けて保持してください。
import torch
from mslk.attention.fmha.merge_training import (
memory_efficient_attention_partial_autograd,
merge_attentions_autograd,
)
B, Mq, Mkv, H, K = 1, 128, 1024, 16, 128
q = torch.randn(B, Mq, H, K, device="cuda", dtype=torch.bfloat16)
k = torch.randn(B, Mkv, H, K, device="cuda", dtype=torch.bfloat16)
v = torch.randn_like(k)
k0, k1 = k.chunk(2, dim=1)
v0, v1 = v.chunk(2, dim=1)
p0 = memory_efficient_attention_partial_autograd(q, k0, v0)
p1 = memory_efficient_attention_partial_autograd(q, k1, v1)
out = merge_attentions_autograd(p0, p1)Exact softmax merge
各部分計算は、その出力と対数和指数(log-sum-exp)を保持します。マージ処理では数学的にチャンクに重み付けを行うため、これは結合された K/V 系列に対するアテンション演算と等価になります。
import torch
import mslk.moe
T, D, E = 256, 512, 8
x = torch.randn(T, D, device="cuda", dtype=torch.bfloat16)
routing_scores = torch.softmax(
torch.randn(T, E, device="cuda"), dim=-1
)
counts, experts, tokens = torch.ops.mslk.index_shuffling(
routing_scores, top_k=1
)
expert_x = mslk.moe.gather_scale_dense_tokens(
x, tokens, experts, routing_scores
)
# Replace this identity with grouped expert GEMMs + silu_mul.
expert_y = expert_x
out = torch.zeros_like(x)
mslk.moe.scatter_add_dense_tokens(out, expert_y, tokens)コンポーザブルなルーティング部品
低レベル API ではデータ移動が明示されます。コンポーザブルなモジュールには BaselineMoE またはトップ 1 のみを使用する MetaShufflingMoE を活用してください。
本ドキュメントにおける形状の読み方
このページに記載されているすべての署名は、同じ軸ラベルを持つテンソルを記述しています。これらのルールを一度覚えておけば、以下の 400 の項目を個別に説明する必要はありません。ほぼすべての場所で成り立つ一つのルールがあります:最後の次元のストライドは必ず 1 でなければならないことです。他の次元が非連続であっても例外ではありません。
Attention(アテンション)
q, k, v*[B, M, H, K]**通常のケース*
q, k, v*[B, M, G, H, K]**GQA/MQA、実験的 — K/V は自分で展開する必要があります*
out*[B, M, H, Kv]**q と同じレイアウト。最後の軸は V から取得します*
- B: バッチサイズ
- M: シーケンス長
- G: ヘッドグループ数
- H: ヘッド数
- K: ヘッド次元
可変長のバッチは、B=1 にパッキングされ、シーケンスのメタデータはマスクによって伝達されます。
GEMM(一般行列積)
x*[M, K]**活性化値*
w*[N, K]**重み — N×K であり、K×N ではありません*
out*[M, N]**計算式は x @ w.T です*
- M: トークン数
- K: 縮小次元
- N: 出力特徴量
グループ化された変種ではこのレイアウトを維持し、グループの説明を追加します。具体的には、テンソルのリスト、先頭のエキスパート軸、結合されたトークンに付随する M_sizes、またはオフセットなどです。出力は BF16 ですが、演算名に f16 が含まれる場合は例外となります。
量子化スケール
tensorwise*[1]**テンソル全体で一つのスケール*
rowwise*[M]**各行ごとに一つのスケール — FP8 の一般的なパスです*
blockwise*[⌈M/Bm⌉, ⌈K/Bk⌉]**Bm×Bk のタイルごとに一つのスケール*
量子化されたテンソルは、パッキングされたデータとそれに対応するスケールの両方を含みます。GEMM は書き込まれた粒度のものしか受け付けないため、各スケールテンソルはそれを生成した量子化器と一緒に保持する必要があります。MX 形式では E8M0 ブロック指数が追加されますが、そのレイアウトは CUDA と ROCm で異なります。これらのバッファは互換性がありません。
MoE ルーティング
scores
[T, E]
router output
indices
[T × top_k]
token and expert index pairs
counts
[E + 2]
T: トークン数
E: エキスパート数
ルーティング順序は、融合された層の中に隠されるのではなく明示的に保たれます。これにより、エキスパートごとの GEMM(行列積)計算を、連続するセグメントにわたる単一のグループ化された呼び出しとして実行することが可能になります。
サポートマトリクス
何処で何が実行されるか
実際に処理を阻害する要因となる 2 つの方向性マップがあります。1 つ目は、あなたのケースに対応できるアテンションバックエンドは何か、2 つ目は、現在使用しているデータ型(dtypes)に適合する GEMM オペレーションはどれかです。これら 2 つの情報はソースコードから読み取られますが、実行時のチェックを完全に置き換えるものではありません。実際の形状、マスク、そしてあなたの Wheel にコンパイルされたアーキテクチャが最終的な決定を下します。
memory_efficient_attention の背後にあるアテンション — バックエンド
この表はアテンション専用です。各行は mslk.attention.fmha 配下の順方向・逆方向演算子クラスを表しています。
op=None を指定すればディスパッチが自動的に最適なものを選定します。特定の演算子を明示したい場合は、op=(FwOp, BwOp) の形式で渡してください。
なお、GEMM、MoE、量子化関連の演算子は、この表を経由してディスパッチされません。
| バックエンド | op=でピン留めする | データ型 | 逆伝播 | ドロップアウト | 可変長 / ページ化 | 以下の場合に使用してください |
|---|---|---|---|---|---|---|
| CUTLASS NVIDIA · 任意のコンパイル済みアーキテクチャ | cutlass.FwOp cutlass.BwOp | FP32 · FP16 · BF16 | あり | あり | マスク依存 | ヘッド次元が通常と異なる場合、または FP32 を使用する必要がある場合。 |
| CUTLASS Blackwell NVIDIA · SM100 | cutlass_blackwell.FwOp…FwOpDecode · …BwOp | FP16 · BF16 | あり | なし | 可変長のみ | Blackwell において、チューニング済みプリフェッチとデコードのペアに対して。 |
| Flash NVIDIA · SM80 | flash.FwOp flash.BwOp | FP16 · BF16 | あり | あり | 可変長 · ページ化(順伝播) | 通常のトレーニングと推論におけるデフォルトの高速パス。 |
| Flash3 NVIDIA · SM80–SM90 | flash3.FwOp…BwOp · …FwOp_KVSplit | FP16 · BF16 · FP8 | あり | なし | 可変長 · ページ化(順伝播) | KV スプリットを必要とする長文コンテキストの順伝播パス。 |
| CuTe Hopper NVIDIA · SM90 | cute_hopper.FwOp cute_hopper.BwOp | FP16 · BF16 | あり | なし | 可変長のみ | Hopper 上で CuTe DSL カーネルを使用したい場合。 |
| CuTe Blackwell NVIDIA · SM100 | cute_blackwell.FwOp…FwOpDecode · …BwOp | FP16 · BF16 · FP8 | あり | なし | 可変長 · ページ化 | ページ化された KV キャッシュに対する Blackwell でのデコーディング。 |
| CK AMD · サポートされる gfx | ck.FwOp ck.BwOp | FP16 · BF16 | あり | あり | バイアス依存 | 一般的な ROCm パス;バイアスの勾配を扱える唯一のパス。 |
| CK デコーダ / split-K AMD · サポートされる gfx | ck_decoder.FwOp ck_splitk.FwOp_S1 … _S128 | FP16 · BF16 · FP32 | 順伝播のみ | なし | 可変長 · ページ化 | ROCm でのデコーディング、またはスプリット数を自分で固定したい場合。 |
| Triton split-K NVIDIA + AMD · Triton | triton_splitk.FwOp…FwOp_S1 … _S128 | FP16 · BF16 · FP8 qquantized KV | 順伝播のみ | なし | 可変長 · ページ化 | KV キャッシュが INT4 または FP8 の場合;このバックエンドはそれを読み取ります。 |
| Flash MTIA MTIA · ビルド依存 | flash_mtia.FwOp flash_mtia.BwOp | FP16 · BF16 | あり | あり | 可変長のみ | MTIA 上で実行している場合。 |
GEMM — 低精度演算の選択
ここでは自動選定は行われません。あなたが既に保持しているデータ型(dtypes)に一致する演算を明示的に呼び出す必要があります。また、その演算が期待する粒度に合わせてスケール値を手動で渡す責任もあなたにあります。
演算子の名称には契約内容が暗記されています。例えば f8f8bf16_rowwise は、「FP8 入力 × FP8 入力 → BF16 出力」を意味し、スケールは行単位(row-wise)で指定されます。
インポート直後であれば必ず対応する演算が存在しますが、もし現在のアーキテクチャに該当するカーネルが用意されていない場合は、呼び出し時にエラーが発生します。
| 呼び出し | 入力 → 出力 | NVIDIA | AMD | 供給する必要があるスケール |
|---|---|---|---|---|
| f8f8bf16_rowwise…_batched · …_grouped_stacked | FP8 × FP8 → BF16 | SM90–SM100 でテスト済み | gfx942, gfx950 | x と w の各行ごとに 1 つ — quantize_fp8_row から。 |
| f8f8bf16_blockwise | FP8 × FP8 → BF16 | SM90–SM100 でテスト済み | gfx942, gfx950 | Bm×Bk タイルごとに 1 つ — ブロック次元は引数。 |
| f8f8bf16_groupwise | FP8 × FP8 → BF16 | SM90–SM100 でテスト済み | gfx942, gfx950 | K 方向に固定された 128 のグループ。 |
| f8f8f16_rowwise…_preshuffle | FP8 × FP8 → FP16 | ROCm のみ | gfx942, gfx950 | 行ごとの処理。上記演算の FP16 出力版。 |
| bf16bf16bf16_grouped_stacked…_cat · …_dynamic | BF16 × BF16 → BF16 | SM90+ でテスト済み | gfx942 でテスト済み | なし — ただし、連結された x, w[G,N,K] と M_sizes を渡すこと。 |
| i8i8bf16i8i8bf16_dynamic | INT8 × INT8 → BF16 | SM80+ | gfx942, gfx950 | スカラー(静的)またはテンソルスケール(動的)。 |
| bf16i4bf16_rowwise…_batched | BF16 × INT4 → BF16 | SM90 ネイティブ | ROCm Triton | パッキングされた w[N,K/2] に加え、グループスケールとゼロポイント。 |
| bf16i4bf16_shuffledf8i4bf16_shuffled | BF16 / FP8 × INT4 → BF16 | SM90 専用 | 非公開 | 上記と同様。ただし、重みに対して preshuffle_i4 を 1 回実行した後。 |
| f4f4bf16…_grouped_mm · …_grouped_stacked | FP4 × FP4 → BF16 | SM100+ | gfx950 | 3 つのフォーマットに対応する 1 つの演算 — NVFP4、MXFP4 または MXFP4-16 は、渡すスケールによって選択される。MXFP4-16 と NVFP4 は CUDA のみ対応。 |
| f4f4bf16_ultra_grouped_mm | FP4 × FP4 → BF16 | SM10.3+, CUDA 13+ | なし | オフセット付きグループ NVFP4。各演算子ごとに独立したグローバルスケールを使用。 |
| mx8mx4bf16mx8mx4/mx8mx8…_grouped_mm | MXFP8 × MXFP4 → BF16 | SM100+ | gfx950 | E8M0 ブロック指数。レイアウトはプラットフォームによって異なる;ROCm の MX8×MX4 はハイブリッド。 |
| mx8mx6bf16mx6mx6bf16 | MXFP8 / MXFP6 × MXFP6 → BF16 | SM100+ | なし | ブロック指数。E2M3 値 4 つを 3 バイトにパッキング。 |
| bf16x9_gemm | FP32 × FP32 → FP32 | CUDA 13+ | なし | なし — cuBLAS が FP32 を 9 つの BF16 積でエミュレート。 |
| mixed_input_gemmmslk.gemm.blackwell_mixed_input_gemm | INT4 / INT8 × BF16 / FP16 | SM100 | なし | CuTe DSL カーネル:狭い演算子 1 つに対して広い演算子 1 つ。 |
完全リファレンス
記号、概念("paged" や "rowwise")、モジュール、データ型、プラットフォームで絞り込み可能です。項目を開くと、シグネチャ、動作、サポート契約、注意点、ソースコードを確認できます。
ここで文書化されているものの範囲
- 含まれるもの:エクスポートされ直接呼び出せる Python API、登録されたディスパッチャースキーマ、選択可能なバックエンドクラス、統合レベルの生オペレーション(raw ops)、公開された C++ ヘッダー。
- 含まれないもの:アンダースコア付きのカーネル本体、Meta/fake 実装、ベンチマーク、テスト専用リファレンスルーチン(ただし、文書化された統合契約を公開している場合は除く)。
文書化済み記号 424 件中 424 件を表示中。
memory_efficient_attention#
mslk.attention.fmha
自動バックエンドディスパッチ機能を備え、Autograd をサポートする融合アテンションです。
公開関数:NVIDIA / AMD
memory_efficient_attention(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None) -> Tensor[B,M,K]、[B,M,H,K]、または実験的な [B,M,G,H,K] 形式の入力を接受します。スケーリングされた QKᵀ を計算し、最適化されたバイアスまたは密なテンソルバイアスを適用した上で、ソフトマックス/ドロップアウト処理を行います。その後、完全なアテンション行列をメモリ上に展開することなく V と乗算します。
戻り値: クエリレイアウトに従ったアテンション出力。最後の次元は V のヘッド次元に置き換えられます。
メソッド / コンストラクタ
op=(FwOp, BwOp):フォワードおよびバックワード演算クラスを明示的に固定します。attn_bias=AttentionBias | Tensor | None:可能であれば最適化されたマスクを使用しますが、任意の密なテンソルは一般的に処理速度が遅くなります。
注意事項と制約
最後の次元はストライド 1 でなければなりません。他の次元は非連続でも構いません。
GQA/MQA の場合、K/V ヘッドをリシェイプして明示的に展開する必要があります。MSLK はこれらを自動的にブロードキャストしません。
推奨されるディスパッチには op=None を設定し、特定のバックエンドに固定する場合は (順伝播関数,逆伝播関数) のクラスタプルを渡してください。
GroupAttention / Core fMHA
サポート: NVIDIA · AMD · MTIA
トピック:fMHA · dispatch · BMK · BMHK · BMGHK
ソース:mslk/attention/fmha/__init__.py
memory_efficient_attention_forward#
mslk.attention.fmha
手動の逆伝播コンテキストを保持しない、順伝播専用のアテンションパスです。
パブリック関数:NVIDIA · AMD
memory_efficient_attention_forward(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None) -> Tensor高レベル API と同じ入力を検証・正規化し、順伝播用のバックエンドを選択してアテンション出力のみを返します。
戻り値: アテンション出力テンソル。
注意事項と制約
- op には演算子ペアではなく、順伝播オペレータのクラスを渡してください。
- グラデントや LSE (Log-Sum-Exp) が必要ない場合にこのパスを使用します。
GroupAttention / Core fMHA
サポート:NVIDIA · AMD · MTIA
トピック:fMHA · dispatch · BMK · BMHK · BMGHK
ソース:mslk/attention/fmha/__init__.py
memory_efficient_attention_forward_requires_grad#
mslk.attention.fmha
手動で順伝播と逆伝播を行い、出力と対数和指数(log-sum-exp)を返す API です。
公開関数: NVIDIA, AMD
memory_efficient_attention_forward_requires_grad(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None) -> tuple[Tensor, Tensor]名前とは裏腹に、これは自動微分(autograd)を含まない明示的な非自動微分 API です。返される LSE は、memory_efficient_attention_backward で使用されるコンテキスト情報となります。
戻り値: (出力, lse)
注記と制約
- 本手動 API では、ゼロ以外のドロップアウトはエラーとして扱われます。
- 順伝播と逆伝播の演算子は、可変長の LSE レイアウトについて一致している必要があります。
GroupAttention / Core fMHA
対応: NVIDIA · AMD · MTIA
トピック: fMHA · dispatch · BMK · BMHK · BMGHK
ソースコード: mslk/attention/fmha/__init__.py
memory_efficient_attention_backward#
mslk.attention.fmha
出力と LSE のペアに対する明示的な逆伝播パスです。
公開関数: NVIDIA, AMD
memory_efficient_attention_backward(grad, output, lse, query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None) -> tuple[Tensor, Tensor, Tensor]元の Q/K/V、順伝播の出力、LSE、および上位からの勾配を受け取ります。互換性のある逆伝播カーネルを自動的にディスパッチしますが、指定された場合はそれを使用します。
戻り値: (dq, dk, dv)。これらは元の入力形状にリシェイプされます。
注記と制約
- 手動の順伝播/逆伝播 API ではドロップアウトはサポートされません。
- この戻り値の仕様には、密なテンソルバイアスの勾配は含まれません。
memory_efficient_attention_partial#
mslk.attention.fmha
1 つの非連続な K/V シャードに対して、出力と LSE を計算します。
Public function NVIDIA AMD
memory_efficient_attention_partial(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None, _allow_backward=False) -> tuple[Tensor, Tensor]同じクエリを保持したままキー/バリューのチャンクを分割して繰り返し呼び出し、その後 merge_attentions で結果を結合してください。これにより、正確な split-KV アテンションが可能になります。
戻り値: (partial_output, partial_lse)
注意事項と制約
- Dropout はサポートされていません。
- パブリックパスはフォワードのみです。_allow_backward はプライベートであり、意図的に制限されています。
- 安全なトレーニングには merge_training ワラッパーを使用してください。
GroupAttention / Core fMHA
Support NVIDIA · AMD · MTIA
トピック fMHA · dispatch · BMK · BMHK · BMGHK
ソース mslk/attention/fmha/__init__.py
merge_attentions#
mslk.attention.fmha
K/V チャンクに対して計算されたアテンションの、log-sum-exp 補正付きの結合。
Public function NVIDIA AMD
merge_attentions(attn_split, lse_split, write_lse=True, output_dtype=None) -> tuple[Tensor, Optional[Tensor]]チャンクシーケンスまたは先頭のチャンク軸に沿ってスタックされたテンソルを受け取ります。これは部分的な出力を平均化するのではなく、チャンクの結合全体に対する正確に正規化された出力を計算します。
戻り値: write_lse=True の場合は (merged_output, merged_lse)、それ以外は (merged_output, None)。
注意事項と制約
- この関数を通じた直接の autograd はサポートされていません。merge_attentions_autograd を使用してください。
- 勾配を必要とする入力には、write_lse=True の設定が必要です。
GroupAttention / Core fMHA
NVIDIA、AMD、MTIA をサポート
トピック:fMHA、dispatch、BMK、BMHK、BMGHK
ソースコード:mslk/attention/fmha/__init__.py
torch.ops.mslk.memory_efficient_attention_forward#
torch.ops.mslk
バイアスをオプションで指定できる、torch.compile 対応のフォワードアテンション演算です。
低レベル torch オペレーション(NVIDIA / Meta / fake)
torch.ops.mslk.memory_efficient_attention_forward(q, k, v, b=None, p=0.0, scale=None) -> Tensorこれらのカスタムライブラリラッパーは、ディスパッチ処理を torch.compile のトレース外に保ちつつ、フォワード専用の簡略化された契約のみを公開します。
戻り値: 入力クエリ q と形状が一致するアテンション出力テンソル。
注意事項と制約
- オペレーションや出力データ型(output_dtype)の明示的な引数は存在しません。
- キー(K)とバリュー(V)のヘッド次元は一致している必要があります。
- トレース安全性が保証されているのは、特定のバイアス形式のみです。
グループアテンション / torch.compile 対応ラッパー
NVIDIA、Meta / fake をサポート
トピック:torch.compile、カスタムオペレーション、フォワード
ソースコード:mslk/attention/fmha/__init__.py
torch.ops.mslk.memory_efficient_attention_forward_with_bias#
torch.ops.mslk
明示的なバイアステンソルを必要とする、torch.compile 対応のフォワードアテンション演算です。
低レベル torch オペレーション(NVIDIA / Meta / fake)
torch.ops.mslk.memory_efficient_attention_forward_with_bias(q, k, v, b, p=0.0, scale=None) -> Tensorこれらのカスタムライブラリラッパーは、ディスパッチ処理を torch.compile のトレース外に保ちつつ、フォワード専用の簡略化された契約のみを公開します。
戻り値: 入力クエリ q と形状が一致するアテンション出力テンソル。
注意事項と制約
- オプや出力データ型の引数は明示しません。
- K と V のヘッド次元は一致している必要があります。
- トレース安全性が保証されるのは、特定のバイアス形式のみです。
GroupAttention / コンパイル対応のラッパー
サポート: NVIDIA · Meta / fake
トピック:torch.compile · カスタムオペレーション · フォワード
ソース:mslk/attention/fmha/__init__.py
Partial#
mslk.attention.fmha.merge_training
部分アテンションの出力とその結合コンテキストを扱う、自動微分用のキャリアです。
公開クラス NVIDIA AMD
Partial(attn: Tensor, lse: Tensor, placeholder: Tensor)通常、ユーザーは Partial を直接構築するのではなく、memory_efficient_attention_partial_autograd から受け取ります。
戻り値: merge_attentions_autograd で消費される軽量オブジェクトを返します。
メソッド / コンストラクタ
is_bmghk() -> bool
格納された出力がグループ化ヘッドの BMGHK レイアウトを使用しているかどうかを報告します。
apply(fn: Callable[[Tensor], Tensor]) -> Partial
埋め込み次元を操作してはならない、レイアウトを保持する変換を適用します。
GroupAttention / Trainable partial attention
SupportNVIDIA · AMD
Topics autograd · split KV · LSE
Source mslk/attention/fmha/merge_training.py
memory_efficient_attention_partial_autograd#
mslk.attention.fmha.merge_training
部分アテンションのオートグラッド対応ラッパー。
Public function NVIDIA AMD
memory_efficient_attention_partial_autograd(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None) -> PartialQ/K/V の記録を行い、隠されたプレースホルダー勾配を用いて、マージされた出力と完全な LSE を各シャードの逆伝播パスへルーティングします。
戻り値: パーシャル(部分結果)
注意事項・制約
- 引数は memory_efficient_attention_partial と同様です。
- 根本的なパーシャルパスでは、ドロップアウトはまだサポートされていません。
GroupAttention / 学習可能な部分アテンション
対応ハードウェア: NVIDIA · AMD
トピック: autograd · split KV · LSE
ソースコード: mslk/attention/fmha/merge_training.py
merge_attentions_autograd#
mslk.attention.fmha.merge_training
正しい勾配を伴って、1 つ以上の Partial オブジェクトをマージします。
パブリック関数: NVIDIA · AMD
merge_attentions_autograd(*partials: Partial) -> Tensor複数のシャードがある場合、正確な LSE 結合を実行します。単一の Partial を渡した場合はその出力を返しますが、自動微分の仕組みは維持されます。
戻り値: 結合されたアテンションの出力。
注意事項と制約
- パーシャルなしで呼び出されると ValueError が発生します。
GroupAttention / トレーナブルなパーシャルアテンション
対応ハードウェア:NVIDIA、AMD
トピック:autograd · split KV · LSE
ソースコード: mslk/attention/fmha/merge_training.py
AttentionBias#
mslk.attention.fmha.attn_bias
最適化されたアテンションバイアス記述のための抽象ベースクラス。
公開クラス:NVIDIA、AMD
AttentionBias()AttentionBias オブジェクトは、Q×K 行列全体を生成することなく、スパース性や加算バイアスを記述します。これにより、互換性のあるカーネルがマスクを直接符号化できるようになります。
戻り値: fMHA の attn_bias パラメータとして受け入れられるオブジェクト。
メソッド / コンストラクタ
materialize(shape, dtype=torch.float32, device='cpu') -> Tensor
デバッグや参照チェック用の密なバイアスを構築します。意図的に低速に設計されています。
to(device)
保存されたシーケンスのメタデータまたはテンソルベースのバイアスを指定したデバイスへ移動します。
注記と制約
- サブクラスでは、materialize と(状態が保存される場合)to(device) を定義する必要があります。
GroupAttention / バイアスとマスク
サポート: NVIDIA · AMD · MTIA · CPU / Python
トピック: attention bias · mask
ソースコード:mslk/attention/fmha/attn_bias.py
LowerTriangularMask#
mslk.attention.fmha.attn_bias
左上揃いの因果マスク。
Public class NVIDIA AMD
LowerTriangularMask(device: Optional[torch.device] = None)AttentionBias オブジェクトは、Q×K 行列を実際に生成することなく、スパース性や加算バイアスを記述します。これにより、対応するカーネルがマスクを直接符号化できるようになります。
戻り値: fMHA の attn_bias パラメータとして受け入れられるオブジェクト。
メソッド / コンストラクタ
add_bias(bias: Tensor) -> LowerTriangularMaskWithTensorBias
因果マスクと任意の加算テンソルを結合します。
materialize(shape, dtype=torch.float32, device='cpu') -> Tensor
対角線上およびその下にはゼロを、それより上には負の無限大(−∞)を生成します。
注記と制約
デバイスコンストラクタの引数は互換性のために保持されていますが、実際には無視されます。
GroupAttention / バイアスとマスク
サポート: NVIDIA, AMD, MTIA, CPU / Python
トピック: attention bias, mask
ソース: mslk/attention/fmha/attn_bias.py
LowerTriangularMaskWithTensorBias#
mslk.attention.fmha.attn_bias
左上の因果マスクに、密な加算テンソルバイアスを組み合わせたものです。
Public class NVIDIA AMD
LowerTriangularMaskWithTensorBias(bias: Tensor)AttentionBias オブジェクトは、Q×K 行列全体を明示的に生成することなく、スパース性や加算バイアスを記述します。これにより、対応するカーネルがマスクを直接符号化することが可能になります。
戻り値: fMHA の attn_bias として受け入れられるオブジェクト。
メソッドとコンストラクタ
materialize(shape, dtype=torch.float32, device='cpu') -> Tensor
デバッグや参照チェック用の稠密バイアスを構築します。意図的に低速に設計されています。
to(device)
保存されたシーケンスメタデータまたはテンソルバイアスを指定したデバイスへ移動します。
注記と制約事項
- 純粋な因果マスクの場合と比較すると、バックエンドのサポート範囲は限定的です。
GroupAttention / バイアスとマスク
対応ハードウェア: NVIDIA · AMD · MTIA · CPU / Python
トピック: attention bias(アテンションバイアス), mask(マスク)
ソースコード: mslk/attention/fmha/attn_bias.py
LowerTriangularFromBottomRightMask#
mslk.attention.fmha.attn_bias
Mq ≠ Mkv の場合、右下にアライメントされた因果マスク。
PublicclassNVIDIAAMD
LowerTriangularFromBottomRightMask()AttentionBias オブジェクトは、完全な Q×K 行列を生成することなく、スパース性や加算バイアスを記述します。これにより、対応するカーネルがマスクを直接符号化できるようになります。
戻り値: fMHA の attn_bias パラメータとして受け入れられるオブジェクト。
メソッド / コンストラクタ
make_local_attention(window_size: int) -> LowerTriangularFromBottomRightLocalAttentionMask
因果領域を末尾のウィンドウに制限します。
GroupAttention / バイアスとマスク
サポート: NVIDIA · AMD · MTIA · CPU / Python
トピック: attention bias · mask
ソース mslk/attention/fmha/attn_bias.py
LowerTriangularFromBottomRightLocalAttentionMask#
mslk.attention.fmha.attn_bias
右下から始まる因果スライディングウィンドウマスク。
PublicclassNVIDIAAMD
LowerTriangularFromBottomRightLocalAttentionMask(_window_size: int)AttentionBias オブジェクトは、Q×K 行列を明示的に作成せずにスパース性や加算バイアスを記述するもので、対応するカーネルがマスクを直接符号化できるようにします。
戻り値: fMHA の attn_bias パラメータとして受け入れられるオブジェクト。
メソッド / コンストラクタ
materialize(shape, dtype=torch.float32, device='cpu') -> Tensor
デバッグや参照チェック用の密なバイアスを構築します。意図的に低速です。
to(device)
保存されたシーケンスメタデータまたはテンソルバイアスを指定したデバイスへ移動します。
GroupAttention / バイアスとマスク
SupportNVIDIA · AMD
原文を表示
Generated from source · CUDA + ROCm
MSLK is a library of fused GPU kernels for transformer workloads: attention, low-precision GEMM, quantization, MoE routing, and convolution. Most of it is reached through torch.ops.mslk.* after import mslk. This page documents every public surface and, more importantly, tells you which one to call.
LatestMSLK 1.3.0 · PyTorch 2.13
NVIDIACUDA 13.0 / 13.2 · SM80 · 90a · 100a · 120a
AMDROCm 7.1 / 7.2 · gfx942
Python3.10 – 3.14
Kernel map
Seven domains.
Pick the workload family you are working on — each card opens the reference filtered to that domain.
[QK
Attention
fMHA dispatch, masks, architecture backends, tree attention, MLA, and paged KV.
156 symbols →](#api-reference)
[AB
GEMM
BF16, FP8, FP4, MX, INT8, INT4, grouped, batched, and mixed-input matrix products.
70 symbols →](#api-reference)
[Q
Quantization
FP8, MXFP4, NVFP4, INT4, and MXFP6 conversion, packing, scaling, and dequantization.
54 symbols →](#api-reference)
[E×
MoE
Routing, shuffling, token gather/scatter, fused activations, and composed expert layers.
27 symbols →](#api-reference)
[3D
Convolution
The low-precision FP8 3D convolution operator.
1 symbol →](#api-reference)
[RT
Runtime
FlyDSL JIT/AOT, device detection, architecture checks, and test decorators.
32 symbols →](#api-reference)
[++
C++
Kernel launch, accessors, tuning, timing, source context, and CUTLASS helpers.
84 symbols →](#api-reference)
Choose a route
The shortest path to the right kernel.
01 · TRANSFORMER CORE
Fused attention
Begin with automatic dispatch. Reach for explicit backends only when you need a specific architecture, paged KV layout, split-K, or deterministic behavior.
Start with memory_efficient_attention →
02 · LINEAR LAYERS
Quantize, then GEMM
Choose a scale granularity that matches the GEMM family: tensor, row, block, group, MXFP4, NVFP4, or packed INT4.
03 · SPARSE MODELS
Route, gather, compute, scatter
MSLK exposes the routing pieces independently and also includes baseline and Meta-shuffling MoE layers for composed execution.
Quick start
From install to output.
These are deliberately small, copyable paths through the major public surfaces.
# CUDA 13.0 wheel
pip install mslk --index-url https://download.pytorch.org/whl/cu130
# ROCm 7.1 wheel
pip install mslk \
--index-url https://download.pytorch.org/whl/rocm7.1/ \
--extra-index-url https://pypi.org/simpleImport registers operators
import mslk loads mslk.so. Import a domain such as mslk.gemm or mslk.moe before calling its torch.ops.mslk entries so Python-side registrations are installed.
import torch
from mslk.attention import fmha
B, M, H, K = 2, 2048, 32, 128
q = torch.randn(B, M, H, K, device="cuda", dtype=torch.bfloat16)
k = torch.randn_like(q)
v = torch.randn_like(q)
out = fmha.memory_efficient_attention(
q, k, v,
attn_bias=fmha.LowerTriangularMask(),
)
# out: [B, M, H, K]Let dispatch work
Automatic dispatch evaluates the input dtype, head dimension, mask, dropout, gradient requirements, and hardware. Supply op=(FwOp, BwOp) only when deliberately pinning a backend.
import torch
import mslk.gemm
from mslk.quantize.triton.fp8_quantize import quantize_fp8_row
x = torch.randn(1024, 4096, device="cuda", dtype=torch.bfloat16)
w = torch.randn(4096, 4096, device="cuda", dtype=torch.bfloat16)
xq, x_scale = quantize_fp8_row(x)
wq, w_scale = quantize_fp8_row(w)
out = torch.ops.mslk.f8f8bf16_rowwise(
xq, wq, x_scale, w_scale
)
# Conceptually: dequant(xq) @ dequant(wq).T → BF16Weights are N × K
Most MSLK GEMMs take activations [M,K] and weights [N,K], then compute X @ W.T. Keep scale layout paired with the quantizer that produced it.
import torch
from mslk.attention.fmha.merge_training import (
memory_efficient_attention_partial_autograd,
merge_attentions_autograd,
)
B, Mq, Mkv, H, K = 1, 128, 1024, 16, 128
q = torch.randn(B, Mq, H, K, device="cuda", dtype=torch.bfloat16)
k = torch.randn(B, Mkv, H, K, device="cuda", dtype=torch.bfloat16)
v = torch.randn_like(k)
k0, k1 = k.chunk(2, dim=1)
v0, v1 = v.chunk(2, dim=1)
p0 = memory_efficient_attention_partial_autograd(q, k0, v0)
p1 = memory_efficient_attention_partial_autograd(q, k1, v1)
out = merge_attentions_autograd(p0, p1)Exact softmax merge
Each partial carries its output and log-sum-exp. The merge reweights chunks mathematically, so it is equivalent to attention over the concatenated K/V sequence.
import torch
import mslk.moe
T, D, E = 256, 512, 8
x = torch.randn(T, D, device="cuda", dtype=torch.bfloat16)
routing_scores = torch.softmax(
torch.randn(T, E, device="cuda"), dim=-1
)
counts, experts, tokens = torch.ops.mslk.index_shuffling(
routing_scores, top_k=1
)
expert_x = mslk.moe.gather_scale_dense_tokens(
x, tokens, experts, routing_scores
)
# Replace this identity with grouped expert GEMMs + silu_mul.
expert_y = expert_x
out = torch.zeros_like(x)
mslk.moe.scatter_add_dense_tokens(out, expert_y, tokens)Composable routing pieces
The low-level API makes data movement explicit. For a composed module, use BaselineMoE or the top-1-only MetaShufflingMoE.
Conventions
How to read a shape in these docs.
Every signature on this page describes tensors with the same axis letters. Learn them once and the 400 entries below stop needing individual explanation. One rule holds nearly everywhere: the last dimension must have stride 1, even when the others are non-contiguous.
Attention
q, k, v*[B, M, H, K]**the usual case*
q, k, v*[B, M, G, H, K]**GQA/MQA, experimental — you expand K/V yourself*
out*[B, M, H, Kv]**same layout as q, last axis from V*
Bbatch
Msequence
Ghead groups
Hheads
Khead dim
Variable-length batches are packed into B=1 with sequence metadata carried by the mask instead.
GEMM
x*[M, K]**activations*
w*[N, K]**weights — N×K, not K×N*
out*[M, N]**computed as x @ w.T*
Mtokens
Kreduction dim
Noutput features
Grouped variants keep this layout and add a group description: a list of tensors, a leading expert axis, M_sizes alongside concatenated tokens, or offsets. Output is BF16 unless the op name says f16.
Quantization scales
tensorwise*[1]**one scale for the whole tensor*
rowwise*[M]**one per row — the common FP8 path*
blockwise*[⌈M/Bm⌉, ⌈K/Bk⌉]**one per Bm×Bk tile*
A quantized tensor is the packed data *plus* its scales — a GEMM only accepts the granularity it was written for, so keep each scale tensor with the quantizer that produced it. MX formats add E8M0 block exponents whose layout differs between CUDA and ROCm; those buffers are not interchangeable.
MoE routing
scores*[T, E]**router output*
indices*[T × top_k]**token and expert index pairs*
counts*[E + 2]**tokens routed per expert*
Ttokens
Eexperts
Routing order stays explicit rather than hidden inside a fused layer, which is what lets the expert GEMM run as one grouped call over contiguous segments.
Support matrices
What runs where.
Two orientation maps for the choices that actually block you: which attention backend can serve your case, and which GEMM op matches the dtypes you already have. Both are read from source, and neither replaces the runtime checks — exact shapes, masks, and the archs compiled into your wheel still decide.
Attention — backends behind memory_efficient_attention
This table is only about attention. Every row is a forward/backward operator class under mslk.attention.fmha. Leave op=None and dispatch picks one for you; pass op=(FwOp, BwOp) when you need a specific one. GEMM, MoE and quantization ops do not dispatch through this.
| Backend | Pin it with op= | Dtypes | Bwd | Dropout | Varlen / paged | Reach for it when |
|---|---|---|---|---|---|---|
| CUTLASSNVIDIA · any compiled arch | cutlass.FwOpcutlass.BwOp | FP32 · FP16 · BF16 | Yes | Yes | Mask-dependent | You need an unusual head dimension, or FP32. |
| CUTLASS BlackwellNVIDIA · SM100 | cutlass_blackwell.FwOp…FwOpDecode · …BwOp | FP16 · BF16 | Yes | No | Varlen only | On Blackwell, for the tuned prefill and decode pair. |
| FlashNVIDIA · SM80 | flash.FwOpflash.BwOp | FP16 · BF16 | Yes | Yes | Varlen · paged fwd | Default fast path for ordinary training and inference. |
| Flash3NVIDIA · SM80–SM90 | flash3.FwOp…BwOp · …FwOp_KVSplit | FP16 · BF16 · FP8 | Yes | No | Varlen · paged (fwd) | Long-context forward passes that want split-KV. |
| CuTe HopperNVIDIA · SM90 | cute_hopper.FwOpcute_hopper.BwOp | FP16 · BF16 | Yes | No | Varlen only | You want the CuTe DSL kernels on Hopper. |
| CuTe BlackwellNVIDIA · SM100 | cute_blackwell.FwOp…FwOpDecode · …BwOp | FP16 · BF16 · FP8 | Yes | No | Varlen · paged | Decoding on Blackwell against a paged KV cache. |
| CKAMD · supported gfx | ck.FwOpck.BwOp | FP16 · BF16 | Yes | Yes | Bias-dependent | General ROCm path; the only one with bias gradients. |
| CK decoder / split-KAMD · supported gfx | ck_decoder.FwOpck_splitk.FwOp_S1 … _S128 | FP16 · BF16 · FP32 | Fwd | No | Varlen · paged | ROCm decode, or you want to fix the split count yourself. |
| Triton split-KNVIDIA + AMD · Triton | triton_splitk.FwOp…FwOp_S1 … _S128 | FP16 · BF16 · FP8 qquantized KV | Fwd | No | Varlen · paged | Your KV cache is INT4 or FP8 — this backend reads it. |
| Flash MTIAMTIA · build-dependent | flash_mtia.FwOpflash_mtia.BwOp | FP16 · BF16 | Yes | Yes | Varlen only | You are running on MTIA. |
GEMM — picking a low-precision op
Nothing here is auto-selected: you call the op that matches the dtypes you already hold, and it is your job to hand it scales in the exact granularity it expects. Names encode the contract — f8f8bf16_rowwise is FP8 in × FP8 in → BF16 out, one scale per row. An op always exists after import; it raises at call time if your wheel has no kernel for the arch.
| Call | In → out | NVIDIA | AMD | Scales you must supply |
|---|---|---|---|---|
| f8f8bf16_rowwise…_batched · …_grouped_stacked | FP8 × FP8 → BF16 | SM90–SM100 tested | gfx942, gfx950 | One per row of x and of w — from quantize_fp8_row. |
| f8f8bf16_blockwise | FP8 × FP8 → BF16 | SM90–SM100 tested | gfx942, gfx950 | One per Bm×Bk tile; block dims are arguments. |
| f8f8bf16_groupwise | FP8 × FP8 → BF16 | SM90–SM100 tested | gfx942, gfx950 | Fixed groups of 128 along K. |
| f8f8f16_rowwise…_preshuffle | FP8 × FP8 → FP16 | ROCm only | gfx942, gfx950 | Rowwise. The FP16-output twin of the op above. |
| bf16bf16bf16_grouped_stacked…_cat · …_dynamic | BF16 × BF16 → BF16 | SM90+ tested | gfx942 tested | None — but pass concatenated x, w[G,N,K] and M_sizes. |
| i8i8bf16i8i8bf16_dynamic | INT8 × INT8 → BF16 | SM80+ | gfx942, gfx950 | One scalar (static) or a tensor scale (dynamic). |
| bf16i4bf16_rowwise…_batched | BF16 × INT4 → BF16 | SM90 native | ROCm Triton | Packed w[N,K/2] plus group scale and zero point. |
| bf16i4bf16_shuffledf8i4bf16_shuffled | BF16 / FP8 × INT4 → BF16 | SM90 exactly | Not exposed | As above, after running preshuffle_i4 on the weights once. |
| f4f4bf16…_grouped_mm · …_grouped_stacked | FP4 × FP4 → BF16 | SM100+ | gfx950 | One op for three formats — NVFP4, MXFP4 or MXFP4-16 is selected by the scales you pass. MXFP4-16 and NVFP4 are CUDA-only. |
| f4f4bf16_ultra_grouped_mm | FP4 × FP4 → BF16 | SM10.3+, CUDA 13+ | No | Offset-grouped NVFP4, with separate global scales per operand. |
| mx8mx4bf16mx8mx4/mx8mx8…_grouped_mm | MXFP8 × MXFP4 → BF16 | SM100+ | gfx950 | E8M0 block exponents. Layout differs by platform; ROCm MX8×MX4 is hybrid. |
| mx8mx6bf16mx6mx6bf16 | MXFP8 / MXFP6 × MXFP6 → BF16 | SM100+ | No | Block exponents, with four E2M3 values packed into three bytes. |
| bf16x9_gemm | FP32 × FP32 → FP32 | CUDA 13+ | No | None — cuBLAS emulates FP32 with nine BF16 products. |
| mixed_input_gemmmslk.gemm.blackwell_mixed_input_gemm | INT4 / INT8 × BF16 / FP16 | SM100 | No | CuTe DSL kernel: one narrow operand against one wide operand. |
Complete reference
Filter by symbol, concept (“paged”, “rowwise”), module, dtype or platform. Open an entry for its signature, behavior, support contract, caveats, and source.
What counts as documented here
Included: exported and directly callable Python APIs, registered dispatcher schemas, selectable backend classes, integration-level raw ops, and published C++ headers. Excluded: underscore-only kernel bodies, Meta/fake implementations, benchmarks, and test-only reference routines — unless they expose a documented integration contract.
Showing 424 of 424 documented symbols.
memory_efficient_attention#
mslk.attention.fmha
Autograd-enabled fused attention with automatic backend dispatch.
PublicfunctionNVIDIAAMD
memory_efficient_attention(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None) -> TensorAccepts [B,M,K], [B,M,H,K], or experimental [B,M,G,H,K] inputs. It computes scaled QKᵀ, applies an optimized bias or dense tensor bias, softmax/dropout, then multiplies V without materializing the full attention matrix.
Returns: Attention output in the query layout, with its last dimension replaced by the V head dimension.
Methods / constructors
op=(FwOp, BwOp)Explicitly pins forward and backward operator classes.
attn_bias=AttentionBias | Tensor | NoneUses optimized masks when possible; arbitrary dense tensors are generally slower.
Notes & constraints
- The last dimension must have stride 1; other dimensions may be non-contiguous.
- For GQA/MQA, reshape and explicitly expand K/V heads; MSLK does not broadcast them automatically.
- Leave op=None for recommended dispatch; pass a (forward, backward) class tuple to pin a backend.
GroupAttention / Core fMHA
SupportNVIDIA · AMD · MTIA
TopicsfMHA · dispatch · BMK · BMHK · BMGHK
Sourcemslk/attention/fmha/__init__.py
memory_efficient_attention_forward#
mslk.attention.fmha
Forward-only attention path that does not retain manual-backward context.
PublicfunctionNVIDIAAMD
memory_efficient_attention_forward(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None) -> TensorValidates and normalizes the same inputs as the high-level API, selects a forward backend, and returns only the attention output.
Returns: Attention output tensor.
Notes & constraints
- Pass a forward operator class, not an operator pair, through op.
- Use this path when no gradients or LSE are needed.
GroupAttention / Core fMHA
SupportNVIDIA · AMD · MTIA
TopicsfMHA · dispatch · BMK · BMHK · BMGHK
Sourcemslk/attention/fmha/__init__.py
memory_efficient_attention_forward_requires_grad#
mslk.attention.fmha
Manual-backward forward pass returning output and log-sum-exp.
PublicfunctionNVIDIAAMD
memory_efficient_attention_forward_requires_grad(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None) -> tuple[Tensor, Tensor]Despite its name, this is the explicit non-autograd API. The returned LSE is the context consumed by memory_efficient_attention_backward.
Returns: (output, lse).
Notes & constraints
- Nonzero dropout is rejected by this manual API.
- The forward and backward operators must agree on variable-length LSE layout.
GroupAttention / Core fMHA
SupportNVIDIA · AMD · MTIA
TopicsfMHA · dispatch · BMK · BMHK · BMGHK
Sourcemslk/attention/fmha/__init__.py
memory_efficient_attention_backward#
mslk.attention.fmha
Explicit backward pass for an output/LSE pair.
PublicfunctionNVIDIAAMD
memory_efficient_attention_backward(grad, output, lse, query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None) -> tuple[Tensor, Tensor, Tensor]Consumes the original Q/K/V, forward output, LSE, and upstream gradient. Dispatches a compatible backward kernel unless one is supplied.
Returns: (dq, dk, dv) reshaped to the original inputs.
Notes & constraints
- Dropout is not supported on the manual forward/backward API.
- This return contract does not include a dense tensor-bias gradient.
GroupAttention / Core fMHA
SupportNVIDIA · AMD · MTIA
TopicsfMHA · dispatch · BMK · BMHK · BMGHK
Sourcemslk/attention/fmha/__init__.py
memory_efficient_attention_partial#
mslk.attention.fmha
Computes an output and LSE for one disjoint K/V shard.
PublicfunctionNVIDIAAMD
memory_efficient_attention_partial(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None, _allow_backward=False) -> tuple[Tensor, Tensor]Call it repeatedly with the same query and separate key/value chunks, then combine the results with merge_attentions. This enables exact split-KV attention.
Returns: (partial_output, partial_lse).
Notes & constraints
- Dropout is unsupported.
- The public path is forward-only. _allow_backward is private and deliberately restricted.
- Use the merge_training wrappers for safe training.
GroupAttention / Core fMHA
SupportNVIDIA · AMD · MTIA
TopicsfMHA · dispatch · BMK · BMHK · BMGHK
Sourcemslk/attention/fmha/__init__.py
merge_attentions#
mslk.attention.fmha
Log-sum-exp-correct merge of attention computed over K/V chunks.
PublicfunctionNVIDIAAMD
merge_attentions(attn_split, lse_split, write_lse=True, output_dtype=None) -> tuple[Tensor, Optional[Tensor]]Accepts sequences of chunk tensors or tensors stacked along a leading chunk axis. It computes the exact normalized output over the union of chunks rather than averaging partial outputs.
Returns: (merged_output, merged_lse) when write_lse=True; otherwise (merged_output, None).
Notes & constraints
- Direct autograd through this function is unsupported; use merge_attentions_autograd.
- Inputs requiring gradients require write_lse=True.
GroupAttention / Core fMHA
SupportNVIDIA · AMD · MTIA
TopicsfMHA · dispatch · BMK · BMHK · BMGHK
Sourcemslk/attention/fmha/__init__.py
torch.ops.mslk.memory_efficient_attention_forward#
torch.ops.mslk
Compile-friendly forward attention with optional bias.
Low-leveltorch opNVIDIAMeta / fake
torch.ops.mslk.memory_efficient_attention_forward(q, k, v, b=None, p=0.0, scale=None) -> TensorThese custom-library wrappers keep dispatch outside a torch.compile trace and expose a reduced forward-only contract.
Returns: Attention output tensor matching q.
Notes & constraints
- No explicit op or output_dtype argument.
- K and V head dimensions must match.
- Only selected bias forms are trace-safe.
GroupAttention / Compile-friendly wrappers
SupportNVIDIA · Meta / fake
Topicstorch.compile · custom op · forward
Sourcemslk/attention/fmha/__init__.py
torch.ops.mslk.memory_efficient_attention_forward_with_bias#
torch.ops.mslk
Compile-friendly forward attention requiring an explicit bias tensor.
Low-leveltorch opNVIDIAMeta / fake
torch.ops.mslk.memory_efficient_attention_forward_with_bias(q, k, v, b, p=0.0, scale=None) -> TensorThese custom-library wrappers keep dispatch outside a torch.compile trace and expose a reduced forward-only contract.
Returns: Attention output tensor matching q.
Notes & constraints
- No explicit op or output_dtype argument.
- K and V head dimensions must match.
- Only selected bias forms are trace-safe.
GroupAttention / Compile-friendly wrappers
SupportNVIDIA · Meta / fake
Topicstorch.compile · custom op · forward
Sourcemslk/attention/fmha/__init__.py
Partial#
mslk.attention.fmha.merge_training
Autograd carrier for a partial attention output and its merge context.
PublicclassNVIDIAAMD
Partial(attn: Tensor, lse: Tensor, placeholder: Tensor)Users normally receive Partial from memory_efficient_attention_partial_autograd rather than constructing it directly.
Returns: A lightweight object consumed by merge_attentions_autograd.
Methods / constructors
is_bmghk() -> boolReports whether the stored output uses the grouped-head BMGHK layout.
apply(fn: Callable[[Tensor], Tensor]) -> PartialApplies a layout-preserving transform that must not manipulate the embedding dimension.
GroupAttention / Trainable partial attention
SupportNVIDIA · AMD
Topicsautograd · split KV · LSE
Sourcemslk/attention/fmha/merge_training.py
memory_efficient_attention_partial_autograd#
mslk.attention.fmha.merge_training
Autograd-safe wrapper around partial attention.
PublicfunctionNVIDIAAMD
memory_efficient_attention_partial_autograd(query, key, value, attn_bias=None, p=0.0, scale=None, *, op=None, output_dtype=None) -> PartialRecords Q/K/V and uses hidden placeholder gradients to route the merged output and full LSE into each shard’s backward pass.
Returns: Partial.
Notes & constraints
- Arguments mirror memory_efficient_attention_partial.
- Dropout remains unsupported by the underlying partial path.
GroupAttention / Trainable partial attention
SupportNVIDIA · AMD
Topicsautograd · split KV · LSE
Sourcemslk/attention/fmha/merge_training.py
merge_attentions_autograd#
mslk.attention.fmha.merge_training
Merges one or more Partial objects with correct gradients.
PublicfunctionNVIDIAAMD
merge_attentions_autograd(*partials: Partial) -> TensorFor multiple shards it performs the exact LSE merge. Passing a single Partial returns its output while retaining the autograd plumbing.
Returns: Merged attention output.
Notes & constraints
- Raises ValueError when called without partials.
GroupAttention / Trainable partial attention
SupportNVIDIA · AMD
Topicsautograd · split KV · LSE
Sourcemslk/attention/fmha/merge_training.py
AttentionBias#
mslk.attention.fmha.attn_bias
Abstract base for optimized attention-bias descriptions.
PublicclassNVIDIAAMD
AttentionBias()AttentionBias objects describe sparsity or additive bias without materializing the full Q×K matrix, allowing compatible kernels to encode the mask directly.
Returns: An object accepted as attn_bias by fMHA.
Methods / constructors
materialize(shape, dtype=torch.float32, device='cpu') -> TensorBuilds the dense bias for debugging/reference checks; intentionally slow.
to(device)Moves stored sequence metadata or tensor bias to a device.
Notes & constraints
- Subclasses define materialize and, where state is stored, to(device).
GroupAttention / Biases & masks
SupportNVIDIA · AMD · MTIA · CPU / Python
Topicsattention bias · mask
Sourcemslk/attention/fmha/attn_bias.py
LowerTriangularMask#
mslk.attention.fmha.attn_bias
Top-left-aligned causal mask.
PublicclassNVIDIAAMD
LowerTriangularMask(device: Optional[torch.device] = None)AttentionBias objects describe sparsity or additive bias without materializing the full Q×K matrix, allowing compatible kernels to encode the mask directly.
Returns: An object accepted as attn_bias by fMHA.
Methods / constructors
add_bias(bias: Tensor) -> LowerTriangularMaskWithTensorBiasCombines causal masking with an arbitrary additive tensor.
materialize(shape, dtype=torch.float32, device='cpu') -> TensorProduces zeros on/below the diagonal and −∞ above it.
Notes & constraints
- The device constructor argument is retained only for compatibility and is ignored.
GroupAttention / Biases & masks
SupportNVIDIA · AMD · MTIA · CPU / Python
Topicsattention bias · mask
Sourcemslk/attention/fmha/attn_bias.py
LowerTriangularMaskWithTensorBias#
mslk.attention.fmha.attn_bias
Top-left causal mask plus a dense additive tensor bias.
PublicclassNVIDIAAMD
LowerTriangularMaskWithTensorBias(bias: Tensor)AttentionBias objects describe sparsity or additive bias without materializing the full Q×K matrix, allowing compatible kernels to encode the mask directly.
Returns: An object accepted as attn_bias by fMHA.
Methods / constructors
materialize(shape, dtype=torch.float32, device='cpu') -> TensorBuilds the dense bias for debugging/reference checks; intentionally slow.
to(device)Moves stored sequence metadata or tensor bias to a device.
Notes & constraints
- Backend support is narrower than for a pure causal mask.
GroupAttention / Biases & masks
SupportNVIDIA · AMD · MTIA · CPU / Python
Topicsattention bias · mask
Sourcemslk/attention/fmha/attn_bias.py
LowerTriangularFromBottomRightMask#
mslk.attention.fmha.attn_bias
Bottom-right-aligned causal mask for Mq ≠ Mkv.
PublicclassNVIDIAAMD
LowerTriangularFromBottomRightMask()AttentionBias objects describe sparsity or additive bias without materializing the full Q×K matrix, allowing compatible kernels to encode the mask directly.
Returns: An object accepted as attn_bias by fMHA.
Methods / constructors
make_local_attention(window_size: int) -> LowerTriangularFromBottomRightLocalAttentionMaskRestricts the causal region to a trailing window.
GroupAttention / Biases & masks
SupportNVIDIA · AMD · MTIA · CPU / Python
Topicsattention bias · mask
Sourcemslk/attention/fmha/attn_bias.py
LowerTriangularFromBottomRightLocalAttentionMask#
mslk.attention.fmha.attn_bias
Bottom-right causal sliding-window mask.
PublicclassNVIDIAAMD
LowerTriangularFromBottomRightLocalAttentionMask(_window_size: int)AttentionBias objects describe sparsity or additive bias without materializing the full Q×K matrix, allowing compatible kernels to encode the mask directly.
Returns: An object accepted as attn_bias by fMHA.
Methods / constructors
materialize(shape, dtype=torch.float32, device='cpu') -> TensorBuilds the dense bias for debugging/reference checks; intentionally slow.
to(device)Moves stored sequence metadata or tensor bias to a device.
GroupAttention / Biases & masks
SupportNVIDIA · AMD
関連記事
今日のまとめ
AIデイリーブリーフで今日の重要ニュースをまとめ読み