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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions benchmark/linear_attention/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ RUN pip install -v /workspace/cudnn-frontend
# Install the Cutlass DSL runtime (cuDNN FROST engines).
RUN pip install nvidia-cutlass-dsl[cu13]==4.7.0 apache-tvm-ffi

# Install the cuTile runtime (cuDNN cuTile engines).
RUN pip install cuda-tile==1.5.0

RUN git clone https://github.com/fla-org/flash-linear-attention.git
RUN pip install -v /workspace/flash-linear-attention

Expand Down
2 changes: 1 addition & 1 deletion benchmark/linear_attention/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ The `kda` and `gdn2` variants fuse q/k L2 normalization in-kernel on every backe
| `flash_qla` | FlashQLA (TileLang fused GDN kernels, `gdn` variant only) |
| `flash_kda` | FlashKDA (`kda` forward variant only) |

The cuDNN backend routes through the pygraph engines: FROST (Cutlass DSL) on SM100-class devices, the cuTile engines elsewhere.
The cuDNN backend routes through the pygraph engines: FROST (Cutlass DSL) on SM100-SM103 and SM107, the cuTile engines elsewhere. `gdn2` is FROST-only.

## Results

Expand Down
117 changes: 81 additions & 36 deletions benchmark/linear_attention/benchmark_single_linear_attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,18 @@ def parse_args():
choices=["bfloat16", "float16"],
help="Data type. Can be bfloat16 or float16",
)
parser.add_argument(
"--gate_data_type",
default="auto",
choices=["auto", "float32", "bfloat16", "float16"],
help="Gate storage dtype. 'auto' picks the width the selected backend consumes natively; an explicit value overrides it on every backend",
)
parser.add_argument(
"--state_data_type",
default="auto",
choices=["auto", "float32", "bfloat16"],
help="Recurrent-state dtype for --initial_state / --store_on. 'auto' picks the width the selected backend consumes natively",
)
parser.add_argument(
"--num_iterations",
default=20,
Expand Down Expand Up @@ -240,6 +252,8 @@ def run_benchmark(
head_dim_qk: Optional[int] = None,
head_dim_vo: Optional[int] = None,
data_type: str = "bfloat16",
gate_data_type: str = "auto",
state_data_type: str = "auto",
backend: str = "cudnn",
variant: str = "gdn",
profile_pass: str = "fwd",
Expand All @@ -266,6 +280,8 @@ def run_benchmark(
head_dim_qk: Head dimension for Q/K (optional, for asymmetric)
head_dim_vo: Head dimension for V/O (optional, for asymmetric)
data_type: Data type ("bfloat16", "float16")
gate_data_type: Gate storage dtype ("auto", "float32", "bfloat16", "float16")
state_data_type: Recurrent-state dtype ("auto", "float32", "bfloat16")
backend: Backend name ("cudnn", "fla", "flash_qla", "flash_kda")
variant: Linear attention variant ("gdn", "kda", "gdn2")
profile_pass: Which pass to profile ("fwd", "bwd", "both")
Expand Down Expand Up @@ -310,6 +326,10 @@ def run_benchmark(
str(num_kv_heads),
"--data_type",
data_type,
"--gate_data_type",
gate_data_type,
"--state_data_type",
state_data_type,
"--la_backend",
backend,
"--variant",
Expand Down Expand Up @@ -418,6 +438,33 @@ def run_benchmark(
target_dtype = torch.float16
else:
raise ValueError(f"Invalid data type: {args.data_type}")
if args.profile_pass is not None:
run_fwd = args.profile_pass in ("fwd", "both")
run_bwd = args.profile_pass in ("bwd", "both")
elif args.fwd_bwd:
run_fwd = True
run_bwd = True
else:
run_fwd = True
run_bwd = False
dtype_by_name = {"float32": torch.float32, "bfloat16": torch.bfloat16, "float16": torch.float16}
narrow_kda_gates = args.variant == "kda" and args.la_backend != "fla"
gate_dtype = target_dtype if narrow_kda_gates else torch.float32
beta_dtype = target_dtype if (narrow_kda_gates or args.variant == "gdn2") else torch.float32
state_dtype = torch.float32
if args.gate_data_type != "auto":
gate_dtype = dtype_by_name[args.gate_data_type]
if args.state_data_type != "auto":
state_dtype = dtype_by_name[args.state_data_type]
if args.la_backend == "flash_kda" and gate_dtype is not target_dtype:
raise ValueError(f"flash_kda takes g and beta at the io dtype ({args.data_type}) only")
if args.la_backend == "flash_qla" and gate_dtype is not torch.float32 and run_bwd:
raise ValueError("flash_qla's backward asserts an fp32 dg")
if args.la_backend == "fla" and (args.initial_state or args.store_on) and state_dtype is not torch.float32:
if args.variant != "gdn":
raise ValueError(f"fla's chunk_{args.variant} asserts an fp32 initial_state")
if run_bwd:
raise ValueError("fla's chunk_gated_delta_rule hands back an fp32 d_initial_state")

# Parse input arguments
num_iters = args.num_iterations
Expand All @@ -436,15 +483,6 @@ def run_benchmark(
raise ValueError("Both --head_dim_qk and --head_dim_vo must be provided together when using asymmetric head dims.")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
assert device.type == "cuda", "Requires CUDA device"
if args.profile_pass is not None:
run_fwd = args.profile_pass in ("fwd", "both")
run_bwd = args.profile_pass in ("bwd", "both")
elif args.fwd_bwd:
run_fwd = True
run_bwd = True
else:
run_fwd = True
run_bwd = False
# Grouped-value attention: the recurrent state lives at the value/gate
# heads; several q/k heads may share one state (num_kv_heads groups over
# num_q_heads).
Expand Down Expand Up @@ -773,18 +811,13 @@ def preprocess_qkv(query, key, value, backend):

def preprocess_gates(gate, beta, write_gate, backend):
if backend == "cudnn":
beta_t = beta.reshape(batch_size * seqlen, *beta.shape[2:])
if kda_raw_gates:
beta_t = beta_t.to(target_dtype)
return (
gate.reshape(batch_size * seqlen, *gate.shape[2:]),
beta_t,
beta.reshape(batch_size * seqlen, *beta.shape[2:]),
write_gate.reshape(batch_size * seqlen, *write_gate.shape[2:]) if write_gate is not None else None,
)
elif backend in ("fla", "flash_qla"):
elif backend in ("fla", "flash_qla", "flash_kda"):
return gate, beta, write_gate
elif backend == "flash_kda":
return gate.to(target_dtype).contiguous(), beta.to(target_dtype).contiguous(), None
else:
raise ValueError(f"Invalid backend: {backend}")

Expand Down Expand Up @@ -858,26 +891,30 @@ def dram_bytes(
mode="fwd",
):
assert mode in ["fwd", "bwd"]
io_bytes = 2
f32_bytes = 4
io_bytes = target_dtype.itemsize
g_bytes = gate_dtype.itemsize
b_bytes = beta_dtype.itemsize
tokens = batch_size * seqlen
q_bytes = tokens * num_q_heads * head_dim_qk * io_bytes
k_bytes = tokens * num_q_heads * head_dim_qk * io_bytes
v_bytes = tokens * num_kv_heads * head_dim_vo * io_bytes
o_bytes = tokens * num_o_heads * head_dim_vo * io_bytes
if args.variant == "gdn":
gate_bytes = tokens * num_o_heads * 2 * f32_bytes
gate_bytes = tokens * num_o_heads * (g_bytes + b_bytes)
elif args.variant == "kda":
gate_bytes = tokens * num_o_heads * (head_dim_qk + 1) * f32_bytes
gate_bytes = tokens * num_o_heads * (head_dim_qk * g_bytes + b_bytes)
else: # gdn2
gate_bytes = tokens * num_o_heads * (head_dim_qk * f32_bytes + (head_dim_qk + head_dim_vo) * io_bytes)
gate_bytes = tokens * num_o_heads * (head_dim_qk * g_bytes + (head_dim_qk + head_dim_vo) * b_bytes)
num_chunks = ceil_div(seqlen, _CHUNK_SIZE[args.variant])
h_bytes = batch_size * num_o_heads * num_chunks * head_dim_qk * head_dim_vo * io_bytes
qkv_bytes = q_bytes + k_bytes + v_bytes
state_elems = batch_size * num_o_heads * head_dim_qk * head_dim_vo
final_state_dtype = state_dtype if args.initial_state else torch.float32
state_bytes = state_elems * (int(args.initial_state) * state_dtype.itemsize + int(args.store_on) * final_state_dtype.itemsize)
if mode == "fwd":
return qkv_bytes + gate_bytes + o_bytes
return qkv_bytes + gate_bytes + o_bytes + state_bytes
Comment thread
jhjpark marked this conversation as resolved.
Resolved
recompute_bytes = k_bytes + v_bytes + gate_bytes + h_bytes
return recompute_bytes + 2 * (qkv_bytes + gate_bytes) + o_bytes + h_bytes
return recompute_bytes + 2 * (qkv_bytes + gate_bytes) + o_bytes + h_bytes + 2 * state_bytes

def tb_per_sec(
batch_size,
Expand Down Expand Up @@ -905,14 +942,15 @@ def tb_per_sec(

## Gate generators per variant. Decays are LOG-space (alpha = exp(g)),
## drawn from ranges the kernels' io-dtype arithmetic is conditioned for.
def generate_gates(io_dtype):
## The draws stay fp32 for the log/logit/sigmoid math and narrow on the way out.
def generate_gates():
if args.variant == "gdn":
# scalar decay [B, T, HO] fp32 + scalar write strength
# scalar decay [B, T, HO] + scalar write strength
gate = torch.empty(batch_size, seqlen, num_o_heads, device=device).uniform_(0.1, 1.0).log()
beta = torch.rand(batch_size, seqlen, num_o_heads, device=device)
write_gate = None
elif args.variant == "kda":
# per-key-channel decay [B, T, HO, K] fp32 + post-sigmoid scalar
# per-key-channel decay [B, T, HO, K] + post-sigmoid scalar
# beta; forward-only runs feed raw logits with the same effective
# distributions (the in-kernel activations invert them)
gate = torch.empty(batch_size, seqlen, num_o_heads, head_dim_qk, device=device).uniform_(0.5, 1.0).log()
Expand All @@ -925,9 +963,9 @@ def generate_gates(io_dtype):
else: # gdn2
# per-key decay/erase [B, T, HO, K] + per-value write gate [B, T, HO, V]
gate = torch.empty(batch_size, seqlen, num_o_heads, head_dim_qk, device=device).uniform_(0.5, 1.0).log()
beta = (torch.rand(batch_size, seqlen, num_o_heads, head_dim_qk, device=device).sigmoid() * 2.0).to(io_dtype)
write_gate = torch.rand(batch_size, seqlen, num_o_heads, head_dim_vo, device=device).sigmoid().to(io_dtype)
return gate, beta, write_gate
beta = torch.rand(batch_size, seqlen, num_o_heads, head_dim_qk, device=device).sigmoid() * 2.0
write_gate = torch.rand(batch_size, seqlen, num_o_heads, head_dim_vo, device=device).sigmoid()
return gate.to(gate_dtype), beta.to(beta_dtype), write_gate.to(beta_dtype) if write_gate is not None else None

#### Done setting up linear attention function per backend ##
#############################################################
Expand All @@ -941,6 +979,7 @@ def generate_gates(io_dtype):
print(f"[INFO] {torch.cuda.device_count() = }")
print(f"[INFO] {torch.cuda.current_device() = }")
print(f"[INFO] {torch.cuda.get_device_name(torch.cuda.current_device()) = }")
print(f"[INFO] input dtypes: g={gate_dtype}, beta={beta_dtype}, state={state_dtype}")

forward_times = []
backward_times = []
Expand All @@ -964,7 +1003,7 @@ def generate_gates(io_dtype):
target_dtype
)
value = torch.randn(batch_size, seqlen, num_kv_heads, head_dim_vo, dtype=target_dtype, device=device)
gate, beta, write_gate = generate_gates(target_dtype)
gate, beta, write_gate = generate_gates()

query, key, value = preprocess_qkv(query, key, value, args.la_backend)
gate, beta, write_gate = preprocess_gates(gate, beta, write_gate, args.la_backend)
Expand All @@ -982,9 +1021,9 @@ def generate_gates(io_dtype):
# gradient feeds the backward pass).
state0 = None
if args.initial_state:
state0 = torch.randn(batch_size, num_o_heads, head_dim_qk, head_dim_vo, dtype=torch.float32, device=device) * 0.05
if args.la_backend == "flash_kda":
# FlashKDA state ports are V-major [B, H, V, K]
state0 = (torch.randn(batch_size, num_o_heads, head_dim_qk, head_dim_vo, dtype=torch.float32, device=device) * 0.05).to(state_dtype)
if args.la_backend in ("cudnn", "flash_kda"):
# cuDNN and FlashKDA state ports are V-major [N, HO, V, K]; fla and flash_qla K-major
state0 = state0.transpose(-1, -2).contiguous()
if run_bwd:
state0.requires_grad_(True)
Expand All @@ -994,7 +1033,11 @@ def generate_gates(io_dtype):
dOutput = torch.randn(batch_size, seqlen, num_o_heads, head_dim_vo, dtype=target_dtype, device=device)
dFinal = None
if args.store_on and run_bwd:
dFinal = torch.randn(batch_size, num_o_heads, head_dim_qk, head_dim_vo, dtype=torch.float32, device=device) * 0.05
# final_state is fp32 when no initial_state seeds it
dfinal_dtype = state_dtype if args.initial_state else torch.float32
dFinal = (torch.randn(batch_size, num_o_heads, head_dim_qk, head_dim_vo, dtype=torch.float32, device=device) * 0.05).to(dfinal_dtype)
if args.la_backend in ("cudnn", "flash_kda"):
dFinal = dFinal.transpose(-1, -2).contiguous()

l2_flush_buffer.zero_()

Expand Down Expand Up @@ -1093,8 +1136,10 @@ def generate_gates(io_dtype):
gate_ref = gate.detach()
beta_ref = beta.detach()
state0_ref = state0.detach() if state0 is not None else None
if state0_ref is not None and args.la_backend == "flash_kda":
state0_ref = state0_ref.transpose(-1, -2).contiguous()
if state0_ref is not None:
if args.la_backend in ("cudnn", "flash_kda"):
state0_ref = state0_ref.transpose(-1, -2).contiguous()
state0_ref = state0_ref.float()
wg_ref = None
if write_gate is not None:
wg_ref = write_gate.detach()
Expand Down
14 changes: 7 additions & 7 deletions docs/python_graph_and_execution_backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ are close.
adapter that builds and executes cached `gdn`/`gdn_bwd` graphs (the SDPA
op pattern), so it inherits whatever engine the planner selects. The
optional `use_qk_l2norm` attribute asks the engine to L2-normalize the q/k
rows; `GdnFrostEngine` (the SM100/SM103 default, serving both `gdn` and
rows; `GdnFrostEngine` (the SM100-SM103 and SM107 default, serving both `gdn` and
`gdn_bwd` on the FROST chunked kernels) serves it through a workspace
helper kernel (normalized q/k copies + saved inverse norms, with the
backward Jacobian projection applied in place after the head-group fold),
Expand All @@ -279,7 +279,7 @@ are close.
per-key-channel decay: its `g` is the log-space vector gate
`[total_T, HV, K]` (GDN's is the scalar `[total_T, HV]`); `beta` stays
scalar. The FROST engine (`cudnn.linear_attention.frost.kda_engine`) is
the forward default on SM100/SM103; the node's `use_qk_l2norm` attribute
the forward default on SM100-SM103 and SM107; the node's `use_qk_l2norm` attribute
(in-kernel L2-normalization of q/k — the KDA model's feature map) passes
through to the kernel (without the in-kernel norm the caller owns the q/k
conditioning). It serves `kda_bwd` on the FROST backward kernel,
Expand All @@ -291,16 +291,16 @@ are close.
- Gated DeltaNet v2 (`gdn2` / `gdn2_bwd`) has channel-wise gates — `g`/`beta`
`[total_T, HO, K]` plus a NEW per-value write gate `w` `[total_T, HO, V]`.
GDN-2 has **no** cuTile engine; `Gdn2FrostEngine`
(`cudnn.linear_attention.frost.gdn2_engine`, SM100/SM103) is its only
(`cudnn.linear_attention.frost.gdn2_engine`, SM100-SM103 and SM107) is its only
engine, passes the `use_qk_l2norm` attribute through to the kernel (like
`KdaFrostEngine`), and serves `gdn2_bwd` the same way (checkpoint
recompute when the series is absent); the op is
`cudnn.linear_attention.ops.gated_delta_net_v2`.
- The FROST engines are pure pass-through: `check_support` requires the
kernel-native dtypes (fp32 gates — io-dtype `beta`/`w` for GDN-2 — int32
or int64 `cu_seqlens`, fp32-or-bf16 state ports with matching
initial/final dtypes, fp32 state gradients for GDN/KDA and io-dtype
`dBeta`/`dW` for GDN-2) and execute hands the caller's buffers straight to
kernel-native dtypes (fp32/bf16/fp16 gates — io-dtype `beta`/`w` for GDN-2
— int32 or int64 `cu_seqlens`, fp32-or-bf16 state ports with matching
initial/final dtypes, state gradients at the state's own dtype, and
io-dtype `dBeta`/`dW` for GDN-2) and execute hands the caller's buffers straight to
the kernels, carving any scratch it needs out of the explicit workspace as
DLPack views. The cuTile engines follow the same buffer contract: outputs
are written in place (the caller's output buffers, required in the
Expand Down
6 changes: 6 additions & 0 deletions python/cudnn/_pygraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -2391,8 +2391,11 @@ def builder(self, *args, name: str = "", compute_data_type: Any = None, **kwargs
# attrs scalar/enum/list params stored in node.params verbatim
# and forwarded as keywords at lowering
# outputs output ports, in C++ return order
# maybe per-output presence predicate over the node (an output
# whose predicate is False is skipped, and comes back None)
# infer per-output IR-side shape inference (introspection; cuDNN
# re-infers at build) — best-effort, None on failure
# dtype_like per-output data_type copied from a named input port
# push_output_dims True for ops whose output dims cuDNN cannot infer
# (dgrad/wgrad/reduction/reshape/...): IR dims are pushed
# no_cdt True for bindings without a compute_data_type kwarg
Expand Down Expand Up @@ -2671,6 +2674,7 @@ def _training_phase(node): # norm stats exist only in TRAINING forward phase
"d_a_log": _like("a_log"),
"d_dt_bias": _like("dt_bias"),
},
dtype_like={"d_initial_state": "initial_state"},
python_only=True,
),
"kda": dict(
Expand Down Expand Up @@ -2714,6 +2718,7 @@ def _training_phase(node): # norm stats exist only in TRAINING forward phase
"d_a_log": _like("a_log"),
"d_dt_bias": _like("dt_bias"),
},
dtype_like={"d_initial_state": "initial_state"},
python_only=True,
),
"gdn2": dict(
Expand Down Expand Up @@ -2759,6 +2764,7 @@ def _training_phase(node): # norm stats exist only in TRAINING forward phase
"d_a_log": _like("a_log"),
"d_dt_bias": _like("dt_bias"),
},
dtype_like={"d_initial_state": "initial_state"},
python_only=True,
),
# ---- convolution ---------------------------------------------------------
Expand Down
9 changes: 4 additions & 5 deletions python/cudnn/fla/gated_delta_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,9 @@ def _to_native(
if a_log_t.shape[0] != HO or dt_bias_t.shape[0] != HO:
raise _Decline("a_log/dt_bias head count does not match HO=max(H,HV)")

# g is always fp32 (raw logits under safe_gate, else FLA's precomputed log decay).
# beta is io-dtype logits when the kernel applies the sigmoid, else fp32 post-activation.
g = g.float()
beta = beta.to(q.dtype) if use_beta_sigmoid_in_kernel else beta.float()
# beta is io-dtype logits when the kernel applies the sigmoid; post-activation beta rides as given.
if use_beta_sigmoid_in_kernel:
beta = beta.to(q.dtype)

def thd(t):
# FLA's fused QKV short-conv returns one compact [B,T,Q+K+V]
Expand All @@ -104,7 +103,7 @@ def thd(t):
if g2.shape[-1] != HO or beta2.shape[-1] != HO:
raise _Decline("g/beta head count does not match HO=max(H,HV)")

h0 = None if initial_state is None else initial_state.float().contiguous()
h0 = None if initial_state is None else initial_state.contiguous()
o, fs = gated_delta_net(
thd(q),
thd(k),
Expand Down
Loading
Loading