diff --git a/benchmark/linear_attention/Dockerfile b/benchmark/linear_attention/Dockerfile index 2b56c22b5b..e7b02385f4 100644 --- a/benchmark/linear_attention/Dockerfile +++ b/benchmark/linear_attention/Dockerfile @@ -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 diff --git a/benchmark/linear_attention/README.md b/benchmark/linear_attention/README.md index a37977a93c..79ff23cfd9 100644 --- a/benchmark/linear_attention/README.md +++ b/benchmark/linear_attention/README.md @@ -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 diff --git a/benchmark/linear_attention/benchmark_single_linear_attention.py b/benchmark/linear_attention/benchmark_single_linear_attention.py index 09b4ea9e9b..f69e3bf194 100644 --- a/benchmark/linear_attention/benchmark_single_linear_attention.py +++ b/benchmark/linear_attention/benchmark_single_linear_attention.py @@ -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, @@ -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", @@ -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") @@ -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", @@ -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 @@ -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). @@ -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}") @@ -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 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, @@ -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() @@ -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 ## ############################################################# @@ -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 = [] @@ -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) @@ -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) @@ -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_() @@ -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() diff --git a/docs/python_graph_and_execution_backends.md b/docs/python_graph_and_execution_backends.md index a50d14c8fc..c8e0857629 100644 --- a/docs/python_graph_and_execution_backends.md +++ b/docs/python_graph_and_execution_backends.md @@ -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), @@ -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, @@ -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 diff --git a/python/cudnn/_pygraph.py b/python/cudnn/_pygraph.py index 027e70103d..102946dad1 100644 --- a/python/cudnn/_pygraph.py +++ b/python/cudnn/_pygraph.py @@ -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 @@ -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( @@ -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( @@ -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 --------------------------------------------------------- diff --git a/python/cudnn/fla/gated_delta_rule.py b/python/cudnn/fla/gated_delta_rule.py index 4591ce8d33..f43aee1cd3 100644 --- a/python/cudnn/fla/gated_delta_rule.py +++ b/python/cudnn/fla/gated_delta_rule.py @@ -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] @@ -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), diff --git a/python/cudnn/fla/kda.py b/python/cudnn/fla/kda.py index 398310ee74..315d296a4f 100644 --- a/python/cudnn/fla/kda.py +++ b/python/cudnn/fla/kda.py @@ -73,7 +73,6 @@ def _to_native( # A_log/dt_bias describe the gate over the H key/query heads (matching g's [B,T,H,K]), # not the value heads; a mismatched element count means we cannot adapt -> decline. - g = g.float() native_safe_gate = False a_log_t = dt_bias_t = gate_lb = None if safe_gate: @@ -98,13 +97,14 @@ def _to_native( b = dt_bias.float().reshape(H, K) g = -a.exp() * F.softplus(g + b) - # beta is io-dtype logits when the kernel applies the sigmoid, else fp32 post-activation. - 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): return t.reshape(-1, *t.shape[2:]) - 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 = kimi_delta_attention( thd(q), thd(k), diff --git a/python/cudnn/frost/tile_dsl/tma.py b/python/cudnn/frost/tile_dsl/tma.py index cfed4e23d8..a044f605ae 100644 --- a/python/cudnn/frost/tile_dsl/tma.py +++ b/python/cudnn/frost/tile_dsl/tma.py @@ -276,3 +276,59 @@ def tma_tensormap_acquire(desc_ptr): from_proxy=nvvm.Proxy.GENERIC, to_proxy=nvvm.Proxy.TENSORMAP, ) + + +def ptx_type_suffix(dtype) -> str: + """PTX type suffix for a 32-bit global ld/st: ``f32`` for floats, ``b32`` for bit patterns.""" + return "f32" if dtype == cutlass.Float32 else "b32" + + +def ld_global(addr, dtype): + """32-bit global load: one register of ``dtype`` from ``addr``.""" + return nvvm.inline_ptx( + f"ld.global.{ptx_type_suffix(dtype)} $0, [$1];", + write_only_types=[dtype], + read_only_args=[addr], + ) + + +def ld_global_v2(addr, dtype): + """64-bit global load: two 32-bit registers of ``dtype`` from ``addr``.""" + return nvvm.inline_ptx( + f"ld.global.v2.{ptx_type_suffix(dtype)} {{$0, $1}}, [$2];", + write_only_types=[dtype] * 2, + read_only_args=[addr], + ) + + +def ld_global_v4(addr, dtype): + """128-bit global load: four 32-bit registers of ``dtype`` from ``addr``.""" + return nvvm.inline_ptx( + f"ld.global.v4.{ptx_type_suffix(dtype)} {{$0, $1, $2, $3}}, [$4];", + write_only_types=[dtype] * 4, + read_only_args=[addr], + ) + + +def st_global(addr, value, dtype): + """32-bit global store: one register of ``dtype`` to ``addr``.""" + nvvm.inline_ptx( + f"st.global.{ptx_type_suffix(dtype)} [$0], $1;", + read_only_args=[addr, value], + ) + + +def st_global_v2(addr, values, dtype): + """64-bit global store: two 32-bit registers of ``dtype`` to ``addr``.""" + nvvm.inline_ptx( + f"st.global.v2.{ptx_type_suffix(dtype)} [$0], {{$1, $2}};", + read_only_args=[addr, values[0], values[1]], + ) + + +def st_global_v4(addr, values, dtype): + """128-bit global store: four 32-bit registers of ``dtype`` to ``addr``.""" + nvvm.inline_ptx( + f"st.global.v4.{ptx_type_suffix(dtype)} [$0], {{$1, $2, $3, $4}};", + read_only_args=[addr, values[0], values[1], values[2], values[3]], + ) diff --git a/python/cudnn/linear_attention/cutile/kernels/gdn.py b/python/cudnn/linear_attention/cutile/kernels/gdn.py index 8460024e71..5f2163d511 100644 --- a/python/cudnn/linear_attention/cutile/kernels/gdn.py +++ b/python/cudnn/linear_attention/cutile/kernels/gdn.py @@ -651,9 +651,7 @@ def recompute_w_u_fwd_kernel( beta_seg = beta.slice(axis=0, start=bos, stop=eos) Z = ct.PaddingMode.ZERO - # Keep Beta native bf16: scaling in bf16 avoids 2 extra ftof - # converts/MMA-input that an f32 cast would force. - b_b = ct.load(beta_seg, index=(i_t_loc, i_h), shape=(BT, 1), padding_mode=Z).reshape((BT,)) + b_b = ct.astype(ct.load(beta_seg, index=(i_t_loc, i_h), shape=(BT, 1), padding_mode=Z).reshape((BT,)), ct.float32) b_A = ct.load(A_seg, index=(i_t_loc, i_h, 0), shape=(BT, 1, BT), padding_mode=Z).reshape((BT, BT)) # U = A @ (V * Beta). latency=3 -> deeper pipeline of the per-tile TMA loads. diff --git a/python/cudnn/linear_attention/frost/common/gate_bwd.py b/python/cudnn/linear_attention/frost/common/gate_bwd.py index 1c23dcb71b..3b82784bd0 100644 --- a/python/cudnn/linear_attention/frost/common/gate_bwd.py +++ b/python/cudnn/linear_attention/frost/common/gate_bwd.py @@ -16,10 +16,6 @@ stable run to run. Two stages with a launch boundary as the grid barrier: a partial pass over token stripes (the same pass rewrites dGate -> dg_raw), then a finisher that folds the stripe partials. - -Scalar stripes scale with the token axis (:func:`scalar_gate_blocks`, capped) -so the partial pass fills the machine; channel stripes stay at -``GATE_BWD_BLOCKS`` (the partials carve is ``128 * HO * 128`` fp32). """ import functools @@ -28,11 +24,16 @@ import cutlass import cutlass.cute as cute import cutlass.experimental.primitives as nvvm -from cutlass.cute.arch.nvvm_wrappers import inline_ptx from cutlass.cute.runtime import from_dlpack from cudnn.frost.buffers import data_ptr from cudnn.frost.tile_dsl.pointwise import fadd2, ffma2, fmul2, lane_group_sum, sigmoid, sigmoid2, softplus +from cudnn.frost.tile_dsl.barrier import launch_dependent_grids, wait_on_dependent_grids +from cudnn.frost.tile_dsl.tma import ld_global_v2, ld_global_v4, st_global_v2, st_global_v4 + +from .host import get_dtype + +USE_PDL = True GATE_BWD_BLOCKS = 128 # channel-gate token stripes (partials carve = 128 * HO * 128 fp32) SCALAR_BLOCK_CAP = 8192 # scalar-gate stripe ceiling @@ -42,8 +43,7 @@ def scalar_gate_blocks(n_tokens: int) -> int: """Scalar-gate stripe count: shape-only (so the summation bracketing is - deterministic) and scaling with the token axis so the partial pass runs - memory-bound instead of 128 * HO threads walking long serial slices.""" + deterministic) and scaling with the token axis.""" return min(SCALAR_BLOCK_CAP, max(1, -(-n_tokens // SCALAR_SLICE_TOKENS))) @@ -62,33 +62,34 @@ def frost_scalar_gate_bwd_partial( """Grid (stripes, head tiles), block (SCALAR_HEAD_TILE,): thread h walks stripe g's token slice in order, rewriting dGate -> dg_raw in place and accumulating the (g, h) partials for dA_log (dGate * g_transformed) and - ddt_bias (dg_raw). Tiling heads over grid.y rather than one thread per - head takes any HO and keeps a small HO down to a single warp; each - (stripe, head) still has exactly one owner, so the partial layout and the - finisher's summation order are unchanged.""" + ddt_bias (dg_raw).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() bid = cute.arch.block_idx() tidx = cutlass.Int32(cute.arch.thread_idx()[0]) - g_blk = cutlass.Int32(bid[0]) + stripe_idx = cutlass.Int32(bid[0]) h = cutlass.Int32(bid[1]) * cutlass.Int32(SCALAR_HEAD_TILE) + tidx if h < h_o: neg_exp_a = -cute.math.exp(mALog[h], fastmath=True) bias = mDtBias[h] - t = g_blk * slice_len + t = stripe_idx * slice_len t_end = t + slice_len if t_end > n_tokens: t_end = n_tokens acc_a = cutlass.Float32(0.0) acc_dt = cutlass.Float32(0.0) while t < t_end: - d_gate = mDg[t, h] - y = mG[t, h] + bias + d_gate = mDg[t, h].to(cutlass.Float32) + y = mG[t, h].to(cutlass.Float32) + bias dg_raw = d_gate * neg_exp_a * sigmoid(y) acc_a += d_gate * (neg_exp_a * softplus(y)) acc_dt += dg_raw - mDg[t, h] = dg_raw + mDg[t, h] = dg_raw.to(mDg.element_type) t += 1 - mPartA[g_blk * h_o + h] = acc_a - mPartDt[g_blk * h_o + h] = acc_dt + mPartA[stripe_idx * h_o + h] = acc_a + mPartDt[stripe_idx * h_o + h] = acc_dt + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.kernel @@ -101,10 +102,11 @@ def frost_scalar_gate_bwd_finish( n_blocks: cutlass.Int32, ) -> None: """Grid (HO,), block (32,): head h's stripe partials fold as 8 fixed - interleaved chains per lane (independent accumulators so the loads - pipeline instead of serializing at memory latency), then the 8 chains + interleaved chains per lane (independent accumulators), then the 8 chains pairwise and one butterfly tree across the 32 lanes — a fixed-shape bracketing regardless of the stripe count.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() bid = cute.arch.block_idx() lane_idx = cutlass.Int32(cute.arch.thread_idx()[0]) h = cutlass.Int32(bid[0]) @@ -123,7 +125,6 @@ def frost_scalar_gate_bwd_finish( idx = s * h_o + h a8[0], d8[0] = fadd2(a8[0], d8[0], mPartA[idx], mPartDt[idx]) s += cutlass.Int32(32) - # the A and dt chains are independent, so each packed add folds both p0a, p0d = fadd2(a8[0], d8[0], a8[1], d8[1]) p1a, p1d = fadd2(a8[2], d8[2], a8[3], d8[3]) p2a, p2d = fadd2(a8[4], d8[4], a8[5], d8[5]) @@ -136,6 +137,8 @@ def frost_scalar_gate_bwd_finish( if lane_idx == 0: mDA[h] = acc_a mDDt[h] = acc_dt + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.kernel @@ -159,11 +162,13 @@ def frost_channel_gate_bwd_partial( w_ * z, the ddt_bias one dg_raw. The four warp partials per channel fold w = 0..3 through SMEM (fixed order) into the (g, h) partial slots. a_log is one scalar per head; dt_bias is per (head, channel).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() bid = cute.arch.block_idx() tidx = cutlass.Int32(cute.arch.thread_idx()[0]) - g_blk = cutlass.Int32(bid[0]) + stripe_idx = cutlass.Int32(bid[0]) h = cutlass.Int32(bid[1]) - wrp = tidx // cutlass.Int32(32) + warp_id = tidx // cutlass.Int32(32) lane_idx = tidx % cutlass.Int32(32) d0 = lane_idx * cutlass.Int32(4) exp_a = cute.math.exp(mALog[h], fastmath=True) @@ -178,29 +183,28 @@ def frost_channel_gate_bwd_partial( acc_dt[q] = cutlass.Float32(0.0) dg_base = mDg.iterator.toint() g_base = mG.iterator.toint() + gate_elem_bytes = cutlass.const_expr(mG.element_type.width // 8) dg_s0 = cutlass.Int64(mDg.stride[0]) dg_s1 = cutlass.Int64(mDg.stride[1]) g_s0 = cutlass.Int64(mG.stride[0]) g_s1 = cutlass.Int64(mG.stride[1]) - t = g_blk * slice_len + wrp - t_end = g_blk * slice_len + slice_len + t = stripe_idx * slice_len + warp_id + t_end = stripe_idx * slice_len + slice_len if t_end > n_tokens: t_end = n_tokens while t < t_end: - dg_addr = dg_base + (cutlass.Int64(t) * dg_s0 + cutlass.Int64(h) * dg_s1 + cutlass.Int64(d0)) * cutlass.Int64(4) - g_addr = g_base + (cutlass.Int64(t) * g_s0 + cutlass.Int64(h) * g_s1 + cutlass.Int64(d0)) * cutlass.Int64(4) - dg0, dg1, dg2, dg3 = inline_ptx( - "ld.global.v4.f32 {$0, $1, $2, $3}, [$4];", - write_only_types=[cutlass.Float32, cutlass.Float32, cutlass.Float32, cutlass.Float32], - read_only_args=[dg_addr], - ) - gv0, gv1, gv2, gv3 = inline_ptx( - "ld.global.v4.f32 {$0, $1, $2, $3}, [$4];", - write_only_types=[cutlass.Float32, cutlass.Float32, cutlass.Float32, cutlass.Float32], - read_only_args=[g_addr], - ) - dgv = (dg0, dg1, dg2, dg3) - gvv = (gv0, gv1, gv2, gv3) + dg_addr = dg_base + (cutlass.Int64(t) * dg_s0 + cutlass.Int64(h) * dg_s1 + cutlass.Int64(d0)) * cutlass.Int64(gate_elem_bytes) + g_addr = g_base + (cutlass.Int64(t) * g_s0 + cutlass.Int64(h) * g_s1 + cutlass.Int64(d0)) * cutlass.Int64(gate_elem_bytes) + if cutlass.const_expr(mG.element_type == cutlass.Float32): + dgv = ld_global_v4(dg_addr, cutlass.Float32) + gvv = ld_global_v4(g_addr, cutlass.Float32) + else: + dw0, dw1 = ld_global_v2(dg_addr, cutlass.Int32) + gw0, gw1 = ld_global_v2(g_addr, cutlass.Int32) + dfrag = cutlass.Vector.from_elements((dw0, dw1), cutlass.Int32).bitcast(mG.element_type).to(cutlass.Float32) + gfrag = cutlass.Vector.from_elements((gw0, gw1), cutlass.Int32).bitcast(mG.element_type).to(cutlass.Float32) + dgv = (dfrag[0], dfrag[1], dfrag[2], dfrag[3]) + gvv = (gfrag[0], gfrag[1], gfrag[2], gfrag[3]) for p in cutlass.range_constexpr(2): i = 2 * p j = i + 1 @@ -217,25 +221,28 @@ def frost_channel_gate_bwd_partial( acc_dt[i], acc_dt[j] = fadd2(acc_dt[i], acc_dt[j], raw_lo, raw_hi) out[i] = raw_lo out[j] = raw_hi - inline_ptx( - "st.global.v4.f32 [$0], {$1, $2, $3, $4};", - read_only_args=[dg_addr, out[0], out[1], out[2], out[3]], - ) + if cutlass.const_expr(mG.element_type == cutlass.Float32): + st_global_v4(dg_addr, out, cutlass.Float32) + else: + words = cutlass.Vector.from_elements((out[0], out[1], out[2], out[3]), cutlass.Float32).to(mG.element_type).bitcast(cutlass.Int32) + st_global_v2(dg_addr, words, cutlass.Int32) t += cutlass.Int32(4) sA = cutlass.Array(cutlass.Float32, 512, space=cutlass.AddressSpace.smem, alignment=16) sDt = cutlass.Array(cutlass.Float32, 512, space=cutlass.AddressSpace.smem, alignment=16) for q in cutlass.range_constexpr(4): - sA[wrp * cutlass.Int32(128) + d0 + cutlass.Int32(q)] = acc_a[q] - sDt[wrp * cutlass.Int32(128) + d0 + cutlass.Int32(q)] = acc_dt[q] + sA[warp_id * cutlass.Int32(128) + d0 + cutlass.Int32(q)] = acc_a[q] + sDt[warp_id * cutlass.Int32(128) + d0 + cutlass.Int32(q)] = acc_dt[q] nvvm.barrier_cta_sync() - if wrp == 0: + if warp_id == 0: for q in cutlass.range_constexpr(4): d = d0 + cutlass.Int32(q) fa = ((sA[d] + sA[cutlass.Int32(128) + d]) + sA[cutlass.Int32(256) + d]) + sA[cutlass.Int32(384) + d] fdt = ((sDt[d] + sDt[cutlass.Int32(128) + d]) + sDt[cutlass.Int32(256) + d]) + sDt[cutlass.Int32(384) + d] - base = (g_blk * h_o + h) * cutlass.Int32(128) + d + base = (stripe_idx * h_o + h) * cutlass.Int32(128) + d mPartA[base] = fa mPartDt[base] = fdt + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.kernel @@ -248,15 +255,17 @@ def frost_channel_gate_bwd_finish( ) -> None: """Grid (HO,), block (128,): thread d folds its channel column over the GATE_BWD_BLOCKS stripe partials as 8 fixed interleaved chains - (independent accumulators so the loads pipeline) folded pairwise. + (independent accumulators) folded pairwise. ddt_bias is per (head, channel), so thread d stores its column outright; dA_log is per head, so the channel axis folds through a fixed tree (warp butterflies, then the 4 warp sums in index order).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() bid = cute.arch.block_idx() tidx = cutlass.Int32(cute.arch.thread_idx()[0]) h = cutlass.Int32(bid[0]) d = tidx - wrp = tidx // cutlass.Int32(32) + warp_id = tidx // cutlass.Int32(32) lane_idx = tidx % cutlass.Int32(32) a8 = cutlass.Array(cutlass.Float32, 8) d8 = cutlass.Array(cutlass.Float32, 8) @@ -276,10 +285,12 @@ def frost_channel_gate_bwd_finish( sWa = cutlass.Array(cutlass.Float32, 4, space=cutlass.AddressSpace.smem, alignment=16) va = lane_group_sum(col_a, 32) if lane_idx == 0: - sWa[wrp] = va + sWa[warp_id] = va nvvm.barrier_cta_sync() if tidx == 0: mDA[h] = ((sWa[0] + sWa[1]) + sWa[2]) + sWa[3] + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -300,9 +311,9 @@ def scalar_gate_bwd_launch( stream: cuda.CUstream, ): frost_scalar_gate_bwd_partial(d_gate, g_raw, a_log, dt_bias, part_a, part_dt, n_tokens, h_o, slice_len).launch( - grid=(n_blocks, head_tiles, 1), block=(SCALAR_HEAD_TILE, 1, 1), stream=stream + grid=(n_blocks, head_tiles, 1), block=(SCALAR_HEAD_TILE, 1, 1), stream=stream, use_pdl=USE_PDL ) - frost_scalar_gate_bwd_finish(part_a, part_dt, d_a_log, d_dt_bias, h_o, n_blocks).launch(grid=(h_o, 1, 1), block=(32, 1, 1), stream=stream) + frost_scalar_gate_bwd_finish(part_a, part_dt, d_a_log, d_dt_bias, h_o, n_blocks).launch(grid=(h_o, 1, 1), block=(32, 1, 1), stream=stream, use_pdl=USE_PDL) @cute.jit @@ -322,9 +333,9 @@ def channel_gate_bwd_launch( stream: cuda.CUstream, ): frost_channel_gate_bwd_partial(d_gate, g_raw, a_log, dt_bias, part_a, part_dt, n_tokens, h_o, slice_len, lower_bound).launch( - grid=(GATE_BWD_BLOCKS, h_o, 1), block=(128, 1, 1), stream=stream + grid=(GATE_BWD_BLOCKS, h_o, 1), block=(128, 1, 1), stream=stream, use_pdl=USE_PDL ) - frost_channel_gate_bwd_finish(part_a, part_dt, d_a_log, d_dt_bias, h_o).launch(grid=(h_o, 1, 1), block=(128, 1, 1), stream=stream) + frost_channel_gate_bwd_finish(part_a, part_dt, d_a_log, d_dt_bias, h_o).launch(grid=(h_o, 1, 1), block=(128, 1, 1), stream=stream, use_pdl=USE_PDL) @functools.cache @@ -336,16 +347,18 @@ def scalar_gate_bwd(d_gate, g_raw, a_log, dt_bias, d_a_log, d_dt_bias, part_a, p """Scalar-gate backward: rewrite d_gate [total, HO] fp32 in place from transformed-space to raw-logit space and fill d_a_log/d_dt_bias (HO,). part_a/part_dt are (scalar_gate_blocks(total) * HO,) fp32 workspace carves.""" - n_tokens, h_o = (int(s_) for s_ in d_gate.shape) + n_tokens, h_o = (int(dim) for dim in d_gate.shape) n_blocks = scalar_gate_blocks(n_tokens) head_tiles = -(-h_o // SCALAR_HEAD_TILE) slice_len = (n_tokens + n_blocks - 1) // n_blocks for name, buf in (("part_a", part_a), ("part_dt", part_dt)): if int(buf.shape[0]) < n_blocks * h_o: raise ValueError(f"{name} must hold scalar_gate_blocks({n_tokens}) * {h_o} = {n_blocks * h_o} fp32; got {int(buf.shape[0])}") - cache = gate_bwd_cache(("gdn",)) + cache = gate_bwd_cache(("gdn", str(g_raw.dtype))) cu_stream = cuda.CUstream(int(stream)) tensors = (d_gate, g_raw, a_log, dt_bias, part_a, part_dt, d_a_log, d_dt_bias) + if str(d_gate.dtype) != str(g_raw.dtype): + raise ValueError(f"d_gate must carry the gate dtype: got {d_gate.dtype} with g_raw {g_raw.dtype}") if "compiled" not in cache: traced = [from_dlpack(t, assumed_align=4) for t in tensors[:2]] traced = [tr.mark_layout_dynamic(leading_dim=1) for tr in traced] @@ -365,29 +378,32 @@ def scalar_gate_bwd(d_gate, g_raw, a_log, dt_bias, d_a_log, d_dt_bias, part_a, p def channel_gate_bwd(d_gate, g_raw, a_log, dt_bias, d_a_log, d_dt_bias, part_a, part_dt, gate_lower_bound, *, stream): - """Per-channel-gate backward: rewrite d_gate [total, HO, 128] fp32 in + """Per-channel-gate backward: rewrite d_gate [total, HO, 128] (gate dtype) in place and fill d_a_log/d_dt_bias at their parameter shapes ((HO,) params get the channel axis folded in the finisher).""" - n_tokens, h_o, d_k = (int(s_) for s_ in d_gate.shape) + n_tokens, h_o, d_k = (int(dim) for dim in d_gate.shape) if d_k != 128: raise ValueError(f"per-channel gate backward requires 128 channels; got {d_k}") - for name, t in (("d_gate", d_gate), ("g_raw", g_raw)): - st = tuple(int(s_) for s_ in t.stride()) - if st[2] != 1 or st[0] % 4 != 0 or st[1] % 4 != 0 or data_ptr(t) % 16 != 0: - raise ValueError(f"{name} needs a 16B-aligned base, unit channel stride, and outer strides in multiples of 4; got {st}") + if str(d_gate.dtype) != str(g_raw.dtype): + raise ValueError(f"d_gate must carry the gate dtype: got {d_gate.dtype} with g_raw {g_raw.dtype}") + g_vector_bytes = 4 * (get_dtype(g_raw.dtype).width // 8) + for name, t, want_align in (("d_gate", d_gate, g_vector_bytes), ("g_raw", g_raw, g_vector_bytes)): + strides = tuple(int(stride) for stride in t.stride()) + if strides[2] != 1 or strides[0] % 4 != 0 or strides[1] % 4 != 0 or data_ptr(t) % want_align != 0: + raise ValueError(f"{name} needs a {want_align}B-aligned base, unit channel stride, and outer strides in multiples of 4; got {strides}") for name, t in (("a_log", a_log), ("d_a_log", d_a_log)): - if tuple(int(s_) for s_ in t.shape) != (h_o,) or tuple(int(s_) for s_ in t.stride()) != (1,): + if tuple(int(dim) for dim in t.shape) != (h_o,) or tuple(int(stride) for stride in t.stride()) != (1,): raise ValueError(f"{name} must be a contiguous ({h_o},) per-head fp32 parameter; got shape {tuple(t.shape)}") for name, t in (("dt_bias", dt_bias), ("d_dt_bias", d_dt_bias)): - if tuple(int(s_) for s_ in t.shape) != (h_o, d_k) or tuple(int(s_) for s_ in t.stride()) != (d_k, 1): + if tuple(int(dim) for dim in t.shape) != (h_o, d_k) or tuple(int(stride) for stride in t.stride()) != (d_k, 1): raise ValueError(f"{name} must be a contiguous ({h_o}, {d_k}) per-channel fp32 parameter; got shape {tuple(t.shape)}") slice_len = (n_tokens + GATE_BWD_BLOCKS - 1) // GATE_BWD_BLOCKS - cache = gate_bwd_cache(("channel",)) + cache = gate_bwd_cache(("channel", str(g_raw.dtype))) cu_stream = cuda.CUstream(int(stream)) tensors = (d_gate, g_raw, a_log, dt_bias, part_a, part_dt, d_a_log, d_dt_bias) args = (n_tokens, h_o, slice_len) if "compiled" not in cache: - traced = [from_dlpack(t, assumed_align=16).mark_layout_dynamic(leading_dim=2) for t in tensors[:2]] + traced = [from_dlpack(t, assumed_align=g_vector_bytes).mark_layout_dynamic(leading_dim=2) for t in (d_gate, g_raw)] traced += [from_dlpack(t, assumed_align=4).mark_layout_dynamic(leading_dim=len(t.shape) - 1) for t in tensors[2:]] cache["compiled"] = cute.compile( channel_gate_bwd_launch, diff --git a/python/cudnn/linear_attention/frost/common/head_reduce.py b/python/cudnn/linear_attention/frost/common/head_reduce.py index 7897b46162..d5731c2cb3 100644 --- a/python/cudnn/linear_attention/frost/common/head_reduce.py +++ b/python/cudnn/linear_attention/frost/common/head_reduce.py @@ -24,6 +24,9 @@ from .host import get_dtype from cudnn.frost.tile_dsl.pointwise import f16x2_to_f32, fp32_to_fp16 +from cudnn.frost.tile_dsl.barrier import launch_dependent_grids, wait_on_dependent_grids + +USE_PDL = True BLOCK = 256 @@ -40,6 +43,8 @@ def frost_head_reduce( inner_words: cutlass.Constexpr[int], io_dtype: cutlass.Constexpr, ) -> None: + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx()[0] gw = cutlass.Int64(cutlass.Int32(bidx)) * cutlass.Int64(BLOCK) + cutlass.Int64(cutlass.Int32(tidx)) @@ -66,6 +71,8 @@ def frost_head_reduce( acc_lo = acc_lo + lo acc_hi = acc_hi + hi (out_p + out_off).store(fp32_to_fp16(acc_lo, acc_hi, dtype=io_dtype)) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -86,6 +93,7 @@ def launch( grid=(grid_x, 1, 1), block=(BLOCK, 1, 1), stream=stream, + use_pdl=USE_PDL, ) diff --git a/python/cudnn/linear_attention/frost/common/l2norm.py b/python/cudnn/linear_attention/frost/common/l2norm.py index 38c954df5c..6fb64ba3fa 100644 --- a/python/cudnn/linear_attention/frost/common/l2norm.py +++ b/python/cudnn/linear_attention/frost/common/l2norm.py @@ -15,11 +15,14 @@ import cuda.bindings.driver as cuda import cutlass import cutlass.cute as cute -from cutlass.cute.arch.nvvm_wrappers import inline_ptx from cutlass.cute.runtime import from_dlpack from cudnn.frost.buffers import data_ptr from cudnn.frost.tile_dsl.pointwise import f16x2_to_f32, ffma2, fmul2, fp32_to_fp16, l2norm_inv, lane_group_sum +from cudnn.frost.tile_dsl.barrier import launch_dependent_grids, wait_on_dependent_grids +from cudnn.frost.tile_dsl.tma import ld_global, ld_global_v4, st_global, st_global_v4 + +USE_PDL = True THREADS_PER_ROW = 16 ROWS_PER_CTA = 8 @@ -43,12 +46,12 @@ def frost_l2norm_qk( """Grid over all q rows then all k rows, FWD_LANES lanes x 32 elements per row (4 x 128-bit loads per lane), FWD_ROWS_PER_GROUP consecutive rows batched per lane group. All rows' loads issue before the reductions and - the 4-lane butterfly is 2 steps, so memory latency pipelines (the - 16-lane single-row shape measured 75.7% of DRAM peak on GB200, this one - 88.3%; FLA's autotuned Triton tile is 91%). fp32 sums of squares, - rsqrt with the shared epsilon floor, normalized rows to the compact io - workspace, fp32 inverse norms to their slots. Tail rows clamp their - loads and skip stores.""" + the 4-lane butterfly is 2 steps, so memory latency pipelines. fp32 + sums of squares, rsqrt with the shared epsilon floor, normalized rows + to the compact io workspace, fp32 inverse norms to their slots. Tail + rows clamp their loads and skip stores.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() bid = cute.arch.block_idx() tidx = cutlass.Int32(cute.arch.thread_idx()[0]) grp = tidx // cutlass.Int32(FWD_LANES) @@ -85,11 +88,7 @@ def frost_l2norm_qk( nrm_addr = mInvK.iterator.toint() + cutlass.Int64(k_row) * cutlass.Int64(4) chunks = [] for c in cutlass.range_constexpr(4): - w0, w1, w2, w3 = inline_ptx( - "ld.global.v4.b32 {$0, $1, $2, $3}, [$4];", - write_only_types=[cutlass.Int32, cutlass.Int32, cutlass.Int32, cutlass.Int32], - read_only_args=[src_addr + cutlass.Int64(16 * c)], - ) + w0, w1, w2, w3 = ld_global_v4(src_addr + cutlass.Int64(16 * c), cutlass.Int32) f0, f1 = f16x2_to_f32(w0, dtype=mQ.element_type) f2, f3 = f16x2_to_f32(w1, dtype=mQ.element_type) f4, f5 = f16x2_to_f32(w2, dtype=mQ.element_type) @@ -116,12 +115,11 @@ def frost_l2norm_qk( w1 = fp32_to_fp16(s2, s3, dtype=mQ.element_type) w2 = fp32_to_fp16(s4, s5, dtype=mQ.element_type) w3 = fp32_to_fp16(s6, s7, dtype=mQ.element_type) - inline_ptx( - "st.global.v4.b32 [$0], {$1, $2, $3, $4};", - read_only_args=[workspace_addrs[r] + cutlass.Int64(16 * c), w0, w1, w2, w3], - ) + st_global_v4(workspace_addrs[r] + cutlass.Int64(16 * c), (w0, w1, w2, w3), cutlass.Int32) if lane_idx == cutlass.Int32(0): - inline_ptx("st.global.f32 [$0], $1;", read_only_args=[nrm_addrs[r], inv]) + st_global(nrm_addrs[r], inv, cutlass.Float32) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.kernel @@ -140,9 +138,9 @@ def frost_l2norm_qk_bwd( """In-place normalize-Jacobian projection of dq/dk: per row, fp32 dot of the incoming gradient with the saved normalized row (butterfly reduce), then ``inv_norm * (grad - dot * row_n)`` back to the caller's buffer. - Single row per lane group: the dot+projection already fills the memory - latency (92.9% SOL measured; the forward's row batching REGRESSED this - kernel to 86% on GB200, lyris job 2694953).""" + Single row per lane group.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() bid = cute.arch.block_idx() tidx = cutlass.Int32(cute.arch.thread_idx()[0]) row = cutlass.Int32(bid[0]) * cutlass.Int32(ROWS_PER_CTA) + tidx // cutlass.Int32(THREADS_PER_ROW) @@ -167,20 +165,12 @@ def frost_l2norm_qk_bwd( grad_addr = mDk.iterator.toint() + grad_elements * cutlass.Int64(2) workspace_addr = mKn.iterator.toint() + (cutlass.Int64(k_row) * cutlass.Int64(128) + cutlass.Int64(v0)) * cutlass.Int64(2) nrm_addr = mInvK.iterator.toint() + cutlass.Int64(k_row) * cutlass.Int64(4) - gw0, gw1, gw2, gw3 = inline_ptx( - "ld.global.v4.b32 {$0, $1, $2, $3}, [$4];", - write_only_types=[cutlass.Int32, cutlass.Int32, cutlass.Int32, cutlass.Int32], - read_only_args=[grad_addr], - ) + gw0, gw1, gw2, gw3 = ld_global_v4(grad_addr, cutlass.Int32) d0, d1 = f16x2_to_f32(gw0, dtype=mDq.element_type) d2, d3 = f16x2_to_f32(gw1, dtype=mDq.element_type) d4, d5 = f16x2_to_f32(gw2, dtype=mDq.element_type) d6, d7 = f16x2_to_f32(gw3, dtype=mDq.element_type) - nw0, nw1, nw2, nw3 = inline_ptx( - "ld.global.v4.b32 {$0, $1, $2, $3}, [$4];", - write_only_types=[cutlass.Int32, cutlass.Int32, cutlass.Int32, cutlass.Int32], - read_only_args=[workspace_addr], - ) + nw0, nw1, nw2, nw3 = ld_global_v4(workspace_addr, cutlass.Int32) n0, n1 = f16x2_to_f32(nw0, dtype=mQn.element_type) n2, n3 = f16x2_to_f32(nw1, dtype=mQn.element_type) n4, n5 = f16x2_to_f32(nw2, dtype=mQn.element_type) @@ -190,11 +180,7 @@ def frost_l2norm_qk_bwd( dot_lo, dot_hi = ffma2(d4, d5, n4, n5, dot_lo, dot_hi) dot_lo, dot_hi = ffma2(d6, d7, n6, n7, dot_lo, dot_hi) dot = lane_group_sum(dot_lo + dot_hi, THREADS_PER_ROW) - inv = inline_ptx( - "ld.global.f32 $0, [$1];", - write_only_types=[cutlass.Float32], - read_only_args=[nrm_addr], - ) + inv = ld_global(nrm_addr, cutlass.Float32) neg_dot = -dot p0, p1 = ffma2(neg_dot, neg_dot, n0, n1, d0, d1) p2, p3 = ffma2(neg_dot, neg_dot, n2, n3, d2, d3) @@ -208,10 +194,9 @@ def frost_l2norm_qk_bwd( w1 = fp32_to_fp16(q2, q3, dtype=mDq.element_type) w2 = fp32_to_fp16(q4, q5, dtype=mDq.element_type) w3 = fp32_to_fp16(q6, q7, dtype=mDq.element_type) - inline_ptx( - "st.global.v4.b32 [$0], {$1, $2, $3, $4};", - read_only_args=[grad_addr, w0, w1, w2, w3], - ) + st_global_v4(grad_addr, (w0, w1, w2, w3), cutlass.Int32) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -230,7 +215,7 @@ def l2norm_qk_launch( stream: cuda.CUstream, ): frost_l2norm_qk(q, k, q_n, k_n, inv_q, inv_k, n_q_rows, n_rows, h_q, h_k).launch( - grid=(n_blocks, 1, 1), block=(THREADS_PER_ROW * ROWS_PER_CTA, 1, 1), stream=stream + grid=(n_blocks, 1, 1), block=(THREADS_PER_ROW * ROWS_PER_CTA, 1, 1), stream=stream, use_pdl=USE_PDL ) @@ -250,7 +235,7 @@ def l2norm_qk_bwd_launch( stream: cuda.CUstream, ): frost_l2norm_qk_bwd(dq, dk, q_n, k_n, inv_q, inv_k, n_q_rows, n_rows, h_q, h_k).launch( - grid=(n_blocks, 1, 1), block=(THREADS_PER_ROW * ROWS_PER_CTA, 1, 1), stream=stream + grid=(n_blocks, 1, 1), block=(THREADS_PER_ROW * ROWS_PER_CTA, 1, 1), stream=stream, use_pdl=USE_PDL ) diff --git a/python/cudnn/linear_attention/frost/common/split_k.py b/python/cudnn/linear_attention/frost/common/split_k.py index 5642484567..e9958d8913 100644 --- a/python/cudnn/linear_attention/frost/common/split_k.py +++ b/python/cudnn/linear_attention/frost/common/split_k.py @@ -56,12 +56,16 @@ import cutlass import cutlass.cute as cute import cutlass.experimental.primitives as nvvm -from cutlass.cute.arch.nvvm_wrappers import inline_ptx from cutlass.cute.runtime import from_dlpack from cudnn.frost.buffers import data_ptr - +from cudnn.frost.tile_dsl.barrier import launch_dependent_grids, wait_on_dependent_grids from cudnn.frost.tile_dsl.pointwise import sigmoid, softplus +from cudnn.frost.tile_dsl.tma import ld_global_v2, ld_global_v4 + +from .host import get_dtype + +USE_PDL = True WORK_ITEM_FIELDS = 8 WARMUP_CAP_CHUNKS = 32 # hard warmup cap: a cut must saturate within one warp of chunks per side @@ -72,6 +76,9 @@ THREADS_PER_BLOCK = WARPS * WARP_SIZE SCAN_WARPS = 4 SCAN_THREADS = SCAN_WARPS * WARP_SIZE +PLAN_THREADS = 128 +SCAN_CTA_CAP = 16 # scan CTAs per SM before the block axis becomes a grid-stride loop +SCAN_BLOCK_LOOP_MAX = 4 # block-loop trips the cap may cost SCAN_ROWS_PER_WARP_MAX = 4 # consecutive chunk rows per scan warp; scan_rows_per_warp() shrinks it to fill the SMs SCAN_TOKEN_STRIDE = 1 # tokens sampled per chunk; a stride > 1 scales the effective threshold by it OVERHEAD_TOKENS = 256 # per-item fixed cost for the piece model: state reseed + pipeline refill + typical warmup @@ -151,12 +158,7 @@ def decode_work_item(cfg, tile_idx, mWorkItems): @cute.jit def emit_item(mWorkItems, mCount, batch_idx, head_idx, write_start, write_end, compute_start, compute_end, batch_start, batch_end): - count_addr = mCount.iterator.toint() - slot = inline_ptx( - "atom.global.add.s32 {$w0}, [{$r0}], 1;", - write_only_types=[cutlass.Int32], - read_only_args=[count_addr], - ) + slot = cutlass.Int32(nvvm.atomicrmw(nvvm.AtomicOp.ADD, mCount.iterator, cutlass.Int32(1))) mWorkItems[slot, 0] = batch_idx mWorkItems[slot, 1] = head_idx mWorkItems[slot, 2] = write_start @@ -350,7 +352,8 @@ def probe_warmup_bwd(lane_idx, x, limit, chunk_value_base, head_idx, mChunkVals, @cute.jit def read_plan(mChunkVals): """The batch-wide span :func:`frost_split_k_plan` left in the scratch's - last row. Spans are small integers, exact in fp32.""" + last row, or -1 when no tile of this batch can be cut. Spans are small + integers, exact in fp32.""" return mChunkVals[mChunkVals.shape[0] - cutlass.Int32(1), 0].to(cutlass.Int32) @@ -367,20 +370,38 @@ def frost_split_k_plan( mChunkVals: cute.Tensor, mCount: cute.Tensor, ): - """One thread: settle the batch-wide span once and leave it in the chunk - scratch's last row for the scan and the walk, and zero the item count. - - :func:`common_span` is batch-global, so ONE evaluation is all that is - needed -- but inlining it into the scan and the walk also puts its code - (two ``piece_choice`` expansions plus a ``P_WINDOW`` search) in kernels - that run tens of thousands of warps, and that costs those kernels ~7 us - and ~5 us respectively even on shapes whose grid is too full for the - probe to run at all. Here it costs one small launch.""" + """One CTA: settle the batch-wide span once and leave it in the chunk + scratch's last row for the scan and the walk, -1 there when no tile of the + batch admits a cut, and zero the item count. Both answers are batch-global, + so the scan and the walk read them instead of re-deriving them per warp.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() - if cutlass.Int32(tidx) == 0: + tidx = cutlass.Int32(tidx) + sCut = cutlass.Array(cutlass.Int32, 1, space=cutlass.AddressSpace.smem, alignment=8) + if tidx == 0: + sCut[0] = cutlass.Int32(0) + nvvm.barrier_cta_sync() + + # ---- cut admissibility over the batch: one thread per entry ---------------------- + cut = cutlass.Int32(0) + b = tidx + while b < batch_size: + nc = cute.ceil_div(cutlass.Int32(mCuSeqlens[b + 1]) - cutlass.Int32(mCuSeqlens[b]), b_t) + _, nb = piece_choice(overhead_chunks, num_sms, nc, n_tiles, ideal_chunks) + cut = cutlass.Int32(1) if nb > cutlass.Int32(1) else cut + b = b + cutlass.Int32(PLAN_THREADS) + nvvm.atomicrmw("max", sCut.data_ptr(0), cut, space=nvvm.SharedSpace.shared_cta) + nvvm.barrier_cta_sync() + + if tidx == 0: mCount[0] = cutlass.Int32(0) + any_cut = sCut[0] common = common_span(b_t, overhead_chunks, n_heads_out, num_sms, n_tiles, ideal_chunks, batch_size, mCuSeqlens) - mChunkVals[mChunkVals.shape[0] - cutlass.Int32(1), 0] = cutlass.Float32(common) + any_cut = cutlass.Int32(1) if common > cutlass.Int32(0) else any_cut + plan = cutlass.Float32(common) if any_cut > cutlass.Int32(0) else cutlass.Float32(-1.0) + mChunkVals[mChunkVals.shape[0] - cutlass.Int32(1), 0] = plan @cute.kernel @@ -396,6 +417,7 @@ def frost_split_k_scan_channel( n_tiles: cutlass.Int32, ideal_chunks: cutlass.Int32, batch_size: cutlass.Int32, + n_scan_blocks: cutlass.Int32, gate_scale_log2: cutlass.Float32, mGate: cute.Tensor, mALog: cute.Tensor | None, @@ -408,103 +430,113 @@ def frost_split_k_scan_channel( covers 16 chunk-scratch rows of head ``h``, one warp per chunk, lane ``l`` owning channels ``[l*cpl, (l+1)*cpl)``. Chunks outside a cut window never touch the gate. The item count is the plan kernel's.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx() tidx = cutlass.Int32(tidx) head_idx = cutlass.Int32(bidx[1]) lane_idx = tidx % cutlass.Int32(WARP_SIZE) widx = tidx // cutlass.Int32(WARP_SIZE) - row0 = (cutlass.Int32(bidx[0]) * cutlass.Int32(SCAN_WARPS) + widx) * cutlass.Int32(scan_rows) common = read_plan(mChunkVals) - - lo = cutlass.Int32(0) - hi = batch_size - cutlass.Int32(1) - while lo < hi: - mid = (lo + hi + cutlass.Int32(1)) // cutlass.Int32(2) - take = cutlass.Int32(mCuSeqlens[mid]) // cutlass.Int32(b_t) + mid <= row0 - lo = mid if take else lo - hi = hi if take else mid - cutlass.Int32(1) - batch_idx = lo - batch_start = cutlass.Int32(mCuSeqlens[batch_idx]) - batch_end = cutlass.Int32(mCuSeqlens[batch_idx + 1]) - batch_num_chunks = cute.ceil_div(batch_end - batch_start, b_t) - chunk_value_base = batch_start // cutlass.Int32(b_t) + batch_idx - span, num_blocks = span_choice(overhead_chunks, num_sms, batch_num_chunks, n_tiles, ideal_chunks, common) - - for rr in cutlass.range_constexpr(scan_rows): - row = row0 + cutlass.Int32(rr) - while (batch_idx + cutlass.Int32(1) < batch_size) and ( - cutlass.Int32(mCuSeqlens[batch_idx + 1]) // cutlass.Int32(b_t) + batch_idx + cutlass.Int32(1) <= row - ): - batch_idx = batch_idx + cutlass.Int32(1) + if common >= cutlass.Int32(0): + blk = cutlass.Int32(bidx[0]) + while blk < n_scan_blocks: + row0 = (blk * cutlass.Int32(SCAN_WARPS) + widx) * cutlass.Int32(scan_rows) + + lo = cutlass.Int32(0) + hi = batch_size - cutlass.Int32(1) + while lo < hi: + mid = (lo + hi + cutlass.Int32(1)) // cutlass.Int32(2) + take = cutlass.Int32(mCuSeqlens[mid]) // cutlass.Int32(b_t) + mid <= row0 + lo = mid if take else lo + hi = hi if take else mid - cutlass.Int32(1) + batch_idx = lo batch_start = cutlass.Int32(mCuSeqlens[batch_idx]) batch_end = cutlass.Int32(mCuSeqlens[batch_idx + 1]) batch_num_chunks = cute.ceil_div(batch_end - batch_start, b_t) chunk_value_base = batch_start // cutlass.Int32(b_t) + batch_idx span, num_blocks = span_choice(overhead_chunks, num_sms, batch_num_chunks, n_tiles, ideal_chunks, common) - c = row - chunk_value_base - if (c >= 0) and (c < batch_num_chunks) and (num_blocks > 1): - if near_boundary(c, span if span > 0 else cutlass.Int32(1), num_blocks): - # ---- per-channel clamped-log2 sums, one channel run per lane --------- - cpl = gate_channels // WARP_SIZE - row_elements = cutlass.Int32(mGate.stride[0]) - lane_base = cutlass.Int64(head_idx * cutlass.Int32(mGate.stride[1]) + lane_idx * cutlass.Int32(cpl)) - gate_addr = mGate.iterator.toint() + lane_base * cutlass.Int64(4) - gate_ptr = mGate.iterator + lane_base - a_exp = cutlass.Float32(1.0) - dt_vals = cutlass.Array(cutlass.Float32, cpl) - if cutlass.const_expr(safe_gate): - a_exp = cute.math.exp2(mALog[head_idx].to(cutlass.Float32) * cutlass.Float32(RCP_LN2), fastmath=True) - for q in cutlass.range_constexpr(cpl): - dt_vals[q] = mDtBias[head_idx, lane_idx * cutlass.Int32(cpl) + cutlass.Int32(q)].to(cutlass.Float32) - ch_acc = cutlass.Array(cutlass.Float32, cpl, alignment=16) - for q in cutlass.range_constexpr(cpl): - ch_acc[q] = cutlass.Float32(0.0) - oob = cutlass.Float32(0.0) if cutlass.const_expr(log_gate) else cutlass.Float32(1.0) - for tt in cutlass.range(0, b_t, SCAN_TOKEN_STRIDE, unroll_full=True): - pos = batch_start + c * cutlass.Int32(b_t) + cutlass.Int32(tt) - inb = pos < batch_end - pos_r = pos if inb else batch_start - grow = cutlass.Int64(pos_r) * cutlass.Int64(row_elements) - if cutlass.const_expr(cpl % 4 == 0): - for q4 in cutlass.range_constexpr(cpl // 4): - addr = gate_addr + (grow + cutlass.Int64(4 * q4)) * cutlass.Int64(4) - g0, g1, g2, g3 = inline_ptx( - "ld.global.v4.f32 {$0, $1, $2, $3}, [$4];", - write_only_types=[cutlass.Float32, cutlass.Float32, cutlass.Float32, cutlass.Float32], - read_only_args=[addr], - ) - for qq, gvq in enumerate((g0, g1, g2, g3)): - q = 4 * q4 + qq - if cutlass.const_expr(safe_gate): - sig = sigmoid(a_exp * (gvq + dt_vals[q])) - contrib = gate_scale_log2 * sig - contrib = contrib if inb else cutlass.Float32(0.0) - else: - gvq = gvq if inb else oob - contrib = clamped_log2(log_gate, gvq) - ch_acc[q] = ch_acc[q] + contrib - else: + + for rr in cutlass.range_constexpr(scan_rows): + row = row0 + cutlass.Int32(rr) + while (batch_idx + cutlass.Int32(1) < batch_size) and ( + cutlass.Int32(mCuSeqlens[batch_idx + 1]) // cutlass.Int32(b_t) + batch_idx + cutlass.Int32(1) <= row + ): + batch_idx = batch_idx + cutlass.Int32(1) + batch_start = cutlass.Int32(mCuSeqlens[batch_idx]) + batch_end = cutlass.Int32(mCuSeqlens[batch_idx + 1]) + batch_num_chunks = cute.ceil_div(batch_end - batch_start, b_t) + chunk_value_base = batch_start // cutlass.Int32(b_t) + batch_idx + span, num_blocks = span_choice(overhead_chunks, num_sms, batch_num_chunks, n_tiles, ideal_chunks, common) + c = row - chunk_value_base + if (c >= 0) and (c < batch_num_chunks) and (num_blocks > 1): + if near_boundary(c, span if span > 0 else cutlass.Int32(1), num_blocks): + # ---- per-channel clamped-log2 sums, one channel run per lane - + cpl = gate_channels // WARP_SIZE + row_elements = cutlass.Int32(mGate.stride[0]) + lane_base = cutlass.Int64(head_idx * cutlass.Int32(mGate.stride[1]) + lane_idx * cutlass.Int32(cpl)) + gate_elem_bytes = cutlass.const_expr(mGate.element_type.width // 8) + gate_addr = mGate.iterator.toint() + lane_base * cutlass.Int64(gate_elem_bytes) + gate_ptr = mGate.iterator + lane_base + a_exp = cutlass.Float32(1.0) + dt_vals = cutlass.Array(cutlass.Float32, cpl) + if cutlass.const_expr(safe_gate): + a_exp = cute.math.exp2(mALog[head_idx].to(cutlass.Float32) * cutlass.Float32(RCP_LN2), fastmath=True) + for q in cutlass.range_constexpr(cpl): + dt_vals[q] = mDtBias[head_idx, lane_idx * cutlass.Int32(cpl) + cutlass.Int32(q)].to(cutlass.Float32) + ch_acc = cutlass.Array(cutlass.Float32, cpl, alignment=16) for q in cutlass.range_constexpr(cpl): - gv = (gate_ptr + grow + cutlass.Int32(q)).load() - if cutlass.const_expr(safe_gate): - sig = sigmoid(a_exp * (gv + dt_vals[q])) - contrib = gate_scale_log2 * sig - contrib = contrib if inb else cutlass.Float32(0.0) + ch_acc[q] = cutlass.Float32(0.0) + oob = cutlass.Float32(0.0) if cutlass.const_expr(log_gate) else cutlass.Float32(1.0) + for tt in cutlass.range(0, b_t, SCAN_TOKEN_STRIDE, unroll_full=True): + pos = batch_start + c * cutlass.Int32(b_t) + cutlass.Int32(tt) + inb = pos < batch_end + pos_r = pos if inb else batch_start + grow = cutlass.Int64(pos_r) * cutlass.Int64(row_elements) + if cutlass.const_expr(cpl % 4 == 0): + for q4 in cutlass.range_constexpr(cpl // 4): + addr = gate_addr + (grow + cutlass.Int64(4 * q4)) * cutlass.Int64(gate_elem_bytes) + if cutlass.const_expr(mGate.element_type == cutlass.Float32): + quad = ld_global_v4(addr, cutlass.Float32) + else: + w0, w1 = ld_global_v2(addr, cutlass.Int32) + frag = cutlass.Vector.from_elements((w0, w1), cutlass.Int32).bitcast(mGate.element_type).to(cutlass.Float32) + quad = (frag[0], frag[1], frag[2], frag[3]) + for qq, gvq in enumerate(quad): + q = 4 * q4 + qq + if cutlass.const_expr(safe_gate): + sig = sigmoid(a_exp * (gvq + dt_vals[q])) + contrib = gate_scale_log2 * sig + contrib = contrib if inb else cutlass.Float32(0.0) + else: + gvq = gvq if inb else oob + contrib = clamped_log2(log_gate, gvq) + ch_acc[q] = ch_acc[q] + contrib else: - gv = gv if inb else oob - contrib = clamped_log2(log_gate, gv) - ch_acc[q] = ch_acc[q] + contrib - - # ---- chunk value = max over channels, then over lanes ---------------- - m = ch_acc[0] - for q in cutlass.range_constexpr(1, cpl): - m = m if m > ch_acc[q] else ch_acc[q] - for off in [1, 2, 4, 8, 16]: - other = cutlass.Float32(nvvm.shfl_sync(0xFFFFFFFF, m, off, 31, kind=nvvm.Shfl.BFLY)) - m = m if m > other else other - if lane_idx == 0: - mChunkVals[chunk_value_base + c, head_idx] = m + for q in cutlass.range_constexpr(cpl): + gv = (gate_ptr + grow + cutlass.Int32(q)).load().to(cutlass.Float32) + if cutlass.const_expr(safe_gate): + sig = sigmoid(a_exp * (gv + dt_vals[q])) + contrib = gate_scale_log2 * sig + contrib = contrib if inb else cutlass.Float32(0.0) + else: + gv = gv if inb else oob + contrib = clamped_log2(log_gate, gv) + ch_acc[q] = ch_acc[q] + contrib + + # ---- chunk value = max over channels, then over lanes -------- + m = ch_acc[0] + for q in cutlass.range_constexpr(1, cpl): + m = m if m > ch_acc[q] else ch_acc[q] + for off in [1, 2, 4, 8, 16]: + other = cutlass.Float32(nvvm.shfl_sync(0xFFFFFFFF, m, off, 31, kind=nvvm.Shfl.BFLY)) + m = m if m > other else other + if lane_idx == 0: + mChunkVals[chunk_value_base + c, head_idx] = m + blk = blk + cutlass.Int32(cute.arch.grid_dim()[0]) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.kernel @@ -519,6 +551,7 @@ def frost_split_k_scan_scalar( n_tiles: cutlass.Int32, ideal_chunks: cutlass.Int32, batch_size: cutlass.Int32, + n_scan_blocks: cutlass.Int32, mGate: cute.Tensor, mALog: cute.Tensor | None, mDtBias: cute.Tensor | None, @@ -531,6 +564,8 @@ def frost_split_k_scan_scalar( ``hg*32 + l``, so reads and writes coalesce and no reduction is needed. With ``safe_gate`` each token contributes ``-exp(A_log[h]) * softplus(g + dt_bias[h]) * RCP_LN2``. The item count is the plan kernel's.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx() tidx = cutlass.Int32(tidx) @@ -544,53 +579,59 @@ def frost_split_k_scan_scalar( if cutlass.const_expr(safe_gate): a = -cute.math.exp2(mALog[h_r].to(cutlass.Float32) * cutlass.Float32(RCP_LN2), fastmath=True) * cutlass.Float32(RCP_LN2) bias = mDtBias[h_r].to(cutlass.Float32) - row0 = (cutlass.Int32(bidx[0]) * cutlass.Int32(SCAN_WARPS) + widx) * cutlass.Int32(scan_rows) common = read_plan(mChunkVals) - - lo = cutlass.Int32(0) - hi = batch_size - cutlass.Int32(1) - while lo < hi: - mid = (lo + hi + cutlass.Int32(1)) // cutlass.Int32(2) - take = cutlass.Int32(mCuSeqlens[mid]) // cutlass.Int32(b_t) + mid <= row0 - lo = mid if take else lo - hi = hi if take else mid - cutlass.Int32(1) - batch_idx = lo - batch_start = cutlass.Int32(mCuSeqlens[batch_idx]) - batch_end = cutlass.Int32(mCuSeqlens[batch_idx + 1]) - batch_num_chunks = cute.ceil_div(batch_end - batch_start, b_t) - chunk_value_base = batch_start // cutlass.Int32(b_t) + batch_idx - span, num_blocks = span_choice(overhead_chunks, num_sms, batch_num_chunks, n_tiles, ideal_chunks, common) - - for rr in cutlass.range_constexpr(scan_rows): - row = row0 + cutlass.Int32(rr) - while (batch_idx + cutlass.Int32(1) < batch_size) and ( - cutlass.Int32(mCuSeqlens[batch_idx + 1]) // cutlass.Int32(b_t) + batch_idx + cutlass.Int32(1) <= row - ): - batch_idx = batch_idx + cutlass.Int32(1) + if common >= cutlass.Int32(0): + blk = cutlass.Int32(bidx[0]) + while blk < n_scan_blocks: + row0 = (blk * cutlass.Int32(SCAN_WARPS) + widx) * cutlass.Int32(scan_rows) + + lo = cutlass.Int32(0) + hi = batch_size - cutlass.Int32(1) + while lo < hi: + mid = (lo + hi + cutlass.Int32(1)) // cutlass.Int32(2) + take = cutlass.Int32(mCuSeqlens[mid]) // cutlass.Int32(b_t) + mid <= row0 + lo = mid if take else lo + hi = hi if take else mid - cutlass.Int32(1) + batch_idx = lo batch_start = cutlass.Int32(mCuSeqlens[batch_idx]) batch_end = cutlass.Int32(mCuSeqlens[batch_idx + 1]) batch_num_chunks = cute.ceil_div(batch_end - batch_start, b_t) chunk_value_base = batch_start // cutlass.Int32(b_t) + batch_idx span, num_blocks = span_choice(overhead_chunks, num_sms, batch_num_chunks, n_tiles, ideal_chunks, common) - c = row - chunk_value_base - if (c >= 0) and (c < batch_num_chunks) and (num_blocks > 1): - if near_boundary(c, span if span > 0 else cutlass.Int32(1), num_blocks): - # ---- clamped-log2 sum over the chunk, one head per lane -------------- - oob = cutlass.Float32(0.0) if cutlass.const_expr(log_gate) else cutlass.Float32(1.0) - acc = cutlass.Float32(0.0) - for tt in cutlass.range(0, b_t, SCAN_TOKEN_STRIDE, unroll_full=True): - pos = batch_start + c * cutlass.Int32(b_t) + cutlass.Int32(tt) - inb = pos < batch_end - pos_r = pos if inb else batch_start - gv = (mGate.iterator + cutlass.Int64(pos_r) * cutlass.Int64(mGate.stride[0]) + h_r).load() - if cutlass.const_expr(safe_gate): - contrib = a * softplus(gv + bias) - acc = acc + (contrib if inb else cutlass.Float32(0.0)) - else: - gv = gv if inb else oob - acc = acc + clamped_log2(log_gate, gv) - if h_ok: - mChunkVals[chunk_value_base + c, h] = acc + + for rr in cutlass.range_constexpr(scan_rows): + row = row0 + cutlass.Int32(rr) + while (batch_idx + cutlass.Int32(1) < batch_size) and ( + cutlass.Int32(mCuSeqlens[batch_idx + 1]) // cutlass.Int32(b_t) + batch_idx + cutlass.Int32(1) <= row + ): + batch_idx = batch_idx + cutlass.Int32(1) + batch_start = cutlass.Int32(mCuSeqlens[batch_idx]) + batch_end = cutlass.Int32(mCuSeqlens[batch_idx + 1]) + batch_num_chunks = cute.ceil_div(batch_end - batch_start, b_t) + chunk_value_base = batch_start // cutlass.Int32(b_t) + batch_idx + span, num_blocks = span_choice(overhead_chunks, num_sms, batch_num_chunks, n_tiles, ideal_chunks, common) + c = row - chunk_value_base + if (c >= 0) and (c < batch_num_chunks) and (num_blocks > 1): + if near_boundary(c, span if span > 0 else cutlass.Int32(1), num_blocks): + # ---- clamped-log2 sum over the chunk, one head per lane ------ + oob = cutlass.Float32(0.0) if cutlass.const_expr(log_gate) else cutlass.Float32(1.0) + acc = cutlass.Float32(0.0) + for tt in cutlass.range(0, b_t, SCAN_TOKEN_STRIDE, unroll_full=True): + pos = batch_start + c * cutlass.Int32(b_t) + cutlass.Int32(tt) + inb = pos < batch_end + pos_r = pos if inb else batch_start + gv = (mGate.iterator + cutlass.Int64(pos_r) * cutlass.Int64(mGate.stride[0]) + h_r).load().to(cutlass.Float32) + if cutlass.const_expr(safe_gate): + contrib = a * softplus(gv + bias) + acc = acc + (contrib if inb else cutlass.Float32(0.0)) + else: + gv = gv if inb else oob + acc = acc + clamped_log2(log_gate, gv) + if h_ok: + mChunkVals[chunk_value_base + c, h] = acc + blk = blk + cutlass.Int32(cute.arch.grid_dim()[0]) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.kernel @@ -611,6 +652,8 @@ def frost_split_k_walk( own warp (one lane per window chunk, warp-scan for the smallest saturating warmup), then thread 0 walks the probe results and emits the items.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) tile = cutlass.Int32(cute.arch.block_idx()[0]) @@ -624,7 +667,10 @@ def frost_split_k_walk( batch_end = cutlass.Int32(mCuSeqlens[batch_idx + 1]) batch_num_chunks = cute.ceil_div(batch_end - batch_start, b_t) chunk_value_base = batch_start // cutlass.Int32(b_t) + batch_idx - span, num_blocks = span_choice(overhead_chunks, num_sms, batch_num_chunks, n_tiles, ideal_chunks, common) + span = cutlass.Int32(0) + num_blocks = cutlass.Int32(1) + if common >= cutlass.Int32(0): + span, num_blocks = span_choice(overhead_chunks, num_sms, batch_num_chunks, n_tiles, ideal_chunks, common) if num_blocks <= 1: # ---- nothing to scan: emit the whole sequence -------------------------------- if tidx == 0: @@ -686,6 +732,8 @@ def frost_split_k_walk( prev_cut = write_end jj = jj + cutlass.Int32(1) emit_item(mStaging, mCount, batch_idx, head_idx, prev_cut, batch_num_chunks, current_compute_start, batch_num_chunks, batch_start, batch_end) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -746,6 +794,7 @@ def order_body( sKey, sIdx, sSpread, + num_ctas: cutlass.Constexpr[int] = 0, ): """Bitonic-sort the staged items by ``compute_end - compute_start``, longest first, into ``work_items``; with ``gen`` synthesize the uncut item @@ -770,8 +819,8 @@ def order_body( else: n = mCount[0] - # ---- copy through unsorted when past SMEM sort capacity -------------------------- - if n > cutlass.Int32(capacity): + # ---- copy through unsorted: past sort capacity, or one item per CTA -------------- + if (n > cutlass.Int32(capacity)) or (n <= cutlass.Int32(num_ctas)): i = tidx while i < n: write_item(gen, b_t, n_heads_out, mCuSeqlens, mStaging, mWorkItems, i, i) @@ -873,6 +922,7 @@ def launch( mCount: cute.Tensor, mScheduler: cute.Tensor | None, n_scan_ctas: cutlass.Int32, + n_scan_blocks: cutlass.Int32, n_walk_ctas: cutlass.Int32, stream: cuda.CUstream, ) -> None: @@ -888,7 +938,7 @@ def launch( mCuSeqlens, mChunkVals, mCount, - ).launch(grid=(1, 1, 1), block=(1, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(PLAN_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) if cutlass.const_expr(gate_channels > 0): frost_split_k_scan_channel( b_t, @@ -902,6 +952,7 @@ def launch( n_tiles, ideal_chunks, batch_size, + n_scan_blocks, gate_scale_log2, mGate, mALog, @@ -913,6 +964,7 @@ def launch( grid=(n_scan_ctas, n_heads_out, 1), block=(SCAN_THREADS, 1, 1), stream=stream, + use_pdl=USE_PDL, ) else: frost_split_k_scan_scalar( @@ -926,6 +978,7 @@ def launch( n_tiles, ideal_chunks, batch_size, + n_scan_blocks, mGate, mALog, mDtBias, @@ -936,6 +989,7 @@ def launch( grid=(n_scan_ctas, -(-n_heads_out // WARP_SIZE), 1), block=(SCAN_THREADS, 1, 1), stream=stream, + use_pdl=USE_PDL, ) frost_split_k_walk( b_t, @@ -953,6 +1007,7 @@ def launch( grid=(n_walk_ctas, 1, 1), block=(THREADS_PER_BLOCK, 1, 1), stream=stream, + use_pdl=USE_PDL, ) @@ -975,6 +1030,7 @@ class TableRecipe(NamedTuple): log2_threshold: float gate_scale_log2: float n_scan_ctas: int + n_scan_blocks: int n_walk_ctas: int @@ -997,6 +1053,7 @@ def run_table(r, gate, a_log, dt_bias, cu_seqlens, chunk_scratch, item_scratch, work_count, scheduler_counter, r.n_scan_ctas, + r.n_scan_blocks, r.n_walk_ctas, cuda.CUstream(int(stream)), ) @@ -1064,13 +1121,19 @@ def build_split_table( raise ValueError("split=True requires ideal_chunks, chunk_scratch, and item_scratch") if gate_channels and gate_channels % WARP_SIZE != 0: raise ValueError(f"per-channel gate dim must be a multiple of {WARP_SIZE}, got {gate_channels}") - if gate_channels and gate_channels % 128 == 0 and data_ptr(gate) % 16 != 0: - raise ValueError("per-channel gate base must be 16-byte aligned (vectorized scan loads)") + gate_elem_bytes = get_dtype(gate.dtype).width // 8 + gate_vector_bytes = 4 * gate_elem_bytes + if gate_channels and gate_channels % 128 == 0 and data_ptr(gate) % gate_vector_bytes != 0: + raise ValueError(f"per-channel gate base must be {gate_vector_bytes}-byte aligned (vectorized scan loads)") n_walk_ctas = batch_size * n_heads_out need_rows = chunk_scratch_rows(gate.shape[0], batch_size, b_t) grid_y = n_heads_out if gate_channels > 0 else -(-n_heads_out // WARP_SIZE) scan_rows = scan_rows_per_warp(need_rows, grid_y, num_sms) - n_scan_ctas = -(-need_rows // (SCAN_WARPS * scan_rows)) + n_scan_blocks = -(-need_rows // (SCAN_WARPS * scan_rows)) + n_scan_ctas = min( + n_scan_blocks, + max(max(1, SCAN_CTA_CAP * num_sms // grid_y), -(-n_scan_blocks // SCAN_BLOCK_LOOP_MAX)), + ) if len(chunk_scratch.shape) != 2 or chunk_scratch.shape[0] < need_rows or chunk_scratch.shape[1] != n_heads_out: raise ValueError(f"chunk_scratch must be (>= {need_rows}, {n_heads_out}) fp32, got {tuple(chunk_scratch.shape)}") if tuple(item_scratch.shape) != tuple(work_items.shape) or work_items.shape[1] != WORK_ITEM_FIELDS: @@ -1091,6 +1154,7 @@ def build_split_table( gate_channels, scheduler_counter is not None, str(cu_seqlens.dtype), + str(gate.dtype), ) if key not in compiled_cache: @@ -1126,7 +1190,7 @@ def build_split_table( cutlass.Int32(batch_size), cutlass.Float32(log2_threshold), cutlass.Float32(gate_scale_log2), - from_dlpack(gate, assumed_align=4).mark_layout_dynamic(leading_dim=len(gate.shape) - 1) if split else None, + from_dlpack(gate, assumed_align=(8 if gate_elem_bytes == 2 else 4)).mark_layout_dynamic(leading_dim=len(gate.shape) - 1) if split else None, from_dlpack(a_log, assumed_align=4).mark_layout_dynamic() if safe_gate else None, dt_bias_c, from_dlpack(cu_seqlens, assumed_align=4).mark_layout_dynamic(), @@ -1136,6 +1200,7 @@ def build_split_table( work_count_c, from_dlpack(scheduler_counter, assumed_align=4).mark_layout_dynamic() if scheduler_counter is not None else None, cutlass.Int32(n_scan_ctas), + cutlass.Int32(n_scan_blocks), cutlass.Int32(n_walk_ctas), cu_stream, options="--enable-tvm-ffi", @@ -1156,6 +1221,7 @@ def build_split_table( work_count, scheduler_counter, n_scan_ctas, + n_scan_blocks, n_walk_ctas, cu_stream, ) @@ -1171,6 +1237,7 @@ def build_split_table( float(log2_threshold), float(gate_scale_log2), n_scan_ctas, + n_scan_blocks, n_walk_ctas, ) diff --git a/python/cudnn/linear_attention/frost/engine.py b/python/cudnn/linear_attention/frost/engine.py index 7c8eeeacd3..e55b287c35 100644 --- a/python/cudnn/linear_attention/frost/engine.py +++ b/python/cudnn/linear_attention/frost/engine.py @@ -41,8 +41,8 @@ def frost_la_gate(engine: str, facts, op: str) -> None: raise NotImplementedError(f"{engine}: k heads ({facts.h_k}) must match q's ({facts.h_q}) or v's ({facts.h_v}; canonical GQA shares grouped k/v heads)") if facts.h_v != facts.h_q and max(facts.h_q, facts.h_v) % min(facts.h_q, facts.h_v) != 0: raise NotImplementedError(f"{engine}: q heads ({facts.h_q}) and v heads ({facts.h_v}) must be equal or one a multiple of the other") - if facts.g_dtype not in (cudnn.data_type.FLOAT, None): - raise NotImplementedError(f"{engine}: 'g' must be fp32, got {facts.g_dtype}") + if facts.g_dtype not in (cudnn.data_type.FLOAT, cudnn.data_type.BFLOAT16, cudnn.data_type.HALF, None): + raise NotImplementedError(f"{engine}: 'g' must be fp32/fp16/bf16, got {facts.g_dtype}") if facts.cu_dtype not in (cudnn.data_type.INT32, cudnn.data_type.INT64, None): raise NotImplementedError(f"{engine}: 'cu_seqlens' must be int32/int64, got {facts.cu_dtype}") diff --git a/python/cudnn/linear_attention/frost/gdn2_engine.py b/python/cudnn/linear_attention/frost/gdn2_engine.py index bf69fe438b..1427f64201 100644 --- a/python/cudnn/linear_attention/frost/gdn2_engine.py +++ b/python/cudnn/linear_attention/frost/gdn2_engine.py @@ -67,17 +67,22 @@ def check_support(self, graph) -> None: for port, got in (("a_log", facts.a_log_dtype), ("dt_bias", facts.dt_bias_dtype)): if got not in (fp32, None): raise NotImplementedError(f"Gdn2FrostEngine: '{port}' must be fp32, got {got}") + state_dtypes = (fp32, cudnn.data_type.BFLOAT16) + for port, got in (("initial_state", facts.state_dtype), ("final_state", facts.final_state_dtype)): + if got not in state_dtypes + (None,): + raise NotImplementedError(f"Gdn2FrostEngine: '{port}' must be fp32/bf16, got {got}") if facts.is_bwd: - for port, got in ( - ("d_a_log", facts.d_a_log_dtype), - ("d_dt_bias", facts.d_dt_bias_dtype), - ("initial_state", facts.state_dtype), - ("d_final_state", facts.d_final_state_dtype), - ("d_initial_state", facts.d_initial_state_dtype), - ("dG", facts.dg_dtype), - ): + for port, got in (("d_a_log", facts.d_a_log_dtype), ("d_dt_bias", facts.d_dt_bias_dtype)): if got not in (fp32, None): raise NotImplementedError(f"Gdn2FrostEngine: '{port}' must be fp32, got {got}") + state_grad_want = facts.state_dtype if facts.state_dtype is not None else fp32 + for port, got in (("d_final_state", facts.d_final_state_dtype), ("d_initial_state", facts.d_initial_state_dtype)): + if got not in (state_grad_want, None): + raise NotImplementedError(f"Gdn2FrostEngine: '{port}' must match the state dtype ({state_grad_want}), got {got}") + if facts.wants_d_initial_state and facts.d_initial_state_dtype is None: + raise NotImplementedError(f"Gdn2FrostEngine: 'd_initial_state' must mirror initial_state ({state_grad_want}), got an unset dtype") + if facts.dg_dtype not in (facts.g_dtype, None): + raise NotImplementedError(f"Gdn2FrostEngine: 'dG' must match 'g' ({facts.g_dtype}), got {facts.dg_dtype}") for port, got in ( ("dO", facts.do_dtype), ("state_checkpoints", facts.state_checkpoints_dtype), @@ -86,13 +91,8 @@ def check_support(self, graph) -> None: ): if facts.io_dtype is not None and got not in (facts.io_dtype, None): raise NotImplementedError(f"Gdn2FrostEngine: '{port}' must match the io dtype, got {got}") - else: - state_dtypes = (fp32, cudnn.data_type.BFLOAT16) - for port, got in (("initial_state", facts.state_dtype), ("final_state", facts.final_state_dtype)): - if got not in state_dtypes + (None,): - raise NotImplementedError(f"Gdn2FrostEngine: '{port}' must be fp32/bf16, got {got}") - if facts.io_dtype is not None and facts.state_checkpoints_out_dtype not in (facts.io_dtype, None): - raise NotImplementedError("Gdn2FrostEngine: 'state_checkpoints' must match the io dtype") + elif facts.io_dtype is not None and facts.state_checkpoints_out_dtype not in (facts.io_dtype, None): + raise NotImplementedError("Gdn2FrostEngine: 'state_checkpoints' must match the io dtype") if not facts.state_pair_match: raise NotImplementedError("Gdn2FrostEngine: initial_state and final_state dtypes must match") @@ -347,10 +347,8 @@ def __init__(self, node, bwd_module, recompute_module): layout = WorkspaceLayout() self.off_scheduler = layout.add(16) self.num_sm = multiprocessor_count(current_device()) - # dynamic always: static costs 2.5-10.5% at multi-wave tile counts and never wins (lyris job 2752338) self.bwd_dynamic_scheduling = True self.batch_invariant = bool(node.params.get("batch_invariant", False)) - # cuts never in batch-invariant mode self.split = not self.batch_invariant self.n_tiles = B * HO if self.split: diff --git a/python/cudnn/linear_attention/frost/gdn_engine.py b/python/cudnn/linear_attention/frost/gdn_engine.py index dd19228217..c5aa6b7ea1 100644 --- a/python/cudnn/linear_attention/frost/gdn_engine.py +++ b/python/cudnn/linear_attention/frost/gdn_engine.py @@ -60,9 +60,9 @@ def check_support(self, graph) -> None: fp32 = cudnn.data_type.FLOAT io = (cudnn.data_type.BFLOAT16, cudnn.data_type.HALF) state_dtypes = (fp32, cudnn.data_type.BFLOAT16) - beta_want = facts.io_dtype if facts.use_beta_sigmoid else fp32 - if beta_want is not None and facts.beta_dtype not in (beta_want, None): - raise NotImplementedError(f"GdnFrostEngine: 'beta' must be {beta_want} (io-dtype logits under use_beta_sigmoid), got {facts.beta_dtype}") + beta_wants = (facts.io_dtype,) if facts.use_beta_sigmoid else (fp32, facts.io_dtype) + if facts.beta_dtype not in beta_wants + (None,): + raise NotImplementedError(f"GdnFrostEngine: 'beta' must be {' or '.join(str(w) for w in beta_wants)}, got {facts.beta_dtype}") for port, got in (("a_log", facts.a_log_dtype), ("dt_bias", facts.dt_bias_dtype)): if got not in (fp32, None): raise NotImplementedError(f"GdnFrostEngine: '{port}' must be fp32, got {got}") @@ -72,22 +72,23 @@ def check_support(self, graph) -> None: if not facts.state_pair_match: raise NotImplementedError("GdnFrostEngine: initial_state and final_state dtypes must match") if facts.is_bwd: - for port, got in ( - ("d_a_log", facts.d_a_log_dtype), - ("d_dt_bias", facts.d_dt_bias_dtype), - ("d_final_state", facts.d_final_state_dtype), - ("d_initial_state", facts.d_initial_state_dtype), - ("dG", facts.dg_dtype), - ): + for port, got in (("d_a_log", facts.d_a_log_dtype), ("d_dt_bias", facts.d_dt_bias_dtype)): if got not in (fp32, None): raise NotImplementedError(f"GdnFrostEngine: '{port}' must be fp32, got {got}") + state_grad_want = facts.state_dtype if facts.state_dtype is not None else fp32 + for port, got in (("d_final_state", facts.d_final_state_dtype), ("d_initial_state", facts.d_initial_state_dtype)): + if got not in (state_grad_want, None): + raise NotImplementedError(f"GdnFrostEngine: '{port}' must match the state dtype ({state_grad_want}), got {got}") + if facts.wants_d_initial_state and facts.d_initial_state_dtype is None: + raise NotImplementedError(f"GdnFrostEngine: 'd_initial_state' must mirror initial_state ({state_grad_want}), got an unset dtype") + if facts.dg_dtype not in (facts.g_dtype, None): + raise NotImplementedError(f"GdnFrostEngine: 'dG' must match 'g' ({facts.g_dtype}), got {facts.dg_dtype}") if facts.do_dtype not in io + (None,): raise NotImplementedError(f"GdnFrostEngine: 'dO' must be fp16/bf16, got {facts.do_dtype}") if facts.io_dtype is not None and facts.state_checkpoints_dtype not in (facts.io_dtype, None): raise NotImplementedError("GdnFrostEngine: 'state_checkpoints' must match the io dtype") - dbeta_want = facts.io_dtype if facts.use_beta_sigmoid and facts.io_dtype is not None else fp32 - if facts.dbeta_dtype not in (dbeta_want, None): - raise NotImplementedError(f"GdnFrostEngine: 'dBeta' must be {dbeta_want}, got {facts.dbeta_dtype}") + if facts.dbeta_dtype not in (facts.beta_dtype, None): + raise NotImplementedError(f"GdnFrostEngine: 'dBeta' must match 'beta' ({facts.beta_dtype}), got {facts.dbeta_dtype}") elif facts.io_dtype is not None and facts.state_checkpoints_out_dtype not in (facts.io_dtype, None): raise NotImplementedError("GdnFrostEngine: 'state_checkpoints' must match the io dtype") @@ -353,7 +354,6 @@ def __init__(self, node, bwd_module, recompute_module): self.num_sm = multiprocessor_count(current_device()) self.bwd_dynamic_scheduling = True self.batch_invariant = bool(node.params.get("batch_invariant", False)) - # cuts never in batch-invariant mode self.split = not self.batch_invariant layout = WorkspaceLayout() self.off_scheduler = layout.add(16) diff --git a/python/cudnn/linear_attention/frost/kda_engine.py b/python/cudnn/linear_attention/frost/kda_engine.py index 7c841e8878..cda5746fc8 100644 --- a/python/cudnn/linear_attention/frost/kda_engine.py +++ b/python/cudnn/linear_attention/frost/kda_engine.py @@ -59,38 +59,37 @@ def check_support(self, graph) -> None: if not facts.gates_at_ho: raise NotImplementedError(f"KdaFrostEngine: g/beta must carry HO = max(q, v) heads ({facts.h_o})") fp32 = cudnn.data_type.FLOAT - beta_want = facts.io_dtype if facts.use_beta_sigmoid else fp32 - if beta_want is not None and facts.beta_dtype not in (beta_want, None): - raise NotImplementedError(f"KdaFrostEngine: 'beta' must be {beta_want} (io-dtype logits under use_beta_sigmoid), got {facts.beta_dtype}") + beta_wants = (facts.io_dtype,) if facts.use_beta_sigmoid else (fp32, facts.io_dtype) + if facts.beta_dtype not in beta_wants + (None,): + raise NotImplementedError(f"KdaFrostEngine: 'beta' must be {' or '.join(str(w) for w in beta_wants)}, got {facts.beta_dtype}") + state_dtypes = (fp32, cudnn.data_type.BFLOAT16) + for port, got in (("initial_state", facts.state_dtype), ("final_state", facts.final_state_dtype)): + if got not in state_dtypes + (None,): + raise NotImplementedError(f"KdaFrostEngine: '{port}' must be fp32/bf16, got {got}") + if not facts.state_pair_match: + raise NotImplementedError("KdaFrostEngine: initial_state and final_state dtypes must match") for port, got in (("a_log", facts.a_log_dtype), ("dt_bias", facts.dt_bias_dtype)): if got not in (fp32, None): raise NotImplementedError(f"KdaFrostEngine: '{port}' must be fp32, got {got}") if facts.is_bwd: - for port, got in ( - ("d_a_log", facts.d_a_log_dtype), - ("d_dt_bias", facts.d_dt_bias_dtype), - ("initial_state", facts.state_dtype), - ("d_final_state", facts.d_final_state_dtype), - ("d_initial_state", facts.d_initial_state_dtype), - ("dG", facts.dg_dtype), - ): + for port, got in (("d_a_log", facts.d_a_log_dtype), ("d_dt_bias", facts.d_dt_bias_dtype)): if got not in (fp32, None): raise NotImplementedError(f"KdaFrostEngine: '{port}' must be fp32, got {got}") + state_grad_want = facts.state_dtype if facts.state_dtype is not None else fp32 + for port, got in (("d_final_state", facts.d_final_state_dtype), ("d_initial_state", facts.d_initial_state_dtype)): + if got not in (state_grad_want, None): + raise NotImplementedError(f"KdaFrostEngine: '{port}' must match the state dtype ({state_grad_want}), got {got}") + if facts.wants_d_initial_state and facts.d_initial_state_dtype is None: + raise NotImplementedError(f"KdaFrostEngine: 'd_initial_state' must mirror initial_state ({state_grad_want}), got an unset dtype") + if facts.dg_dtype not in (facts.g_dtype, None): + raise NotImplementedError(f"KdaFrostEngine: 'dG' must match 'g' ({facts.g_dtype}), got {facts.dg_dtype}") for port, got in (("dO", facts.do_dtype), ("state_checkpoints", facts.state_checkpoints_dtype)): if got not in (facts.io_dtype, None): raise NotImplementedError(f"KdaFrostEngine: '{port}' must match the io dtype") - dbeta_want = facts.io_dtype if facts.use_beta_sigmoid and facts.io_dtype is not None else fp32 - if facts.dbeta_dtype not in (dbeta_want, None): - raise NotImplementedError(f"KdaFrostEngine: 'dBeta' must be {dbeta_want}, got {facts.dbeta_dtype}") - else: - state_dtypes = (fp32, cudnn.data_type.BFLOAT16) - for port, got in (("initial_state", facts.state_dtype), ("final_state", facts.final_state_dtype)): - if got not in state_dtypes + (None,): - raise NotImplementedError(f"KdaFrostEngine: '{port}' must be fp32/bf16, got {got}") - if facts.io_dtype is not None and facts.state_checkpoints_out_dtype not in (facts.io_dtype, None): - raise NotImplementedError("KdaFrostEngine: 'state_checkpoints' must match the io dtype") - if not facts.state_pair_match: - raise NotImplementedError("KdaFrostEngine: initial_state and final_state dtypes must match") + if facts.dbeta_dtype not in (facts.beta_dtype, None): + raise NotImplementedError(f"KdaFrostEngine: 'dBeta' must match 'beta' ({facts.beta_dtype}), got {facts.dbeta_dtype}") + elif facts.io_dtype is not None and facts.state_checkpoints_out_dtype not in (facts.io_dtype, None): + raise NotImplementedError("KdaFrostEngine: 'state_checkpoints' must match the io dtype") def build_plan(self, graph, plan, ctx=None) -> CompiledPlan: # Bake the plan for the handle's device (via ctx), not the ambient one; a @@ -338,10 +337,8 @@ def __init__(self, node, bwd_module, recompute_module): layout = WorkspaceLayout() self.off_scheduler = layout.add(16) self.num_sm = multiprocessor_count(current_device()) - # dynamic always: static costs 2.5-10.5% at multi-wave tile counts and never wins (lyris job 2752338) self.bwd_dynamic_scheduling = True self.batch_invariant = bool(node.params.get("batch_invariant", False)) - # cuts never in batch-invariant mode self.split = not self.batch_invariant self.n_tiles = B * HO if self.split: diff --git a/python/cudnn/linear_attention/frost/kernel/gdn2_bprop_f16.py b/python/cudnn/linear_attention/frost/kernel/gdn2_bprop_f16.py index cd36bd3fae..464416d1d2 100644 --- a/python/cudnn/linear_attention/frost/kernel/gdn2_bprop_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/gdn2_bprop_f16.py @@ -18,6 +18,8 @@ from .gdn2_bprop_config import CFG from cudnn.frost.tile_dsl.barrier import ( + launch_dependent_grids, + wait_on_dependent_grids, advance, MBarrier, PipelineState, @@ -41,6 +43,8 @@ sub_f16x2, ) +USE_PDL = True + LOG2_E: float = 1.4426950408889634 DEFAULT_GATE_LOWER_BOUND: float = -5.0 L2_NORM_EPS: float = 1.0e-12 @@ -352,6 +356,7 @@ def epilogue_warp( tma_granu_elems=64, tma_subtile_stride_elems=cfg.b_t * 64, ) + dgate_granu = cutlass.const_expr(128 // (cfg.gate_dtype.width // 8)) sDgate_tma = SmemTile( base=sDgate_raw, elems_per_stage=(cfg.b_t * cfg.d_k), @@ -359,9 +364,9 @@ def epilogue_warp( leading_byte_offset=0, stride_byte_offset=0, layout=0, - tma_loads_per_tile=(cfg.d_k // 32), - tma_granu_elems=32, - tma_subtile_stride_elems=cfg.b_t * 32, + tma_loads_per_tile=(cfg.d_k // dgate_granu), + tma_granu_elems=dgate_granu, + tma_subtile_stride_elems=cfg.b_t * dgate_granu, ) sDb_tma = SmemTile( base=sDb_raw, @@ -1555,6 +1560,7 @@ def tmaldg_warp( tma_granu_elems=64, tma_subtile_stride_elems=(cfg.b_t * 64), ) + gate_granu = cutlass.const_expr(128 // (cfg.gate_dtype.width // 8)) sGate_tma = SmemTile( base=sGate_raw, elems_per_stage=(cfg.d_k * cfg.b_t), @@ -1562,8 +1568,8 @@ def tmaldg_warp( leading_byte_offset=0, stride_byte_offset=0, layout=0, - tma_loads_per_tile=(cfg.d_k // 32), - tma_granu_elems=32, + tma_loads_per_tile=(cfg.d_k // gate_granu), + tma_granu_elems=gate_granu, tma_subtile_stride_elems=(cfg.b_t * 32), ) sDo_tma = SmemTile( @@ -1708,6 +1714,8 @@ def tmaldg_warp( tma_load_tile(sW_tma[raw_index.idx], w_slice, bars.mb_w_ready[raw_index.idx].smem_ptr, acquire=False) raw_index = advance(raw_index, cfg.smem_raw_stages) tile_idx = next_tile + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -1737,6 +1745,7 @@ def compute0_warp_group( mDt_bias, sK_inv_raw, sGate_raw, + sGate_load_ptr, sK_raw, sQ_raw, sState_raw, @@ -1793,7 +1802,8 @@ def compute0_warp_group( sK_ptr = sK_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sBetaP_ptr = sBeta_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sWP_ptr = sW_raw.data_ptr() + raw_stage * (cfg.d_v * cfg.b_t) - sGate_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) + sGate_ptr = sGate_load_ptr + raw_stage * cfg.gate_stage_elems + sGate_exchange_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sK_inv_ptr = sK_inv_raw.data_ptr() + decay_stage * (cfg.b_t * cfg.d_k) sK_decay_ptr = sK_decay_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) sQ_decay_ptr = sQ_decay_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) @@ -1810,54 +1820,98 @@ def compute0_warp_group( lane_in_row_group = lane_idx - lane_row_group * 8 decay_row = row_group_start + lane_row_group - gate_prefix_ptr = sGate_ptr + gate_prefix_ptr = sGate_exchange_ptr channel_dim = cg0_warp * cfg.threads_per_warp + lane_idx # ---- gate prefix scan: cumulative log-gate per key channel --------------- f32_segment = channel_dim // 32 f32_segment_dim = channel_dim - f32_segment * 32 + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + raw_segment = channel_dim // 64 + raw_seg_base = raw_segment * (cfg.b_t * 64) + raw_col = channel_dim - raw_segment * 64 prefix_acc = cutlass.Float32(0.0) exp_g_last = cutlass.Float32(0.0) - for row_pair in cutlass.range(cfg.b_t // 2, unroll=1): - row0 = row_pair * 2 - row1 = row0 + 1 - prefix_idx0 = f32_segment * (cfg.b_t * 32) + row0 * 32 + swizzle_xor_128b(row0, f32_segment_dim, elem_bytes=4) - prefix_idx1 = f32_segment * (cfg.b_t * 32) + row1 * 32 + swizzle_xor_128b(row1, f32_segment_dim, elem_bytes=4) - gate0 = (sGate_ptr + prefix_idx0).load() - gate1 = (sGate_ptr + prefix_idx1).load() - token_idx0 = chunk_idx * cutlass.Int32(cfg.b_t) + row0 - token_idx1 = chunk_idx * cutlass.Int32(cfg.b_t) + row1 - if cutlass.const_expr(cfg.safe_gate): - if token_idx0 < batch_seqlen: - gate0 = gate_scale(cfg, cg0_a_log_exp * (gate0 + cg0_dt_bias_value)) - else: - gate0 = cutlass.Float32(0.0) - if token_idx1 < batch_seqlen: - gate1 = gate_scale(cfg, cg0_a_log_exp * (gate1 + cg0_dt_bias_value)) - else: - gate1 = cutlass.Float32(0.0) - else: - if token_idx0 < batch_seqlen: - gate0 = gate_scale(cfg, gate0) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + for row_pair in cutlass.range(cfg.b_t // 2, unroll=1): + row0 = row_pair * 2 + row1 = row0 + 1 + prefix_idx0 = f32_segment * (cfg.b_t * 32) + row0 * 32 + swizzle_xor_128b(row0, f32_segment_dim, elem_bytes=4) + prefix_idx1 = f32_segment * (cfg.b_t * 32) + row1 * 32 + swizzle_xor_128b(row1, f32_segment_dim, elem_bytes=4) + gate0 = (sGate_ptr + prefix_idx0).load() + gate1 = (sGate_ptr + prefix_idx1).load() + token_idx0 = chunk_idx * cutlass.Int32(cfg.b_t) + row0 + token_idx1 = chunk_idx * cutlass.Int32(cfg.b_t) + row1 + if cutlass.const_expr(cfg.safe_gate): + if token_idx0 < batch_seqlen: + gate0 = gate_scale(cfg, cg0_a_log_exp * (gate0 + cg0_dt_bias_value)) + else: + gate0 = cutlass.Float32(0.0) + if token_idx1 < batch_seqlen: + gate1 = gate_scale(cfg, cg0_a_log_exp * (gate1 + cg0_dt_bias_value)) + else: + gate1 = cutlass.Float32(0.0) else: - gate0 = cutlass.Float32(0.0) - if token_idx1 < batch_seqlen: - gate1 = gate_scale(cfg, gate1) + if token_idx0 < batch_seqlen: + gate0 = gate_scale(cfg, gate0) + else: + gate0 = cutlass.Float32(0.0) + if token_idx1 < batch_seqlen: + gate1 = gate_scale(cfg, gate1) + else: + gate1 = cutlass.Float32(0.0) + pair_vec = nvvm.add_packed_f32x2( + cutlass.Vector.from_elements((prefix_acc, gate0), cutlass.Float32), + cutlass.Vector.from_elements((gate0, gate1), cutlass.Float32), + ftz=False, + rnd="rn", + ) + prefix0, row_pair_sum = cutlass.Float32(pair_vec[0]), cutlass.Float32(pair_vec[1]) + prefix1 = prefix_acc + row_pair_sum + exp_g0 = cute.math.exp2(prefix0, fastmath=True) + exp_g1 = cute.math.exp2(prefix1, fastmath=True) + (sGate_exchange_ptr + prefix_idx0).store(exp_g0) + (sGate_exchange_ptr + prefix_idx1).store(exp_g1) + prefix_acc = prefix1 + exp_g_last = exp_g1 + else: + gate_conditioned = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) + for row in cutlass.range_constexpr(cfg.b_t): + raw_idx = raw_seg_base + swizzle_xor_128b(row, row * 64 + raw_col, elem_bytes=2) + gate_row = (sGate_ptr + raw_idx).load().to(cutlass.Float32) + token_idx = chunk_idx * cutlass.Int32(cfg.b_t) + row + if cutlass.const_expr(cfg.safe_gate): + if token_idx < batch_seqlen: + gate_row = gate_scale(cfg, cg0_a_log_exp * (gate_row + cg0_dt_bias_value)) + else: + gate_row = cutlass.Float32(0.0) else: - gate1 = cutlass.Float32(0.0) - pair_vec = nvvm.add_packed_f32x2( - cutlass.Vector.from_elements((prefix_acc, gate0), cutlass.Float32), - cutlass.Vector.from_elements((gate0, gate1), cutlass.Float32), - ftz=False, - rnd="rn", - ) - prefix0, row_pair_sum = cutlass.Float32(pair_vec[0]), cutlass.Float32(pair_vec[1]) - prefix1 = prefix_acc + row_pair_sum - exp_g0 = cute.math.exp2(prefix0, fastmath=True) - exp_g1 = cute.math.exp2(prefix1, fastmath=True) - (sGate_ptr + prefix_idx0).store(exp_g0) - (sGate_ptr + prefix_idx1).store(exp_g1) - prefix_acc = prefix1 - exp_g_last = exp_g1 + if token_idx < batch_seqlen: + gate_row = gate_scale(cfg, gate_row) + else: + gate_row = cutlass.Float32(0.0) + gate_conditioned[row] = gate_row + nvvm.barrier_cta_sync(cfg.cg0_sync_barrier_id, thread_count=cfg.cg0_threads) + for row_pair in cutlass.range_constexpr(cfg.b_t // 2): + row0 = row_pair * 2 + row1 = row0 + 1 + prefix_idx0 = f32_segment * (cfg.b_t * 32) + row0 * 32 + swizzle_xor_128b(row0, f32_segment_dim, elem_bytes=4) + prefix_idx1 = f32_segment * (cfg.b_t * 32) + row1 * 32 + swizzle_xor_128b(row1, f32_segment_dim, elem_bytes=4) + gate0 = gate_conditioned[row0] + gate1 = gate_conditioned[row1] + pair_vec = nvvm.add_packed_f32x2( + cutlass.Vector.from_elements((prefix_acc, gate0), cutlass.Float32), + cutlass.Vector.from_elements((gate0, gate1), cutlass.Float32), + ftz=False, + rnd="rn", + ) + prefix0, row_pair_sum = cutlass.Float32(pair_vec[0]), cutlass.Float32(pair_vec[1]) + prefix1 = prefix_acc + row_pair_sum + exp_g0 = cute.math.exp2(prefix0, fastmath=True) + exp_g1 = cute.math.exp2(prefix1, fastmath=True) + (sGate_exchange_ptr + prefix_idx0).store(exp_g0) + (sGate_exchange_ptr + prefix_idx1).store(exp_g1) + prefix_acc = prefix1 + exp_g_last = exp_g1 # ---- decay-slot guard ---------------------------------------------------- operand_done_phase = ((gc // cfg.smem_decay_stages) + 1) % 2 bars.mb_decay_done[decay_stage].wait(operand_done_phase) @@ -2200,14 +2254,15 @@ def compute1_warp_group( bars.mb_dstate_smem_cg2_done.wait(dstate_smem_done_index.phase) dstate_smem_done_index = advance(dstate_smem_done_index, 1) row_lo_addr = tmem_row << 16 + seed_vw = 16 // (mDstate_in.element_type.width // 8) dstate_src = (mDstate_in.iterator + mDstate_in.layout((batch_idx, head_idx, value_dim, 0))).raw_ptr() for i in cutlass.range_constexpr(cfg.d_k // 16): seed_block = cutlass.Array(cutlass.Float32, 16, alignment=16) - for g in cutlass.range_constexpr(4): - seed_chunk = (dstate_src + i * 16 + g * 4).load(count=4, alignment=16) - for t in cutlass.range_constexpr(4): + for g in cutlass.range_constexpr(16 // seed_vw): + seed_chunk = (dstate_src + i * 16 + g * seed_vw).load(count=seed_vw, alignment=16) + for t in cutlass.range_constexpr(seed_vw): dval = seed_chunk[t].to(cutlass.Float32) - seed_block[g * 4 + t] = dval if seed_true else cutlass.Float32(0.0) + seed_block[g * seed_vw + t] = dval if seed_true else cutlass.Float32(0.0) nvvm.tcgen05_st( "32x32b", nvvm.make_tmem_ptr(row_lo_addr + (tmem_col + cfg.tmem_dstate_acc_offset + i * 16), cutlass.Float32), @@ -2544,14 +2599,18 @@ def compute1_warp_group( if sk_nt > 0: if write_start == 0: row_lo_addr = tmem_row << 16 + dstate0_vw = 16 // (mDstate0.element_type.width // 8) dstate0_dst = (mDstate0.iterator + mDstate0.layout((batch_idx, head_idx, value_dim, 0))).raw_ptr() for i in cutlass.range_constexpr(cfg.d_k // 32): dstate0_vec = nvvm.tcgen05_ld( "32x32b", nvvm.make_tmem_ptr(row_lo_addr + (tmem_col + cfg.tmem_dstate_acc_offset + i * 32), cutlass.Float32), num=32 ) - for g in cutlass.range_constexpr(8): - (dstate0_dst + i * 32 + g * 4).store( - cutlass.Vector.from_elements(tuple(dstate0_vec[g * 4 + t] for t in range(4)), cutlass.Float32), + for g in cutlass.range_constexpr(32 // dstate0_vw): + (dstate0_dst + i * 32 + g * dstate0_vw).store( + cutlass.Vector.from_elements( + tuple(dstate0_vec[g * dstate0_vw + t].to(mDstate0.element_type) for t in range(dstate0_vw)), + mDstate0.element_type, + ), alignment=16, ) else: @@ -2561,7 +2620,7 @@ def compute1_warp_group( if cutlass.const_expr(cfg.use_dstate_in): mDstate0[batch_idx, head_idx, value_dim, kd] = mDstate_in[batch_idx, head_idx, value_dim, kd] else: - mDstate0[batch_idx, head_idx, value_dim, kd] = cutlass.Float32(0.0) + mDstate0[batch_idx, head_idx, value_dim, kd] = cutlass.Float32(0.0).to(mDstate0.element_type) if sk_nt > 0: bars.mb_dstate0_acc_stored.arrive() gbase += sk_nt @@ -2640,7 +2699,7 @@ def compute2_warp_group( if cutlass.const_expr(cfg.use_dstate_in): has_dstate = cutlass.Boolean(True) sBetaP_ptr = sBeta_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) - sGate_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) + sGate_exchange_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) writes = chunk_idx < write_end bars.mb_k_decay_inv_ready[decay_stage].wait((gc // cfg.smem_decay_stages) % 2) @@ -2652,7 +2711,7 @@ def compute2_warp_group( f16_dim = channel - f16_seg * 64 eg = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) for t in cutlass.range_constexpr(cfg.b_t): - eg[t] = (sGate_ptr + f32_seg * (cfg.b_t * 32) + t * 32 + swizzle_xor_128b(t, f32_dim, elem_bytes=4)).load() + eg[t] = (sGate_exchange_ptr + f32_seg * (cfg.b_t * 32) + t * 32 + swizzle_xor_128b(t, f32_dim, elem_bytes=4)).load() egl = eg[cfg.b_t - 1] nvvm.fence_proxy("async.shared", space="cta") bars.mb_gate_done[raw_stage].arrive() @@ -2871,11 +2930,20 @@ def compute2_warp_group( bars.mb_dgate_tmastg_done[dgate_stage].wait(((gc // cfg.smem_dgate_stages) + 1) % 2) db_stage = gc % cfg.smem_db_stages bars.mb_db_tmastg_done[db_stage].wait(((gc // cfg.smem_db_stages) + 1) % 2) + dgate_base = dgate_stage * (cfg.b_t * cfg.d_k) + db_base = db_stage * (cfg.b_t * cfg.d_k) + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + dgate_seg = channel // 64 + dgate_dim = channel - dgate_seg * 64 for t in cutlass.range_constexpr(cfg.b_t): - dgate_idx = f32_seg * (cfg.b_t * 32) + t * 32 + swizzle_xor_128b(t, f32_dim, elem_bytes=4) - (sDgate_raw.data_ptr() + dgate_idx).store(dgate_regs[t]) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + dgate_idx = f32_seg * (cfg.b_t * 32) + t * 32 + swizzle_xor_128b(t, f32_dim, elem_bytes=4) + (sDgate_raw.data_ptr() + dgate_base + dgate_idx).store(dgate_regs[t]) + else: + dgate_idx = dgate_seg * (cfg.b_t * 64) + t * 64 + swizzle_xor_128b(t, dgate_dim, elem_bytes=2) + (sDgate_raw.data_ptr() + dgate_base + dgate_idx).store(dgate_regs[t].to(cfg.gate_dtype)) db_idx = f16_seg * (cfg.b_t * 64) + t * 64 + swizzle_xor_128b(t, f16_dim, elem_bytes=2) - (sDb_raw.data_ptr() + db_idx).store(db_regs[t].to(cfg.io_dtype)) + (sDb_raw.data_ptr() + db_base + db_idx).store(db_regs[t].to(cfg.io_dtype)) nvvm.fence_proxy("async.shared", space="cta") bars.mb_dgate_tmastg_ready[dgate_stage].arrive() bars.mb_db_tmastg_ready[db_stage].arrive() @@ -3080,6 +3148,9 @@ def frost_gdn2_bprop_prologue( consumers' scheduler rings via :func:`order_body`; it then builds the per-batch TMA-descriptor arrays via :func:`build_descs_body`, one warp per array (the extra warps only take part in the order phase).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) @@ -3218,14 +3289,17 @@ def prologue( base_q = cuda.create_tensor_map_tiled_from_view(q_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_k = cuda.create_tensor_map_tiled_from_view(k_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_v = cuda.create_tensor_map_tiled_from_view(v_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) - base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(32, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) + gate_granu_elems = 128 // (gate.element_type.width // 8) + base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(gate_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_do = cuda.create_tensor_map_tiled_from_view(do_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_beta = cuda.create_tensor_map_tiled_from_view(beta_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_w = cuda.create_tensor_map_tiled_from_view(w_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_dq = cuda.create_tensor_map_tiled_from_view(dq_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_dk = cuda.create_tensor_map_tiled_from_view(dk_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_dv = cuda.create_tensor_map_tiled_from_view(dv_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) - base_dgate = cuda.create_tensor_map_tiled_from_view(dgate_headed, box_dims=(32, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) + base_dgate = cuda.create_tensor_map_tiled_from_view( + dgate_headed, box_dims=(128 // (dgate.element_type.width // 8), 1, b_t), stride_order=(0, 1, 2), swizzle=swz + ) base_dwo = cuda.create_tensor_map_tiled_from_view(dwo_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_dbo = cuda.create_tensor_map_tiled_from_view(dbo_headed, box_dims=(granule, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) @@ -3293,7 +3367,7 @@ def prologue( cutlass.Int32(dbo.stride[0]), cutlass.Int32(state_checkpoints.stride[0]), cutlass.Int32(b_t), - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) @cute.jit @@ -3342,6 +3416,7 @@ def host( grid=grid_shape, block=(cfg.threads_per_cta, 1, 1), stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -3366,6 +3441,8 @@ def frost_gdn2_bprop( scale: cutlass.Float32, ) -> None: """BT=16 GDN-2 backward kernel (persistent, 16 warps).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx()[0] num_ctas = cute.arch.grid_dim()[0] @@ -3374,7 +3451,7 @@ def frost_gdn2_bprop( total_tiles = mCount[0] assert cu_seqlens.element_type in (cutlass.Int32, cutlass.Int64) - assert mDgate.element_type == cutlass.Float32 + assert mDgate.element_type == cfg.gate_dtype assert mDb.element_type == cfg.io_dtype and mDw_out.element_type == cfg.io_dtype desc_base_words = tensormap_workspace.iterator.raw_ptr() @@ -3423,13 +3500,17 @@ def frost_gdn2_bprop( sK_raw = cutlass.Array(cfg.io_dtype, cfg.raw_qk_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sV_raw = cutlass.Array(cfg.io_dtype, cfg.raw_v_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sGate_raw = cutlass.Array(cutlass.Float32, cfg.raw_gate_cosize, space=SMEM, alignment=1024) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + sGate_load_ptr = sGate_raw.data_ptr() + else: + sGate_load_ptr = cute.make_ptr(cfg.gate_dtype, sGate_raw.data_ptr().toint(), mem_space=SMEM, assumed_align=1024) sW_raw = cutlass.Array(cfg.io_dtype, cfg.raw_v_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sU_raw = cutlass.Array(cfg.io_dtype, cfg.b_t * cfg.d_v, space=SMEM, alignment=cfg.buffer_align_bytes) sDy_raw = cutlass.Array(cfg.io_dtype, cfg.b_t * cfg.d_v, space=SMEM, alignment=cfg.buffer_align_bytes) sDq_raw = cutlass.Array(cfg.io_dtype, cfg.dq_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sDk_raw = cutlass.Array(cfg.io_dtype, cfg.dk_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sDv_raw = cutlass.Array(cfg.io_dtype, cfg.dv_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) - sDgate_raw = cutlass.Array(cutlass.Float32, cfg.dgate_cosize, space=SMEM, alignment=1024) + sDgate_raw = cutlass.Array(cfg.gate_dtype, cfg.dgate_cosize, space=SMEM, alignment=1024) sDwOut_raw = cutlass.Array(cfg.io_dtype, cfg.dwo_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sDb_raw = cutlass.Array(cfg.io_dtype, cfg.db_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) @@ -3548,7 +3629,7 @@ def frost_gdn2_bprop( ) q_tx_bytes = cutlass.const_expr(cfg.d_k * cfg.b_t * bpe) k_tx_bytes = cutlass.const_expr(cfg.d_k * cfg.b_t * bpe) - gate_tx_bytes = cutlass.const_expr(cfg.d_k * cfg.b_t * 4) + gate_tx_bytes = cutlass.const_expr(cfg.d_k * cfg.b_t * (cfg.gate_dtype.width // 8)) beta_tx_bytes = cutlass.const_expr(cfg.d_k * cfg.b_t * bpe) do_tx_bytes = cutlass.const_expr(cfg.d_v * cfg.b_t * bpe) v_tx_bytes = cutlass.const_expr(cfg.d_v * cfg.b_t * bpe) @@ -3779,6 +3860,7 @@ def frost_gdn2_bprop( mDt_bias, sK_inv_raw, sGate_raw, + sGate_load_ptr, sK_raw, sQ_raw, sState_raw, @@ -3851,6 +3933,7 @@ class Gdn2BwdCfg: and SMEM buffer cosizes are stamped by ``build_cfg``).""" io_dtype: Type[cutlass.Numeric] + gate_dtype: Type[cutlass.Numeric] use_dstate_in: bool use_dstate0: bool l2norm: bool @@ -3931,6 +4014,7 @@ class Gdn2BwdCfg: raw_qk_cosize: int = 0 raw_v_cosize: int = 0 raw_gate_cosize: int = 0 + gate_stage_elems: int = 0 operand_cosize: int = 0 diag_cosize: int = 0 intermediate_cosize: int = 0 @@ -3946,6 +4030,7 @@ class Gdn2BwdCfg: def build_cfg( io_dtype: Type[cutlass.Numeric], + gate_dtype: Type[cutlass.Numeric], *, use_dstate_in: bool, use_dstate0: bool, @@ -3968,6 +4053,7 @@ def build_cfg( raise ValueError("beta_guard requires l2norm (the sensor is defined on the normalized key)") cfg = Gdn2BwdCfg( io_dtype=io_dtype, + gate_dtype=gate_dtype, use_dstate_in=use_dstate_in, use_dstate0=use_dstate0, l2norm=l2norm, @@ -4012,6 +4098,7 @@ def build_cfg( cfg.raw_qk_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t cfg.raw_v_cosize = cfg.smem_raw_stages * cfg.d_v * cfg.b_t cfg.raw_gate_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t + cfg.gate_stage_elems = (cfg.d_k * cfg.b_t) * (4 // (cfg.gate_dtype.width // 8)) cfg.operand_cosize = cfg.smem_decay_stages * cfg.b_t * cfg.d_k cfg.diag_cosize = cfg.smem_decay_stages * (cfg.d_k // 16) * 256 cfg.intermediate_cosize = cfg.smem_intermediate_stages * cfg.intermediate_tiles * cfg.b_t * cfg.b_t @@ -4036,6 +4123,9 @@ def build_cfg( @lru_cache(maxsize=None) def get_compiled_cache( io_dtype_str: str, + dstate_in_dtype_str: str, + dstate0_dtype_str: str, + gate_dtype_str: str, cu_dtype_str: str, HQ: int, HK: int, @@ -4101,7 +4191,8 @@ def chunk_gdn2_bwd_sm100( q: ``(total_tokens, HQ, DK)`` float16/bfloat16 k: ``(total_tokens, HK, DK)`` float16/bfloat16 v: ``(total_tokens, HV, DV)`` float16/bfloat16 - gate: ``(total_tokens, HO, DK)`` fp32 per-channel decay. Natural-log + gate: ``(total_tokens, HO, DK)`` float32/bfloat16/float16 (16-bit is widened to fp32 on the SMEM read). + Per-channel decay, natural-log unless ``safe_gate``, which applies the safe-gate transform ``lower_bound * sigmoid(exp(a_log) * (gate + dt_bias))`` beta: ``(total_tokens, HO, DK)`` io dtype per-key erase. Post-sigmoid, @@ -4122,8 +4213,9 @@ def chunk_gdn2_bwd_sm100( scale: attention scale factor use_initial_state: the forward ran with an initial state, so chunk 0 has an entering state to load from ``state_checkpoints`` row 0 - d_initial_state: fp32 ``(num_seqs, HO, DV, DK)`` OUT (dL/dS0), or None - d_final_state: fp32 ``(num_seqs, HO, DV, DK)`` IN (dL/d final state) + d_initial_state: ``(num_seqs, HO, DV, DK)`` float32/bfloat16 OUT (dL/dS0), or None + d_final_state: ``(num_seqs, HO, DV, DK)`` float32/bfloat16 IN (dL/d final state); both state + gradients carry the same dtype use_qk_l2norm_in_kernel: q/k arrive raw; the kernel normalizes for the recompute math and chains the L2-norm backward into dq/dk safe_gate: interpret ``gate`` through the safe-gate transform @@ -4172,6 +4264,9 @@ def chunk_gdn2_bwd_sm100( cu_stream = cuda_driver.CUstream(int(stream)) cache = get_compiled_cache( str(q.dtype), + str(d_final_state.dtype) if d_final_state is not None else "none", + str(d_initial_state.dtype) if d_initial_state is not None else "none", + str(gate.dtype), str(cu_seqlens.dtype), HQ, HK, @@ -4192,8 +4287,10 @@ def chunk_gdn2_bwd_sm100( if "compiled" not in cache: io_dtype = get_dtype(q.dtype) + gate_dtype = get_dtype(gate.dtype) cfg = build_cfg( io_dtype, + gate_dtype, use_dstate_in=use_dstate_in, use_dstate0=use_dstate0, l2norm=use_qk_l2norm_in_kernel, diff --git a/python/cudnn/linear_attention/frost/kernel/gdn2_prefill_f16.py b/python/cudnn/linear_attention/frost/kernel/gdn2_prefill_f16.py index 24d12537f0..5bb6682934 100644 --- a/python/cudnn/linear_attention/frost/kernel/gdn2_prefill_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/gdn2_prefill_f16.py @@ -35,6 +35,8 @@ from .gdn2_prefill_config import CFG from cudnn.frost.tile_dsl.barrier import ( + launch_dependent_grids, + wait_on_dependent_grids, advance, MBarrier, PipelineState, @@ -57,6 +59,8 @@ sub_f16x2, ) +USE_PDL = True + LOG2_E: float = 1.4426950408889634 DEFAULT_GATE_LOWER_BOUND: float = -5.0 L2_NORM_EPS: float = 1.0e-12 @@ -293,6 +297,7 @@ def tmaldg_warp( tma_granu_elems=64, tma_subtile_stride_elems=(cfg.b_t * 64), ) + gate_granu = cutlass.const_expr(128 // (cfg.gate_dtype.width // 8)) sGate_tma = SmemTile( base=sGate_raw, elems_per_stage=(cfg.d_k * cfg.b_t), @@ -300,8 +305,8 @@ def tmaldg_warp( leading_byte_offset=0, stride_byte_offset=0, layout=0, - tma_loads_per_tile=(cfg.d_k // 32), - tma_granu_elems=32, + tma_loads_per_tile=(cfg.d_k // gate_granu), + tma_granu_elems=gate_granu, tma_subtile_stride_elems=(cfg.b_t * 32), ) tile_idx = cutlass.Int32(bidx) @@ -374,6 +379,8 @@ def tmaldg_warp( raw_index = advance(raw_index, cfg.smem_raw_stages) raw_bar_index = advance(raw_bar_index, cfg.smem_raw_bar_stages) tile_idx, scheduler_state = scheduler_publish_next(cfg, bars, sScheduler, mScheduler, scheduler_state, tile_idx, num_ctas, elect_one) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -1064,6 +1071,7 @@ def compute0_warp_group( sK_inv_raw, sBeta_raw, sGate_raw, + sGate_load_ptr, sK_raw, sQ_raw, sV_raw, @@ -1119,7 +1127,8 @@ def compute0_warp_group( sQ_ptr = sQ_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sK_ptr = sK_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sV_ptr = sV_raw.data_ptr() + raw_stage * (cfg.d_v * cfg.b_t) - sGate_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) + sGate_ptr = sGate_load_ptr + raw_stage * cfg.gate_stage_elems + sGate_exchange_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sBeta_ptr = sBeta_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sW_ptr = sW_raw.data_ptr() + raw_stage * (cfg.d_v * cfg.b_t) sK_inv_ptr = sK_inv_raw.data_ptr() + decay_stage * (cfg.b_t * cfg.d_k) @@ -1141,11 +1150,19 @@ def compute0_warp_group( f32_segment = channel_dim // 32 prefix_seg_base = f32_segment * (cfg.b_t * 32) prefix_col = channel_dim - f32_segment * 32 + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + raw_segment = channel_dim // 64 + raw_seg_base = raw_segment * (cfg.b_t * 64) + raw_col = channel_dim - raw_segment * 64 g_prefix_regs = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) if cutlass.const_expr(cfg.safe_gate): for row in cutlass.range_constexpr(cfg.b_t): - prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - gate = (sGate_ptr + prefix_idx).load() + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) + gate = (sGate_ptr + prefix_idx).load() + else: + raw_idx = raw_seg_base + swizzle_xor_128b(row, row * 64 + raw_col, elem_bytes=2) + gate = (sGate_ptr + raw_idx).load().to(cutlass.Float32) token_idx = chunk_idx * cutlass.Int32(cfg.b_t) + cutlass.Int32(row) if token_idx < batch_seqlen: gate = gate_scale( @@ -1157,8 +1174,12 @@ def compute0_warp_group( g_prefix_regs[row] = gate else: for row in cutlass.range_constexpr(cfg.b_t): - prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - gate = (sGate_ptr + prefix_idx).load() + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) + gate = (sGate_ptr + prefix_idx).load() + else: + raw_idx = raw_seg_base + swizzle_xor_128b(row, row * 64 + raw_col, elem_bytes=2) + gate = (sGate_ptr + raw_idx).load().to(cutlass.Float32) token_idx = chunk_idx * cutlass.Int32(cfg.b_t) + cutlass.Int32(row) if token_idx < batch_seqlen: gate = gate_scale( @@ -1186,9 +1207,11 @@ def compute0_warp_group( g_prefix_regs[row] = cute.math.exp2(g_prefix_regs[row], fastmath=True) exp_g_last = g_prefix_regs[cfg.b_t - 1] + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + nvvm.barrier_cta_sync(cfg.cg0_group_sync_barrier_base_id + cg0_group_id, thread_count=cfg.cg0_threads_per_group) for row in cutlass.range_constexpr(cfg.b_t): prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - (sGate_ptr + prefix_idx).store(g_prefix_regs[row]) + (sGate_exchange_ptr + prefix_idx).store(g_prefix_regs[row]) # ---- state-scale diag: stage exp2(g last) decay blocks ------------------- bars.mb_state_scale_diag_done[state_scale_diag_stage].wait(diag_ring_phase ^ cutlass.Int32(1)) @@ -1258,7 +1281,7 @@ def compute0_warp_group( # ---- beta guard ---------------------------------------------------------- if cutlass.const_expr(cfg.beta_guard): - beta_guard(cfg, raw_beta_regs, raw_k_regs, k_inv_norm, sGate_ptr, decay_row, lane_in_row_group) + beta_guard(cfg, raw_beta_regs, raw_k_regs, k_inv_norm, sGate_exchange_ptr, decay_row, lane_in_row_group) # ---- decay/restore operands: exp2(+-g) applied per key channel ----------- exp_g_regs = cutlass.Array(cutlass.Float32, 2 * 8, alignment=16) @@ -1272,11 +1295,11 @@ def compute0_warp_group( f32_segment = f32_dim_base // 32 f32_segment_dim = f32_dim_base - f32_segment * 32 g_prefix_idx = f32_segment * (cfg.b_t * 32) + decay_row * 32 + swizzle_xor_128b(decay_row, f32_segment_dim, elem_bytes=4) - exp_g_frag = (sGate_ptr + g_prefix_idx).load(count=4, alignment=16) + exp_g_frag = (sGate_exchange_ptr + g_prefix_idx).load(count=4, alignment=16) f32_segment = f32_dim_base // 32 f32_segment_dim = f32_dim_base - f32_segment * 32 exp_g_last_idx = f32_segment * (cfg.b_t * 32) + (cfg.b_t - 1) * 32 + swizzle_xor_128b((cfg.b_t - 1), f32_segment_dim, elem_bytes=4) - exp_g_last_frag = (sGate_ptr + exp_g_last_idx).load(count=4, alignment=16) + exp_g_last_frag = (sGate_exchange_ptr + exp_g_last_idx).load(count=4, alignment=16) half_reg_base = f32_group * 4 f32_reg_base = reg_base + half_reg_base exp_g_regs[f32_reg_base] = exp_g_frag[0] @@ -2002,6 +2025,7 @@ def host( grid=grid_shape, block=(cfg.threads_per_cta, 1, 1), stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -2036,6 +2060,8 @@ def frost_gdn2_prefill( one split-K work item — iterating its chunks in order. Source heads follow repeat_interleave: head_x = head_idx // X_RATIO. """ + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx()[0] @@ -2047,7 +2073,7 @@ def frost_gdn2_prefill( if cutlass.const_expr(cfg.dynamic_scheduling): assert mScheduler is not None and mScheduler.element_type == cutlass.Int32 assert mQ.element_type == cfg.io_dtype and mK.element_type == cfg.io_dtype and mV.element_type == cfg.io_dtype - assert mGate.element_type == cutlass.Float32 + assert mGate.element_type == cfg.gate_dtype assert mBeta.element_type == cfg.io_dtype and mW.element_type == cfg.io_dtype, "channel-wise beta/w must match the io dtype" assert cu_seqlens.element_type in (cutlass.Int32, cutlass.Int64) if cutlass.const_expr(cfg.use_initial_state): @@ -2084,6 +2110,10 @@ def frost_gdn2_prefill( sK_raw = cutlass.Array(mK.element_type, cfg.k_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sV_raw = cutlass.Array(mV.element_type, cfg.v_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sGate_raw = cutlass.Array(cutlass.Float32, cfg.gate_cosize, space=SMEM, alignment=1024) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + sGate_load_ptr = sGate_raw.data_ptr() + else: + sGate_load_ptr = cute.make_ptr(cfg.gate_dtype, sGate_raw.data_ptr().toint(), mem_space=SMEM, assumed_align=1024) sState_scale_diag_raw = cutlass.Array(cfg.io_dtype, cfg.state_scale_diag_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sK_inv_raw = cutlass.Array(cfg.io_dtype, cfg.k_inv_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sO_raw = cutlass.Array( @@ -2297,6 +2327,7 @@ def frost_gdn2_prefill( sK_inv_raw, sBeta_raw, sGate_raw, + sGate_load_ptr, sK_raw, sQ_raw, sV_raw, @@ -2341,6 +2372,7 @@ class Gdn2Cfg: io_dtype: Type[cutlass.Numeric] state_dtype: Type[cutlass.Numeric] + gate_dtype: Type[cutlass.Numeric] use_initial_state: bool store_final_state: bool enable_checkpoints: bool @@ -2405,6 +2437,7 @@ class Gdn2Cfg: k_cosize: int = 0 v_cosize: int = 0 gate_cosize: int = 0 + gate_stage_elems: int = 0 beta_cosize: int = 0 w_cosize: int = 0 k_inv_cosize: int = 0 @@ -2427,6 +2460,7 @@ class Gdn2Cfg: def build_cfg( io_dtype: Type[cutlass.Numeric], state_dtype: Type[cutlass.Numeric], + gate_dtype: Type[cutlass.Numeric], *, use_initial_state: bool, store_final_state: bool, @@ -2452,6 +2486,7 @@ def build_cfg( cfg = Gdn2Cfg( io_dtype=io_dtype, state_dtype=state_dtype, + gate_dtype=gate_dtype, use_initial_state=use_initial_state, store_final_state=store_final_state, enable_checkpoints=enable_checkpoints, @@ -2489,6 +2524,7 @@ def build_cfg( cfg.k_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t cfg.v_cosize = cfg.smem_raw_stages * cfg.d_v * cfg.b_t cfg.gate_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t + cfg.gate_stage_elems = (cfg.d_k * cfg.b_t) * (4 // (cfg.gate_dtype.width // 8)) cfg.beta_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t cfg.w_cosize = cfg.smem_raw_stages * cfg.d_v * cfg.b_t cfg.k_inv_cosize = cfg.smem_decay_stages * cfg.b_t * cfg.d_k @@ -2500,7 +2536,7 @@ def build_cfg( cfg.intermediate_cosize = cfg.smem_intermediate_stages * 2 * cfg.b_t * cfg.b_t cfg.tma_q_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_k_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) - cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * 4 + cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * (cfg.gate_dtype.width // 8) cfg.tma_beta_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_v_bytes = cfg.d_v * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_w_bytes = cfg.d_v * cfg.b_t * (cfg.io_dtype.width // 8) @@ -2636,6 +2672,9 @@ def frost_gdn2_prefill_prologue( rings via :func:`order_body`, then build the per-batch TMA-descriptor arrays via :func:`build_descs_body`, one warp per array (the extra warps only take part in the order phase).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) @@ -2754,7 +2793,8 @@ def prologue( base_q = cuda.create_tensor_map_tiled_from_view(q_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_k = cuda.create_tensor_map_tiled_from_view(k_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_v = cuda.create_tensor_map_tiled_from_view(v_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) - base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(32, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) + gate_granu_elems = 128 // (gate.element_type.width // 8) + base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(gate_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_beta = cuda.create_tensor_map_tiled_from_view(beta_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_w = cuda.create_tensor_map_tiled_from_view(w_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_o = cuda.create_tensor_map_tiled_from_view(o_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) @@ -2805,7 +2845,7 @@ def prologue( cutlass.Int32(o.stride[0]), cutlass.Int32(state_checkpoints.stride[0] if state_checkpoints is not None else 0), checkpoint_every_n, - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) # ---- Torch adapter / host-side compilation ------------------------------------------- @@ -2815,6 +2855,7 @@ def prologue( def get_compiled_cache( io_dtype_str: str, state_dtype_str: str, + gate_dtype_str: str, cu_dtype_str: str, HQ: int, HK: int, @@ -2837,6 +2878,7 @@ def get_compiled_cache( def compile( io_dtype, state_dtype, + gate_dtype, use_initial_state: bool, store_final_state: bool, enable_checkpoints: bool, @@ -2876,6 +2918,7 @@ def compile( cfg = build_cfg( io_dtype, state_dtype, + gate_dtype, use_initial_state=use_initial_state, store_final_state=store_final_state, enable_checkpoints=enable_checkpoints, @@ -2957,7 +3000,8 @@ def chunk_gdn2_sm100( q: ``(total_tokens, HQ, DK)`` float16/bfloat16 k: ``(total_tokens, HK, DK)`` float16/bfloat16 v: ``(total_tokens, HV, DV)`` float16/bfloat16 - gate: ``(total_tokens, HO, DK)`` float32. Natural-log decay unless + gate: ``(total_tokens, HO, DK)`` float32/bfloat16/float16 (16-bit is widened to fp32 on the SMEM read). + Natural-log decay unless ``safe_gate``, which applies the safe-gate transform ``lower_bound * sigmoid(exp(a_log) * (gate + dt_bias))``. beta: ``(total_tokens, HO, DK)`` io dtype, channel-wise erase gate. @@ -3033,6 +3077,7 @@ def chunk_gdn2_sm100( cache = get_compiled_cache( str(q.dtype), str(state_dtype_src), + str(gate.dtype), str(cu_seqlens.dtype), HQ, HK, @@ -3052,6 +3097,7 @@ def chunk_gdn2_sm100( if "compiled" not in cache: io_dtype = get_dtype(q.dtype) state_dtype = get_dtype(state_dtype_src) + gate_dtype = get_dtype(gate.dtype) q_cute = from_dlpack(q, assumed_align=16).mark_layout_dynamic(leading_dim=2) k_cute = from_dlpack(k, assumed_align=16).mark_layout_dynamic(leading_dim=2) v_cute = from_dlpack(v, assumed_align=16).mark_layout_dynamic(leading_dim=2) @@ -3084,6 +3130,7 @@ def chunk_gdn2_sm100( cache["compiled"] = compile( io_dtype, state_dtype, + gate_dtype, use_initial_state, store_final_state, enable_checkpoints, diff --git a/python/cudnn/linear_attention/frost/kernel/gdn2_recompute_f16.py b/python/cudnn/linear_attention/frost/kernel/gdn2_recompute_f16.py index 2748e5bad7..ab88dc424a 100644 --- a/python/cudnn/linear_attention/frost/kernel/gdn2_recompute_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/gdn2_recompute_f16.py @@ -35,6 +35,8 @@ from .gdn2_recompute_config import CFG from cudnn.frost.tile_dsl.barrier import ( + launch_dependent_grids, + wait_on_dependent_grids, advance, MBarrier, PipelineState, @@ -57,6 +59,8 @@ sub_f16x2, ) +USE_PDL = True + LOG2_E: float = 1.4426950408889634 DEFAULT_GATE_LOWER_BOUND: float = -5.0 L2_NORM_EPS: float = 1.0e-12 @@ -274,6 +278,7 @@ def tmaldg_warp( tma_granu_elems=64, tma_subtile_stride_elems=(cfg.b_t * 64), ) + gate_granu = cutlass.const_expr(128 // (cfg.gate_dtype.width // 8)) sGate_tma = SmemTile( base=sGate_raw, elems_per_stage=(cfg.d_k * cfg.b_t), @@ -281,8 +286,8 @@ def tmaldg_warp( leading_byte_offset=0, stride_byte_offset=0, layout=0, - tma_loads_per_tile=(cfg.d_k // 32), - tma_granu_elems=32, + tma_loads_per_tile=(cfg.d_k // gate_granu), + tma_granu_elems=gate_granu, tma_subtile_stride_elems=(cfg.b_t * 32), ) tile_idx = cutlass.Int32(bidx) @@ -345,6 +350,8 @@ def tmaldg_warp( raw_index = advance(raw_index, cfg.smem_raw_stages) raw_bar_index = advance(raw_bar_index, cfg.smem_raw_bar_stages) tile_idx, scheduler_state = scheduler_publish_next(cfg, bars, sScheduler, mScheduler, scheduler_state, tile_idx, num_ctas, elect_one) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -847,6 +854,7 @@ def compute0_warp_group( sK_inv_raw, sBeta_raw, sGate_raw, + sGate_load_ptr, sK_raw, sV_raw, sW_raw, @@ -899,7 +907,8 @@ def compute0_warp_group( qk_scale_ready_stage = state_scale_diag_stage sK_ptr = sK_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sV_ptr = sV_raw.data_ptr() + raw_stage * (cfg.d_v * cfg.b_t) - sGate_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) + sGate_ptr = sGate_load_ptr + raw_stage * cfg.gate_stage_elems + sGate_exchange_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sBeta_ptr = sBeta_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sW_ptr = sW_raw.data_ptr() + raw_stage * (cfg.d_v * cfg.b_t) sK_inv_ptr = sK_inv_raw.data_ptr() + decay_stage * (cfg.b_t * cfg.d_k) @@ -920,11 +929,19 @@ def compute0_warp_group( f32_segment = channel_dim // 32 prefix_seg_base = f32_segment * (cfg.b_t * 32) prefix_col = channel_dim - f32_segment * 32 + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + raw_segment = channel_dim // 64 + raw_seg_base = raw_segment * (cfg.b_t * 64) + raw_col = channel_dim - raw_segment * 64 g_prefix_regs = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) if cutlass.const_expr(cfg.safe_gate): for row in cutlass.range_constexpr(cfg.b_t): - prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - gate = (sGate_ptr + prefix_idx).load() + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) + gate = (sGate_ptr + prefix_idx).load() + else: + raw_idx = raw_seg_base + swizzle_xor_128b(row, row * 64 + raw_col, elem_bytes=2) + gate = (sGate_ptr + raw_idx).load().to(cutlass.Float32) token_idx = chunk_idx * cutlass.Int32(cfg.b_t) + cutlass.Int32(row) if token_idx < batch_seqlen: gate = gate_scale( @@ -936,8 +953,12 @@ def compute0_warp_group( g_prefix_regs[row] = gate else: for row in cutlass.range_constexpr(cfg.b_t): - prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - gate = (sGate_ptr + prefix_idx).load() + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) + gate = (sGate_ptr + prefix_idx).load() + else: + raw_idx = raw_seg_base + swizzle_xor_128b(row, row * 64 + raw_col, elem_bytes=2) + gate = (sGate_ptr + raw_idx).load().to(cutlass.Float32) token_idx = chunk_idx * cutlass.Int32(cfg.b_t) + cutlass.Int32(row) if token_idx < batch_seqlen: gate = gate_scale( @@ -965,9 +986,11 @@ def compute0_warp_group( g_prefix_regs[row] = cute.math.exp2(g_prefix_regs[row], fastmath=True) exp_g_last = g_prefix_regs[cfg.b_t - 1] + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + nvvm.barrier_cta_sync(cfg.cg0_group_sync_barrier_base_id + cg0_group_id, thread_count=cfg.cg0_threads_per_group) for row in cutlass.range_constexpr(cfg.b_t): prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - (sGate_ptr + prefix_idx).store(g_prefix_regs[row]) + (sGate_exchange_ptr + prefix_idx).store(g_prefix_regs[row]) # ---- state-scale diag: stage exp2(g last) decay blocks ------------------- bars.mb_state_scale_diag_done[state_scale_diag_stage].wait(diag_phase ^ cutlass.Int32(1)) @@ -1021,7 +1044,7 @@ def compute0_warp_group( # ---- beta guard ---------------------------------------------------------- if cutlass.const_expr(cfg.beta_guard): - beta_guard(cfg, raw_beta_regs, raw_k_regs, k_inv_norm, sGate_ptr, decay_row, lane_in_row_group) + beta_guard(cfg, raw_beta_regs, raw_k_regs, k_inv_norm, sGate_exchange_ptr, decay_row, lane_in_row_group) # ---- decay/restore operands: exp2(+-g) applied per key channel ----------- exp_g_regs = cutlass.Array(cutlass.Float32, 2 * 8, alignment=16) @@ -1035,11 +1058,11 @@ def compute0_warp_group( f32_segment = f32_dim_base // 32 f32_segment_dim = f32_dim_base - f32_segment * 32 g_prefix_idx = f32_segment * (cfg.b_t * 32) + decay_row * 32 + swizzle_xor_128b(decay_row, f32_segment_dim, elem_bytes=4) - exp_g_frag = (sGate_ptr + g_prefix_idx).load(count=4, alignment=16) + exp_g_frag = (sGate_exchange_ptr + g_prefix_idx).load(count=4, alignment=16) f32_segment = f32_dim_base // 32 f32_segment_dim = f32_dim_base - f32_segment * 32 exp_g_last_idx = f32_segment * (cfg.b_t * 32) + (cfg.b_t - 1) * 32 + swizzle_xor_128b((cfg.b_t - 1), f32_segment_dim, elem_bytes=4) - exp_g_last_frag = (sGate_ptr + exp_g_last_idx).load(count=4, alignment=16) + exp_g_last_frag = (sGate_exchange_ptr + exp_g_last_idx).load(count=4, alignment=16) half_reg_base = f32_group * 4 f32_reg_base = reg_base + half_reg_base exp_g_regs[f32_reg_base] = exp_g_frag[0] @@ -1630,6 +1653,7 @@ def host( grid=grid_shape, block=(cfg.threads_per_cta, 1, 1), stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -1656,6 +1680,8 @@ def frost_gdn2_recompute( ) -> None: """BT=16 GDN-2 recompute device kernel (persistent); grid `(min(tiles, SM count), 1, 1)`.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx()[0] @@ -1667,7 +1693,7 @@ def frost_gdn2_recompute( if cutlass.const_expr(cfg.dynamic_scheduling): assert mScheduler is not None and mScheduler.element_type == cutlass.Int32 assert mK.element_type == cfg.io_dtype and mV.element_type == cfg.io_dtype - assert mGate.element_type == cutlass.Float32 + assert mGate.element_type == cfg.gate_dtype assert mBeta.element_type == cfg.io_dtype and mW.element_type == cfg.io_dtype, "channel-wise beta/w must match the io dtype" assert cu_seqlens.element_type in (cutlass.Int32, cutlass.Int64) if cutlass.const_expr(cfg.use_initial_state): @@ -1700,6 +1726,10 @@ def frost_gdn2_recompute( sK_raw = cutlass.Array(mK.element_type, cfg.k_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sV_raw = cutlass.Array(mV.element_type, cfg.v_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sGate_raw = cutlass.Array(cutlass.Float32, cfg.gate_cosize, space=SMEM, alignment=1024) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + sGate_load_ptr = sGate_raw.data_ptr() + else: + sGate_load_ptr = cute.make_ptr(cfg.gate_dtype, sGate_raw.data_ptr().toint(), mem_space=SMEM, assumed_align=1024) sState_scale_diag_raw = cutlass.Array(cfg.io_dtype, cfg.state_scale_diag_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sK_inv_raw = cutlass.Array(cfg.io_dtype, cfg.k_inv_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sBeta_raw = cutlass.Array(mBeta.element_type, cfg.beta_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) @@ -1879,6 +1909,7 @@ def frost_gdn2_recompute( sK_inv_raw, sBeta_raw, sGate_raw, + sGate_load_ptr, sK_raw, sV_raw, sW_raw, @@ -1918,6 +1949,7 @@ class Gdn2RecomputeCfg: io_dtype: Type[cutlass.Numeric] state_dtype: Type[cutlass.Numeric] + gate_dtype: Type[cutlass.Numeric] use_initial_state: bool store_final_state: bool enable_checkpoints: bool @@ -1977,6 +2009,7 @@ class Gdn2RecomputeCfg: k_cosize: int = 0 v_cosize: int = 0 gate_cosize: int = 0 + gate_stage_elems: int = 0 beta_cosize: int = 0 w_cosize: int = 0 k_inv_cosize: int = 0 @@ -1996,6 +2029,7 @@ class Gdn2RecomputeCfg: def build_cfg( io_dtype: Type[cutlass.Numeric], state_dtype: Type[cutlass.Numeric], + gate_dtype: Type[cutlass.Numeric], *, use_initial_state: bool, store_final_state: bool, @@ -2020,6 +2054,7 @@ def build_cfg( cfg = Gdn2RecomputeCfg( io_dtype=io_dtype, state_dtype=state_dtype, + gate_dtype=gate_dtype, use_initial_state=use_initial_state, store_final_state=store_final_state, enable_checkpoints=enable_checkpoints, @@ -2054,6 +2089,7 @@ def build_cfg( cfg.k_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t cfg.v_cosize = cfg.smem_raw_stages * cfg.d_v * cfg.b_t cfg.gate_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t + cfg.gate_stage_elems = (cfg.d_k * cfg.b_t) * (4 // (cfg.gate_dtype.width // 8)) cfg.beta_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t cfg.w_cosize = cfg.smem_raw_stages * cfg.d_v * cfg.b_t cfg.k_inv_cosize = cfg.smem_decay_stages * cfg.b_t * cfg.d_k @@ -2062,7 +2098,7 @@ def build_cfg( cfg.state_scale_diag_cosize = cfg.smem_state_scale_diag_stages * (cfg.d_k // 16) * 256 cfg.intermediate_cosize = cfg.smem_intermediate_stages * cfg.b_t * cfg.b_t cfg.tma_k_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) - cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * 4 + cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * (cfg.gate_dtype.width // 8) cfg.tma_beta_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_v_bytes = cfg.d_v * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_w_bytes = cfg.d_v * cfg.b_t * (cfg.io_dtype.width // 8) @@ -2175,6 +2211,9 @@ def frost_gdn2_recompute_prologue( consumers' scheduler rings via :func:`order_body`; it then builds the per-batch TMA-descriptor arrays via :func:`build_descs_body`, one warp per array (the extra warps only take part in the order phase).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) @@ -2273,7 +2312,8 @@ def prologue( swz = cuda.TensorMapSwizzle.s128b base_k = cuda.create_tensor_map_tiled_from_view(k_headed, box_dims=(tma_box_elements, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_v = cuda.create_tensor_map_tiled_from_view(v_headed, box_dims=(tma_box_elements, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) - base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(32, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) + gate_granu_elems = 128 // (gate.element_type.width // 8) + base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(gate_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_beta = cuda.create_tensor_map_tiled_from_view(beta_headed, box_dims=(tma_box_elements, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_w = cuda.create_tensor_map_tiled_from_view(w_headed, box_dims=(tma_box_elements, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) @@ -2320,7 +2360,7 @@ def prologue( cutlass.Int32(w.stride[0]), cutlass.Int32(state_checkpoints.stride[0] if state_checkpoints is not None else 0), checkpoint_every_n, - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) # ---- Torch adapter / host-side compilation ------------------------------------------- @@ -2330,6 +2370,7 @@ def prologue( def get_compiled_cache( io_dtype_str: str, state_dtype_str: str, + gate_dtype_str: str, cu_dtype_str: str, HO: int, HK: int, @@ -2354,6 +2395,7 @@ def get_compiled_cache( def compile( io_dtype, state_dtype, + gate_dtype, use_initial_state: bool, store_final_state: bool, enable_checkpoints: bool, @@ -2389,6 +2431,7 @@ def compile( cfg = build_cfg( io_dtype, state_dtype, + gate_dtype, use_initial_state=use_initial_state, store_final_state=store_final_state, enable_checkpoints=enable_checkpoints, @@ -2464,7 +2507,8 @@ def chunk_gdn2_recompute_sm100( Args: k: ``(total_tokens, HK, DK)`` float16/bfloat16 v: ``(total_tokens, HV, DV)`` float16/bfloat16 - gate: ``(total_tokens, HO, DK)`` float32. Natural-log decay unless + gate: ``(total_tokens, HO, DK)`` float32/bfloat16/float16 (16-bit is widened to fp32 on the SMEM read). + Natural-log decay unless ``safe_gate``, which applies the safe-gate transform ``lower_bound * sigmoid(exp(a_log) * (gate + dt_bias))``. beta: ``(total_tokens, HO, DK)`` io dtype, channel-wise erase gate. @@ -2538,6 +2582,7 @@ def chunk_gdn2_recompute_sm100( cache = get_compiled_cache( str(k.dtype), str(state_dtype_src), + str(gate.dtype), str(cu_seqlens.dtype), HO, HK, @@ -2559,6 +2604,7 @@ def chunk_gdn2_recompute_sm100( if "compiled" not in cache: io_dtype = get_dtype(k.dtype) state_dtype = get_dtype(state_dtype_src) + gate_dtype = get_dtype(gate.dtype) k_cute = from_dlpack(k, assumed_align=16).mark_layout_dynamic(leading_dim=2) v_cute = from_dlpack(v, assumed_align=16).mark_layout_dynamic(leading_dim=2) gate_cute = from_dlpack(gate, assumed_align=16).mark_layout_dynamic(leading_dim=2) @@ -2589,6 +2635,7 @@ def chunk_gdn2_recompute_sm100( cache["compiled"] = compile( io_dtype, state_dtype, + gate_dtype, use_initial_state, store_final_state, enable_checkpoints, diff --git a/python/cudnn/linear_attention/frost/kernel/gdn_bprop_f16.py b/python/cudnn/linear_attention/frost/kernel/gdn_bprop_f16.py index 9daa79701f..527408a261 100644 --- a/python/cudnn/linear_attention/frost/kernel/gdn_bprop_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/gdn_bprop_f16.py @@ -128,6 +128,8 @@ Producer, PipelineState, advance, + launch_dependent_grids, + wait_on_dependent_grids, ) from cudnn.frost.tile_dsl.handles import MmaDesc, SmemTile, tma_slice_runtime_desc from cudnn.frost.tile_dsl.mma import mma_ss, mma_step_k8, mma_ts_step, mma_step @@ -142,6 +144,8 @@ ) from .gdn_bprop_config import CFG +USE_PDL = True + class GdnBwdBars(NamedTuple): """Every inter-warp handoff as an ``MBarrier`` over its ring.""" @@ -695,7 +699,7 @@ def gate_beta_warp( # ---- Gate load: GMEM -> SMEM (OOB neutral: 1.0 -> log2 = 0.0) -------- oob_neutral = cutlass.Float32(0.0) if cutlass.const_expr(cfg.log_gate) else cutlass.Float32(1.0) - gate_vals = [gGate[lane_idx + col * cfg.threads_per_warp] if pos_valid[col] else oob_neutral for col in range(n_cols)] + gate_vals = [gGate[lane_idx + col * cfg.threads_per_warp].to(cutlass.Float32) if pos_valid[col] else oob_neutral for col in range(n_cols)] if cutlass.const_expr(cfg.safe_gate): for col in cutlass.range_constexpr(0, n_cols, 2): @@ -739,13 +743,14 @@ def gate_beta_warp( # ---- Beta load: GMEM -> SMEM (per-element cp.async) ------------------ beta_idx = beta_index.idx beta_index = advance(beta_index, cfg.smem_beta_stages) - if cutlass.const_expr(cfg.beta_sigmoid): + if cutlass.const_expr(cfg.beta_sigmoid or mBeta.element_type != cutlass.Float32): for col in cutlass.range_constexpr(n_cols): pos = lane_idx + col * cfg.threads_per_warp beta_value = cutlass.Float32(0.0) if pos_valid[col]: beta_value = gBeta[pos].to(cutlass.Float32) - beta_value = sigmoid(beta_value).to(mBeta.element_type).to(cutlass.Float32) + if cutlass.const_expr(cfg.beta_sigmoid): + beta_value = sigmoid(beta_value).to(mBeta.element_type).to(cutlass.Float32) sBeta[pos, 0, beta_idx] = beta_value bars.mb_beta_ready[beta_idx].arrive() else: @@ -780,7 +785,7 @@ def gate_beta_warp( for col in cutlass.range_constexpr(n_cols): pos = lane_idx + col * cfg.threads_per_warp if st_offset + pos < write_end_token: - gDgate[pos] = dgate_vals[col] + gDgate[pos] = dgate_vals[col].to(mDgate.element_type) # ---- dBeta store ----------------------------------------------------- beta_store_idx = beta_store_index.idx @@ -789,10 +794,7 @@ def gate_beta_warp( for col in cutlass.range_constexpr(n_cols): pos = lane_idx + col * cfg.threads_per_warp if st_offset + pos < write_end_token: - if cutlass.const_expr(cfg.beta_sigmoid): - gDbeta[pos] = sBeta[pos, 0, beta_store_idx].to(mDbeta.element_type) - else: - gDbeta[pos] = sBeta[pos, 0, beta_store_idx] + gDbeta[pos] = sBeta[pos, 0, beta_store_idx].to(mDbeta.element_type) tile_idx, scheduler_state = scheduler_next_tile(cfg, bars, sScheduler, scheduler_state, tile_idx, num_ctas, elect_one) @@ -1751,6 +1753,8 @@ def tmaldg_warp( for _ in range(cfg.smem_do_stages): bars.mb_do_mma_done[do_index.idx].wait(do_index.phase) do_index = advance(do_index, cfg.smem_do_stages) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -2766,7 +2770,7 @@ def compute2_warp_group( for i in cutlass.range_constexpr(num_ldtms): dstate_in_vals = [] for kk in cutlass.range_constexpr(ldtm_width): - v = gDstate_in[cg2_tidx, i * ldtm_width + kk] + v = gDstate_in[cg2_tidx, i * ldtm_width + kk].to(cfg.acc_dtype) v = v if seed_from_dstate_in else cutlass.Float32(0.0) dstate_in_vals.append(v) nvvm.tcgen05_st( @@ -3020,7 +3024,7 @@ def compute2_warp_group( for i in cutlass.range_constexpr(num_ldtms): dstate0_vec = nvvm.tcgen05_ld("32x32b", nvvm.make_tmem_ptr(row_lo_addr + tmem_dstate_acc_col + i * ldtm_width, cutlass.Float32), num=32) for kk in cutlass.range_constexpr(32): - gDstate0[cg2_tidx, i * ldtm_width + kk] = dstate0_vec[kk] + gDstate0[cg2_tidx, i * ldtm_width + kk] = dstate0_vec[kk].to(mDstate0_out.element_type) if cutlass.const_expr(not cfg.use_dstate_in): bars.mb_dstate_scale_acc_done[dstate_idx].arrive() else: @@ -3036,7 +3040,7 @@ def compute2_warp_group( else: for i in cutlass.range_constexpr(num_ldtms): for kk in cutlass.range_constexpr(32): - gDstate0[cg2_tidx, i * ldtm_width + kk] = cutlass.Float32(0.0) + gDstate0[cg2_tidx, i * ldtm_width + kk] = cutlass.Float32(0.0).to(mDstate0_out.element_type) tile_idx, scheduler_state = scheduler_next_tile(cfg, bars, sScheduler, scheduler_state, tile_idx, num_ctas, elect_one) @@ -3172,6 +3176,9 @@ def frost_gdn_bprop_prologue( consumers' sched rings via :func:`order_body`; it then builds the per-batch TMA-descriptor arrays via :func:`build_descs_body`, one warp per array (the extra warps only take part in the order phase).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) @@ -3340,7 +3347,7 @@ def prologue( cutlass.Int32(dq_row_stride), cutlass.Int32(dk_row_stride), cutlass.Int32(dv_row_stride), - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) @cute.jit @@ -3447,6 +3454,7 @@ def host( block=(cfg.threads_per_cta, 1, 1), cluster=cfg.cluster_shape_mnk, stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -3480,6 +3488,8 @@ def frost_gdn_bprop( n_desc: cutlass.Int32, ): """Main GDN bprop chunked kernel (warp-specialized persistent body).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) bidx = cute.arch.block_idx()[0] @@ -4328,6 +4338,10 @@ def build_cfg( def get_compiled_cache( io_dtype_str: str, cu_dtype_str: str, + gate_dtype_str: str, + beta_dtype_str: str, + dstate_in_dtype_str: str, + dstate0_dtype_str: str, HQ: int, HK: int, HV: int, @@ -4469,11 +4483,13 @@ def chunk_gdn_bwd_sm100( reduces over the head group; dGate = dL/d(ln alpha)). With ``use_initial_state``, chunk 0 reads its entering state from ``state_checkpoints`` row 0 like every other chunk (the forward writes the - initial state there); ``d_initial_state`` (fp32) then also receives the - initial-state gradient. The two go together. ``state_checkpoints`` is - always the PLAIN per-chunk checkpoint series. All tensors are DLPack-compatible - CUDA tensors on the same device with a stride-1 innermost dim (outer - strides are runtime arguments). + initial state there); ``d_initial_state`` then also receives the + initial-state gradient. The two go together. Both state gradients carry + the state dtype -- fp32, or bfloat16 when the forward ran with a bfloat16 + ``initial_state``. ``state_checkpoints`` is always the PLAIN per-chunk + checkpoint series. All tensors are DLPack-compatible CUDA tensors on the + same device with a stride-1 innermost dim (outer strides are runtime + arguments). Compile-cache-and-replay. Args: @@ -4543,6 +4559,10 @@ def chunk_gdn_bwd_sm100( cache = get_compiled_cache( str(q.dtype), str(cu_seqlens.dtype), + str(gate.dtype), + str(beta.dtype), + str(d_final_state.dtype) if d_final_state is not None else "none", + str(d_initial_state.dtype) if d_initial_state is not None else "none", HQ, HK, HV, diff --git a/python/cudnn/linear_attention/frost/kernel/gdn_prefill_f16.py b/python/cudnn/linear_attention/frost/kernel/gdn_prefill_f16.py index 05741a8591..e7289b1dda 100644 --- a/python/cudnn/linear_attention/frost/kernel/gdn_prefill_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/gdn_prefill_f16.py @@ -106,6 +106,8 @@ Producer, PipelineState, advance, + launch_dependent_grids, + wait_on_dependent_grids, ) from cudnn.frost.tile_dsl.handles import MmaDesc, SmemTile, tma_slice_runtime_desc from cudnn.frost.tile_dsl.mma import mma_ss, mma_step_k8, mma_ts_step, mma_step @@ -120,6 +122,8 @@ ) from .gdn_prefill_config import CFG +USE_PDL = True + class GdnBars(NamedTuple): """Every inter-warp handoff as an ``MBarrier`` over its ring.""" @@ -590,7 +594,7 @@ def gate_beta_warp( oob_neutral = cutlass.Float32(0.0) if cutlass.const_expr(cfg.log_gate) else cutlass.Float32(1.0) toks = [chunk_offset + lane_idx + col * cfg.threads_per_warp for col in range(n_cols)] pos_valid = [tok < batch_end for tok in toks] - gate_vals = [gGateSeq[min(tok, batch_end - 1)] if valid else oob_neutral for tok, valid in zip(toks, pos_valid)] + gate_vals = [gGateSeq[min(tok, batch_end - 1)].to(cutlass.Float32) if valid else oob_neutral for tok, valid in zip(toks, pos_valid)] if cutlass.const_expr(cfg.safe_gate): for col in cutlass.range_constexpr(0, n_cols, 2): @@ -635,13 +639,14 @@ def gate_beta_warp( beta_idx = beta_index.idx bars.mb_beta_done[beta_idx].wait(beta_index.phase) beta_index = advance(beta_index, cfg.smem_beta_stages) - if cutlass.const_expr(cfg.beta_sigmoid): + if cutlass.const_expr(cfg.beta_sigmoid or mBeta.element_type != cutlass.Float32): for col in cutlass.range_constexpr(n_cols): pos = lane_idx + col * cfg.threads_per_warp beta_value = cutlass.Float32(0.0) if pos_valid[col]: beta_value = gBeta[pos].to(cutlass.Float32) - beta_value = sigmoid(beta_value).to(mBeta.element_type).to(cutlass.Float32) + if cutlass.const_expr(cfg.beta_sigmoid): + beta_value = sigmoid(beta_value).to(mBeta.element_type).to(cutlass.Float32) sBeta[pos, 0, beta_idx] = beta_value bars.mb_beta_ready[beta_idx].arrive() else: @@ -1113,6 +1118,8 @@ def tmaldg_warp( for _ in range(cfg.smem_v_stages): bars.mb_v_done[v_index.idx].wait(v_index.phase) v_index = advance(v_index, cfg.smem_v_stages) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -1945,6 +1952,9 @@ def frost_gdn_prefill_prologue( rings via :func:`order_body`, then build the per-batch TMA-descriptor arrays via :func:`build_descs_body`, one warp per array (the extra warps only take part in the order phase).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) @@ -2089,7 +2099,7 @@ def prologue( cutlass.Int32(o.stride[0] if o is not None else 0), cutlass.Int32(state_checkpoints_out.stride[0] if state_checkpoints_out is not None else 0), checkpoint_every_n, - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) @cute.jit @@ -2276,6 +2286,7 @@ def host( block=(cfg.threads_per_cta, 1, 1), cluster=cfg.cluster_shape_mnk, stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -2305,6 +2316,8 @@ def frost_gdn_prefill( n_desc: cutlass.Int32, ): """Main GDN chunked kernel: warp-specialized persistent tile loop.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) bidx = cute.arch.block_idx()[0] @@ -2765,6 +2778,8 @@ def get_compiled_cache( io_dtype_str: str, state_dtype_str: str, cu_dtype_str: str, + gate_dtype_str: str, + beta_dtype_str: str, HQ: int, HK: int, HV: int, @@ -2965,6 +2980,8 @@ def chunk_gdn_sm100( str(q.dtype), str(state_dtype_src), str(cu_seqlens.dtype), + str(gate.dtype), + str(beta.dtype), HQ, k.shape[1], HV, diff --git a/python/cudnn/linear_attention/frost/kernel/gdn_recompute_f16.py b/python/cudnn/linear_attention/frost/kernel/gdn_recompute_f16.py index 793a73844e..5624a6e8bd 100644 --- a/python/cudnn/linear_attention/frost/kernel/gdn_recompute_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/gdn_recompute_f16.py @@ -96,6 +96,8 @@ Producer, PipelineState, advance, + launch_dependent_grids, + wait_on_dependent_grids, ) from cudnn.frost.tile_dsl.handles import MmaDesc, SmemTile, tma_slice_runtime_desc from cudnn.frost.tile_dsl.mma import mma_ss, mma_step_k8, mma_ts_step, mma_step @@ -110,6 +112,8 @@ ) from .gdn_recompute_config import CFG +USE_PDL = True + class GdnBars(NamedTuple): """Every inter-warp handoff as an ``MBarrier`` over its ring.""" @@ -498,7 +502,7 @@ def gate_beta_warp( oob_neutral = cutlass.Float32(0.0) if cutlass.const_expr(cfg.log_gate) else cutlass.Float32(1.0) toks = [chunk_offset + lane_idx + col * cfg.threads_per_warp for col in range(n_cols)] pos_valid = [tok < batch_end for tok in toks] - gate_vals = [gGateSeq[min(tok, batch_end - 1)] if valid else oob_neutral for tok, valid in zip(toks, pos_valid)] + gate_vals = [gGateSeq[min(tok, batch_end - 1)].to(cutlass.Float32) if valid else oob_neutral for tok, valid in zip(toks, pos_valid)] if cutlass.const_expr(cfg.safe_gate): for col in cutlass.range_constexpr(0, n_cols, 2): @@ -544,13 +548,14 @@ def gate_beta_warp( beta_idx = beta_index.idx bars.mb_beta_done[beta_idx].wait(beta_index.phase) beta_index = advance(beta_index, cfg.smem_beta_stages) - if cutlass.const_expr(cfg.beta_sigmoid): + if cutlass.const_expr(cfg.beta_sigmoid or mBeta.element_type != cutlass.Float32): for col in cutlass.range_constexpr(n_cols): pos = lane_idx + col * cfg.threads_per_warp beta_value = cutlass.Float32(0.0) if pos_valid[col]: beta_value = gBeta[pos].to(cutlass.Float32) - beta_value = sigmoid(beta_value).to(mBeta.element_type).to(cutlass.Float32) + if cutlass.const_expr(cfg.beta_sigmoid): + beta_value = sigmoid(beta_value).to(mBeta.element_type).to(cutlass.Float32) sBeta[pos, 0, beta_idx] = beta_value bars.mb_beta_ready[beta_idx].arrive() else: @@ -971,6 +976,8 @@ def tmaldg_warp( for _ in range(cfg.smem_v_stages): bars.mb_v_done[v_index.idx].wait(v_index.phase) v_index = advance(v_index, cfg.smem_v_stages) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -1639,6 +1646,9 @@ def frost_gdn_recompute_prologue( consumers' scheduler rings via :func:`order_body`; it then builds the per-batch TMA-descriptor arrays via :func:`build_descs_body`, one warp per array (the extra warps only take part in the order phase).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) @@ -1763,7 +1773,7 @@ def prologue( cutlass.Int32(v_row_stride), cutlass.Int32(state_checkpoints_out.stride[0] if state_checkpoints_out is not None else 0), checkpoint_every_n, - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) @cute.jit @@ -1915,6 +1925,7 @@ def host( block=(cfg.threads_per_cta, 1, 1), cluster=cfg.cluster_shape_mnk, stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -1942,6 +1953,8 @@ def frost_gdn_recompute( ): """Main GDN chunked kernel: warp-specialized dispatch over (batch, head) tiles.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() warp_idx = cute.arch.make_warp_uniform(cute.arch.warp_idx()) bidx = cute.arch.block_idx()[0] @@ -2345,6 +2358,8 @@ def get_compiled_cache( io_dtype_str: str, state_dtype_str: str, cu_dtype_str: str, + gate_dtype_str: str, + beta_dtype_str: str, HK: int, HV: int, HO: int, @@ -2543,6 +2558,8 @@ def chunk_gdn_recompute_sm100( str(k.dtype), str(state_dtype_src), str(cu_seqlens.dtype), + str(gate.dtype), + str(beta.dtype), HK, HV, HO, diff --git a/python/cudnn/linear_attention/frost/kernel/kda_bprop_f16.py b/python/cudnn/linear_attention/frost/kernel/kda_bprop_f16.py index 4cfffcedbf..bfc27b92de 100644 --- a/python/cudnn/linear_attention/frost/kernel/kda_bprop_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/kda_bprop_f16.py @@ -17,6 +17,8 @@ from .kda_bprop_config import CFG from cudnn.frost.tile_dsl.barrier import ( + launch_dependent_grids, + wait_on_dependent_grids, advance, MBarrier, PipelineState, @@ -40,6 +42,8 @@ sub_f16x2, ) +USE_PDL = True + LOG2_E: float = 1.4426950408889634 DEFAULT_GATE_LOWER_BOUND: float = -5.0 L2_NORM_EPS: float = 1.0e-12 @@ -334,6 +338,7 @@ def epilogue_warp( tma_granu_elems=64, tma_subtile_stride_elems=cfg.b_t * 64, ) + dgate_granu = cutlass.const_expr(128 // (cfg.gate_dtype.width // 8)) sDgate_tma = SmemTile( base=sDgate_raw, elems_per_stage=(cfg.b_t * cfg.d_k), @@ -341,9 +346,9 @@ def epilogue_warp( leading_byte_offset=0, stride_byte_offset=0, layout=0, - tma_loads_per_tile=(cfg.d_k // 32), - tma_granu_elems=32, - tma_subtile_stride_elems=cfg.b_t * 32, + tma_loads_per_tile=(cfg.d_k // dgate_granu), + tma_granu_elems=dgate_granu, + tma_subtile_stride_elems=cfg.b_t * dgate_granu, ) dq_index = PipelineState.start(phase=0) dk_index = PipelineState.start(phase=0) @@ -1511,6 +1516,7 @@ def tmaldg_warp( tma_granu_elems=64, tma_subtile_stride_elems=(cfg.b_t * 64), ) + gate_granu = cutlass.const_expr(128 // (cfg.gate_dtype.width // 8)) sGate_tma = SmemTile( base=sGate_raw, elems_per_stage=(cfg.d_k * cfg.b_t), @@ -1518,8 +1524,8 @@ def tmaldg_warp( leading_byte_offset=0, stride_byte_offset=0, layout=0, - tma_loads_per_tile=(cfg.d_k // 32), - tma_granu_elems=32, + tma_loads_per_tile=(cfg.d_k // gate_granu), + tma_granu_elems=gate_granu, tma_subtile_stride_elems=(cfg.b_t * 32), ) sDo_tma = SmemTile( @@ -1623,6 +1629,8 @@ def tmaldg_warp( tma_load_tile(sState_tma[state_idx], state_slice, bars.mb_state_ready[state_idx].smem_ptr, acquire=False) raw_index = advance(raw_index, cfg.smem_raw_stages) tile_idx = next_tile + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -1654,6 +1662,7 @@ def compute0_warp_group( sBeta_raw, sK_inv_raw, sGate_raw, + sGate_load_ptr, sK_raw, sQ_raw, sState_raw, @@ -1704,7 +1713,8 @@ def compute0_warp_group( raw_stage = chunk_serial % cfg.smem_raw_stages sQ_ptr = sQ_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sK_ptr = sK_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) - sGate_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) + sGate_ptr = sGate_load_ptr + raw_stage * cfg.gate_stage_elems + sGate_exchange_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sK_inv_ptr = sK_inv_raw.data_ptr() + decay_stage * (cfg.b_t * cfg.d_k) sK_decay_ptr = sK_decay_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) sQ_decay_ptr = sQ_decay_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) @@ -1734,54 +1744,111 @@ def compute0_warp_group( lane_in_row_group = lane_idx - lane_row_group * 8 decay_row = row_group_start + lane_row_group - g_prefix_ptr = sGate_ptr channel_dim = cg0_warp * cfg.threads_per_warp + lane_idx # ---- gate prefix scan: cumulative log-gate per key channel --------------- f32_segment = channel_dim // 32 f32_segment_dim = channel_dim - f32_segment * 32 + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + raw_segment = channel_dim // 64 + raw_seg_base = raw_segment * (cfg.b_t * 64) + raw_col = channel_dim - raw_segment * 64 prefix_acc = cutlass.Float32(0.0) exp_g_last = cutlass.Float32(0.0) - for row_pair in cutlass.range(cfg.b_t // 2, unroll=1): - row0 = row_pair * 2 - row1 = row0 + 1 - prefix_idx0 = f32_segment * (cfg.b_t * 32) + row0 * 32 + swizzle_xor_128b(row0, f32_segment_dim, elem_bytes=4) - prefix_idx1 = f32_segment * (cfg.b_t * 32) + row1 * 32 + swizzle_xor_128b(row1, f32_segment_dim, elem_bytes=4) - gate0 = (sGate_ptr + prefix_idx0).load() - gate1 = (sGate_ptr + prefix_idx1).load() - token_idx0 = chunk_idx * cutlass.Int32(cfg.b_t) + row0 - token_idx1 = chunk_idx * cutlass.Int32(cfg.b_t) + row1 - if cutlass.const_expr(cfg.safe_gate): - if token_idx0 < batch_seqlen: - gate0 = gate_scale(cfg, cg0_a_log_exp * (gate0 + cg0_dt_bias_value)) - else: - gate0 = cutlass.Float32(0.0) - if token_idx1 < batch_seqlen: - gate1 = gate_scale(cfg, cg0_a_log_exp * (gate1 + cg0_dt_bias_value)) - else: - gate1 = cutlass.Float32(0.0) - else: - if token_idx0 < batch_seqlen: - gate0 = gate_scale(cfg, gate0) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + for row_pair in cutlass.range(cfg.b_t // 2, unroll=1): + row0 = row_pair * 2 + row1 = row0 + 1 + prefix_idx0 = f32_segment * (cfg.b_t * 32) + row0 * 32 + swizzle_xor_128b(row0, f32_segment_dim, elem_bytes=4) + prefix_idx1 = f32_segment * (cfg.b_t * 32) + row1 * 32 + swizzle_xor_128b(row1, f32_segment_dim, elem_bytes=4) + gate0 = (sGate_ptr + prefix_idx0).load() + gate1 = (sGate_ptr + prefix_idx1).load() + token_idx0 = chunk_idx * cutlass.Int32(cfg.b_t) + row0 + token_idx1 = chunk_idx * cutlass.Int32(cfg.b_t) + row1 + if cutlass.const_expr(cfg.safe_gate): + if token_idx0 < batch_seqlen: + gate0 = gate_scale(cfg, cg0_a_log_exp * (gate0 + cg0_dt_bias_value)) + else: + gate0 = cutlass.Float32(0.0) + if token_idx1 < batch_seqlen: + gate1 = gate_scale(cfg, cg0_a_log_exp * (gate1 + cg0_dt_bias_value)) + else: + gate1 = cutlass.Float32(0.0) else: - gate0 = cutlass.Float32(0.0) - if token_idx1 < batch_seqlen: - gate1 = gate_scale(cfg, gate1) + if token_idx0 < batch_seqlen: + gate0 = gate_scale(cfg, gate0) + else: + gate0 = cutlass.Float32(0.0) + if token_idx1 < batch_seqlen: + gate1 = gate_scale(cfg, gate1) + else: + gate1 = cutlass.Float32(0.0) + pair_vec = nvvm.add_packed_f32x2( + cutlass.Vector.from_elements((prefix_acc, gate0), cutlass.Float32), + cutlass.Vector.from_elements((gate0, gate1), cutlass.Float32), + ftz=False, + rnd="rn", + ) + prefix0, row_pair_sum = cutlass.Float32(pair_vec[0]), cutlass.Float32(pair_vec[1]) + prefix1 = prefix_acc + row_pair_sum + exp_g0 = cute.math.exp2(prefix0, fastmath=True) + exp_g1 = cute.math.exp2(prefix1, fastmath=True) + (sGate_exchange_ptr + prefix_idx0).store(exp_g0) + (sGate_exchange_ptr + prefix_idx1).store(exp_g1) + prefix_acc = prefix1 + exp_g_last = exp_g1 + else: + gate_raw = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) + for row_pair in cutlass.range_constexpr(cfg.b_t // 2): + row0 = row_pair * 2 + row1 = row0 + 1 + raw_idx0 = raw_seg_base + swizzle_xor_128b(row0, row0 * 64 + raw_col, elem_bytes=2) + raw_idx1 = raw_seg_base + swizzle_xor_128b(row1, row1 * 64 + raw_col, elem_bytes=2) + gate0 = (sGate_ptr + raw_idx0).load().to(cutlass.Float32) + gate1 = (sGate_ptr + raw_idx1).load().to(cutlass.Float32) + token_idx0 = chunk_idx * cutlass.Int32(cfg.b_t) + row0 + token_idx1 = chunk_idx * cutlass.Int32(cfg.b_t) + row1 + if cutlass.const_expr(cfg.safe_gate): + if token_idx0 < batch_seqlen: + gate0 = gate_scale(cfg, cg0_a_log_exp * (gate0 + cg0_dt_bias_value)) + else: + gate0 = cutlass.Float32(0.0) + if token_idx1 < batch_seqlen: + gate1 = gate_scale(cfg, cg0_a_log_exp * (gate1 + cg0_dt_bias_value)) + else: + gate1 = cutlass.Float32(0.0) else: - gate1 = cutlass.Float32(0.0) - pair_vec = nvvm.add_packed_f32x2( - cutlass.Vector.from_elements((prefix_acc, gate0), cutlass.Float32), - cutlass.Vector.from_elements((gate0, gate1), cutlass.Float32), - ftz=False, - rnd="rn", - ) - prefix0, row_pair_sum = cutlass.Float32(pair_vec[0]), cutlass.Float32(pair_vec[1]) - prefix1 = prefix_acc + row_pair_sum - exp_g0 = cute.math.exp2(prefix0, fastmath=True) - exp_g1 = cute.math.exp2(prefix1, fastmath=True) - (sGate_ptr + prefix_idx0).store(exp_g0) - (sGate_ptr + prefix_idx1).store(exp_g1) - prefix_acc = prefix1 - exp_g_last = exp_g1 + if token_idx0 < batch_seqlen: + gate0 = gate_scale(cfg, gate0) + else: + gate0 = cutlass.Float32(0.0) + if token_idx1 < batch_seqlen: + gate1 = gate_scale(cfg, gate1) + else: + gate1 = cutlass.Float32(0.0) + gate_raw[row0] = gate0 + gate_raw[row1] = gate1 + nvvm.barrier_cta_sync(cfg.cg0_sync_barrier_id, thread_count=cfg.cg0_threads) + for row_pair in cutlass.range_constexpr(cfg.b_t // 2): + row0 = row_pair * 2 + row1 = row0 + 1 + prefix_idx0 = f32_segment * (cfg.b_t * 32) + row0 * 32 + swizzle_xor_128b(row0, f32_segment_dim, elem_bytes=4) + prefix_idx1 = f32_segment * (cfg.b_t * 32) + row1 * 32 + swizzle_xor_128b(row1, f32_segment_dim, elem_bytes=4) + gate0 = gate_raw[row0] + gate1 = gate_raw[row1] + pair_vec = nvvm.add_packed_f32x2( + cutlass.Vector.from_elements((prefix_acc, gate0), cutlass.Float32), + cutlass.Vector.from_elements((gate0, gate1), cutlass.Float32), + ftz=False, + rnd="rn", + ) + prefix0, row_pair_sum = cutlass.Float32(pair_vec[0]), cutlass.Float32(pair_vec[1]) + prefix1 = prefix_acc + row_pair_sum + exp_g0 = cute.math.exp2(prefix0, fastmath=True) + exp_g1 = cute.math.exp2(prefix1, fastmath=True) + (sGate_exchange_ptr + prefix_idx0).store(exp_g0) + (sGate_exchange_ptr + prefix_idx1).store(exp_g1) + prefix_acc = prefix1 + exp_g_last = exp_g1 # ---- decay-slot guard ---------------------------------------------------- operand_done_phase = ((chunk_serial // cfg.smem_decay_stages) + 1) % 2 bars.mb_decay_done[decay_stage].wait(operand_done_phase) @@ -1889,9 +1956,9 @@ def compute0_warp_group( f32_segment = f32_dim_base // 32 f32_segment_dim = f32_dim_base - f32_segment * 32 g_prefix_idx = f32_segment * (cfg.b_t * 32) + decay_row * 32 + swizzle_xor_128b(decay_row, f32_segment_dim, elem_bytes=4) - exp_g_frag = (g_prefix_ptr + g_prefix_idx).load(count=4, alignment=16) + exp_g_frag = (sGate_exchange_ptr + g_prefix_idx).load(count=4, alignment=16) exp_g_last_idx = f32_segment * (cfg.b_t * 32) + (cfg.b_t - 1) * 32 + swizzle_xor_128b((cfg.b_t - 1), f32_segment_dim, elem_bytes=4) - exp_g_last_frag = (g_prefix_ptr + exp_g_last_idx).load(count=4, alignment=16) + exp_g_last_frag = (sGate_exchange_ptr + exp_g_last_idx).load(count=4, alignment=16) f32_reg_base = reg_base + f32_group * 4 exp_g_regs[f32_reg_base] = exp_g_frag[0] exp_g_regs[f32_reg_base + 1] = exp_g_frag[1] @@ -2082,14 +2149,15 @@ def compute1_warp_group( bars.mb_dstate_smem_cg2_done.wait(dstate_smem_done_index.phase) dstate_smem_done_index = advance(dstate_smem_done_index, 1) row_lo_addr = tmem_row << 16 + seed_vw = 16 // (mDstate_in.element_type.width // 8) dstate_src = (mDstate_in.iterator + mDstate_in.layout((batch_idx, head_idx, value_dim, 0))).raw_ptr() for i in cutlass.range_constexpr(cfg.d_k // 16): seed_block = cutlass.Array(cutlass.Float32, 16, alignment=16) - for g in cutlass.range_constexpr(4): - seed_chunk = (dstate_src + i * 16 + g * 4).load(count=4, alignment=16) - for t in cutlass.range_constexpr(4): + for g in cutlass.range_constexpr(16 // seed_vw): + seed_chunk = (dstate_src + i * 16 + g * seed_vw).load(count=seed_vw, alignment=16) + for t in cutlass.range_constexpr(seed_vw): dval = seed_chunk[t].to(cutlass.Float32) - seed_block[g * 4 + t] = dval if seed_true else cutlass.Float32(0.0) + seed_block[g * seed_vw + t] = dval if seed_true else cutlass.Float32(0.0) nvvm.tcgen05_st( "32x32b", nvvm.make_tmem_ptr(row_lo_addr + (tmem_col + cfg.tmem_dstate_acc_offset + i * 16), cutlass.Float32), @@ -2419,14 +2487,18 @@ def compute1_warp_group( if num_compute_chunks > 0: if write_start == 0: row_lo_addr = tmem_row << 16 + dstate0_vw = 16 // (mDstate0.element_type.width // 8) dstate0_dst = (mDstate0.iterator + mDstate0.layout((batch_idx, head_idx, value_dim, 0))).raw_ptr() for i in cutlass.range_constexpr(cfg.d_k // 32): dstate0_vec = nvvm.tcgen05_ld( "32x32b", nvvm.make_tmem_ptr(row_lo_addr + (tmem_col + cfg.tmem_dstate_acc_offset + i * 32), cutlass.Float32), num=32 ) - for g in cutlass.range_constexpr(8): - (dstate0_dst + i * 32 + g * 4).store( - cutlass.Vector.from_elements(tuple(dstate0_vec[g * 4 + t] for t in range(4)), cutlass.Float32), + for g in cutlass.range_constexpr(32 // dstate0_vw): + (dstate0_dst + i * 32 + g * dstate0_vw).store( + cutlass.Vector.from_elements( + tuple(dstate0_vec[g * dstate0_vw + t].to(mDstate0.element_type) for t in range(dstate0_vw)), + mDstate0.element_type, + ), alignment=16, ) else: @@ -2436,7 +2508,7 @@ def compute1_warp_group( if cutlass.const_expr(cfg.use_dstate_in): mDstate0[batch_idx, head_idx, value_dim, kd] = mDstate_in[batch_idx, head_idx, value_dim, kd] else: - mDstate0[batch_idx, head_idx, value_dim, kd] = cutlass.Float32(0.0) + mDstate0[batch_idx, head_idx, value_dim, kd] = cutlass.Float32(0.0).to(mDstate0.element_type) if num_compute_chunks > 0: bars.mb_dstate0_acc_stored.arrive() chunk_serial_base += num_compute_chunks @@ -2511,7 +2583,7 @@ def compute2_warp_group( has_dstate = cutlass.Boolean(rev_idx > 0) if cutlass.const_expr(cfg.use_dstate_in): has_dstate = cutlass.Boolean(True) - sGate_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) + sGate_exchange_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) writes = chunk_idx < write_end bars.mb_k_decay_inv_ready[decay_stage].wait((chunk_serial // cfg.smem_decay_stages) % 2) @@ -2523,7 +2595,7 @@ def compute2_warp_group( f16_dim = channel - f16_seg * 64 eg = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) for t in cutlass.range_constexpr(cfg.b_t): - eg[t] = (sGate_ptr + f32_seg * (cfg.b_t * 32) + t * 32 + swizzle_xor_128b(t, f32_dim, elem_bytes=4)).load() + eg[t] = (sGate_exchange_ptr + f32_seg * (cfg.b_t * 32) + t * 32 + swizzle_xor_128b(t, f32_dim, elem_bytes=4)).load() egl = eg[cfg.b_t - 1] nvvm.fence_proxy("async.shared", space="cta") bars.mb_gate_done[raw_stage].arrive() @@ -2735,9 +2807,17 @@ def compute2_warp_group( # ---- stage dGate for the epilogue TMA store ------------------------------ dgate_stage = chunk_serial % cfg.smem_dgate_stages bars.mb_dgate_tmastg_done[dgate_stage].wait(((chunk_serial // cfg.smem_dgate_stages) + 1) % 2) - for t in cutlass.range_constexpr(cfg.b_t): - dgate_idx = f32_seg * (cfg.b_t * 32) + t * 32 + swizzle_xor_128b(t, f32_dim, elem_bytes=4) - (sDgate_raw.data_ptr() + dgate_idx).store(dgate_regs[t]) + dgate_base = dgate_stage * (cfg.b_t * cfg.d_k) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + for t in cutlass.range_constexpr(cfg.b_t): + dgate_idx = f32_seg * (cfg.b_t * 32) + t * 32 + swizzle_xor_128b(t, f32_dim, elem_bytes=4) + (sDgate_raw.data_ptr() + dgate_base + dgate_idx).store(dgate_regs[t]) + else: + dgate_seg = channel // 64 + dgate_dim = channel - dgate_seg * 64 + for t in cutlass.range_constexpr(cfg.b_t): + dgate_idx = dgate_seg * (cfg.b_t * 64) + t * 64 + swizzle_xor_128b(t, dgate_dim, elem_bytes=2) + (sDgate_raw.data_ptr() + dgate_base + dgate_idx).store(dgate_regs[t].to(cfg.gate_dtype)) nvvm.fence_proxy("async.shared", space="cta") bars.mb_dgate_tmastg_ready[dgate_stage].arrive() raw_index = advance(raw_index, cfg.smem_raw_stages) @@ -2897,6 +2977,9 @@ def frost_kda_bprop_prologue( consumers' scheduler rings via :func:`order_body`; it then builds the per-batch TMA-descriptor arrays via :func:`build_descs_body`, one warp per array (the extra warps only take part in the order phase).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) @@ -3016,12 +3099,15 @@ def prologue( base_q = cuda.create_tensor_map_tiled_from_view(q_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_k = cuda.create_tensor_map_tiled_from_view(k_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_v = cuda.create_tensor_map_tiled_from_view(v_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) - base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(32, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) + gate_granu_elems = 128 // (gate.element_type.width // 8) + base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(gate_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_do = cuda.create_tensor_map_tiled_from_view(do_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_dq = cuda.create_tensor_map_tiled_from_view(dq_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_dk = cuda.create_tensor_map_tiled_from_view(dk_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_dv = cuda.create_tensor_map_tiled_from_view(dv_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) - base_dgate = cuda.create_tensor_map_tiled_from_view(dgate_headed, box_dims=(32, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) + base_dgate = cuda.create_tensor_map_tiled_from_view( + dgate_headed, box_dims=(128 // (dgate.element_type.width // 8), 1, b_t), stride_order=(0, 1, 2), swizzle=swz + ) checkpoint_view = cute.make_tensor( state_checkpoints.iterator, @@ -3075,7 +3161,7 @@ def prologue( cutlass.Int32(dgate.stride[0]), cutlass.Int32(state_checkpoints.stride[0]), cutlass.Int32(b_t), - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) @cute.jit @@ -3122,6 +3208,7 @@ def host( grid=grid_shape, block=(cfg.threads_per_cta, 1, 1), stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -3145,6 +3232,8 @@ def frost_kda_bprop( scale: cutlass.Float32, ) -> None: """BT=16 KDA backward kernel (persistent, 16 warps).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx()[0] num_ctas = cute.arch.grid_dim()[0] @@ -3152,10 +3241,9 @@ def frost_kda_bprop( lane_idx = tidx % cfg.threads_per_warp total_tiles = mCount[0] - beta_expected = cfg.io_dtype if cutlass.const_expr(cfg.beta_sigmoid) else cutlass.Float32 - assert mBeta.element_type == beta_expected + assert mBeta.element_type in (cutlass.Float32, cfg.io_dtype) assert cu_seqlens.element_type in (cutlass.Int32, cutlass.Int64) - assert mDgate.element_type == cutlass.Float32 and mDbeta.element_type == beta_expected + assert mDgate.element_type == cfg.gate_dtype and mDbeta.element_type == mBeta.element_type desc_base_words = tensormap_workspace.iterator.raw_ptr() arr_words = n_desc * cutlass.Int32(TENSOR_MAP_QWORDS) @@ -3201,11 +3289,15 @@ def frost_kda_bprop( sK_raw = cutlass.Array(cfg.io_dtype, cfg.raw_qk_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sV_raw = cutlass.Array(cfg.io_dtype, cfg.raw_v_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sGate_raw = cutlass.Array(cutlass.Float32, cfg.raw_gate_cosize, space=SMEM, alignment=1024) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + sGate_load_ptr = sGate_raw.data_ptr() + else: + sGate_load_ptr = cute.make_ptr(cfg.gate_dtype, sGate_raw.data_ptr().toint(), mem_space=SMEM, assumed_align=1024) sDy_raw = cutlass.Array(cfg.io_dtype, cfg.b_t * cfg.d_v, space=SMEM, alignment=cfg.buffer_align_bytes) sU_raw = cutlass.Array(cfg.io_dtype, cfg.b_t * cfg.d_v, space=SMEM, alignment=cfg.buffer_align_bytes) sDq_raw = cutlass.Array(cfg.io_dtype, cfg.dq_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sDk_raw = cutlass.Array(cfg.io_dtype, cfg.dk_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) - sDgate_raw = cutlass.Array(cutlass.Float32, cfg.dgate_cosize, space=SMEM, alignment=1024) + sDgate_raw = cutlass.Array(cfg.gate_dtype, cfg.dgate_cosize, space=SMEM, alignment=1024) sState_trans = SmemTile( base=sState_raw.data_ptr().toint(), @@ -3537,6 +3629,7 @@ def frost_kda_bprop( sBeta_raw, sK_inv_raw, sGate_raw, + sGate_load_ptr, sK_raw, sQ_raw, sState_raw, @@ -3605,6 +3698,7 @@ class KdaBwdCfg: and SMEM buffer cosizes are stamped by ``build_cfg``).""" io_dtype: Type[cutlass.Numeric] + gate_dtype: Type[cutlass.Numeric] use_dstate_in: bool use_dstate0: bool l2norm: bool @@ -3683,6 +3777,7 @@ class KdaBwdCfg: raw_qk_cosize: int = 0 raw_v_cosize: int = 0 raw_gate_cosize: int = 0 + gate_stage_elems: int = 0 operand_cosize: int = 0 diag_cosize: int = 0 intermediate_cosize: int = 0 @@ -3703,6 +3798,7 @@ class KdaBwdCfg: def build_cfg( io_dtype: Type[cutlass.Numeric], + gate_dtype: Type[cutlass.Numeric], *, use_dstate_in: bool, use_dstate0: bool, @@ -3722,6 +3818,7 @@ def build_cfg( raise ValueError(f"io_dtype={io_dtype} not supported; only Float16 and BFloat16 are supported") cfg = KdaBwdCfg( io_dtype=io_dtype, + gate_dtype=gate_dtype, use_dstate_in=use_dstate_in, use_dstate0=use_dstate0, l2norm=l2norm, @@ -3765,6 +3862,7 @@ def build_cfg( cfg.raw_qk_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t cfg.raw_v_cosize = cfg.smem_raw_stages * cfg.d_v * cfg.b_t cfg.raw_gate_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t + cfg.gate_stage_elems = (cfg.d_k * cfg.b_t) * (4 // (cfg.gate_dtype.width // 8)) cfg.operand_cosize = cfg.smem_decay_stages * cfg.b_t * cfg.d_k cfg.diag_cosize = cfg.smem_decay_stages * (cfg.d_k // 16) * 256 cfg.intermediate_cosize = cfg.smem_intermediate_stages * cfg.intermediate_tiles * cfg.b_t * cfg.b_t @@ -3776,7 +3874,7 @@ def build_cfg( cfg.tma_state_bytes = cfg.d_k * cfg.d_v * (io_dtype.width // 8) cfg.tma_q_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_k_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) - cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * 4 + cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * (cfg.gate_dtype.width // 8) cfg.tma_do_bytes = cfg.d_v * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_v_bytes = cfg.d_v * cfg.b_t * (cfg.io_dtype.width // 8) return cfg @@ -3792,7 +3890,11 @@ def build_cfg( @lru_cache(maxsize=None) def get_compiled_cache( io_dtype_str: str, + dstate_in_dtype_str: str, + dstate0_dtype_str: str, + gate_dtype_str: str, cu_dtype_str: str, + beta_dtype_str: str, HQ: int, HK: int, HV: int, @@ -3852,7 +3954,8 @@ def chunk_kda_bwd_sm100( q: ``(total_tokens, HQ, DK)`` float16/bfloat16 k: ``(total_tokens, HK, DK)`` float16/bfloat16 v: ``(total_tokens, HV, DV)`` float16/bfloat16 - gate: ``(total_tokens, HO, DK)`` fp32. Natural-log per-channel decay + gate: ``(total_tokens, HO, DK)`` float32/bfloat16/float16 (16-bit is widened to fp32 on the SMEM read). + Natural-log per-channel decay unless ``safe_gate``, which applies the safe-gate transform ``lower_bound * sigmoid(exp(a_log) * (gate + dt_bias))``. beta: ``(total_tokens, HO)``. Post-sigmoid float32, or io-dtype @@ -3874,8 +3977,9 @@ def chunk_kda_bwd_sm100( scale: attention scale factor use_initial_state: the forward ran with an initial state, so chunk 0 has an entering state to load from ``state_checkpoints`` row 0 - d_initial_state: fp32 ``(num_seqs, HO, DV, DK)`` OUT (dL/d initial state), or None - d_final_state: fp32 ``(num_seqs, HO, DV, DK)`` IN (dL/d final state) + d_initial_state: ``(num_seqs, HO, DV, DK)`` float32/bfloat16 OUT (dL/d initial state), or None + d_final_state: ``(num_seqs, HO, DV, DK)`` float32/bfloat16 IN (dL/d final state); both state + gradients carry the same dtype use_qk_l2norm_in_kernel: q/k arrive raw; the kernel normalizes for the recompute math and chains the L2-norm backward into dq/dk safe_gate: interpret ``gate`` through the safe-gate transform @@ -3924,7 +4028,11 @@ def chunk_kda_bwd_sm100( cu_stream = cuda_driver.CUstream(int(stream)) cache = get_compiled_cache( str(q.dtype), + str(d_final_state.dtype) if d_final_state is not None else "none", + str(d_initial_state.dtype) if d_initial_state is not None else "none", + str(gate.dtype), str(cu_seqlens.dtype), + str(beta.dtype), HQ, HK, HV, @@ -3942,8 +4050,10 @@ def chunk_kda_bwd_sm100( if "compiled" not in cache: io_dtype = get_dtype(q.dtype) + gate_dtype = get_dtype(gate.dtype) cfg = build_cfg( io_dtype, + gate_dtype, use_dstate_in=use_dstate_in, use_dstate0=use_dstate0, l2norm=use_qk_l2norm_in_kernel, diff --git a/python/cudnn/linear_attention/frost/kernel/kda_prefill_f16.py b/python/cudnn/linear_attention/frost/kernel/kda_prefill_f16.py index b092b98b05..7619e86b68 100644 --- a/python/cudnn/linear_attention/frost/kernel/kda_prefill_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/kda_prefill_f16.py @@ -35,9 +35,11 @@ from cudnn.frost.tile_dsl.barrier import ( advance, + launch_dependent_grids, MBarrier, PipelineState, Producer, + wait_on_dependent_grids, ) from cudnn.frost.tile_dsl.handles import GmemTileTma, MmaDesc, SmemTile, tma_slice_runtime_desc from cudnn.frost.tile_dsl.mma import mma_step, mma_ts_step @@ -56,6 +58,8 @@ sub_f16x2, ) +USE_PDL = True + LOG2_E: float = 1.4426950408889634 DEFAULT_GATE_LOWER_BOUND: float = -5.0 L2_NORM_EPS: float = 1.0e-12 @@ -218,6 +222,8 @@ def tmaldg_warp( sK_raw, sV_raw, sGate_raw, + mBeta, + sBeta_raw, desc_q_base, desc_k_base, desc_v_base, @@ -225,7 +231,7 @@ def tmaldg_warp( bars, ) -> None: """TMA-LDG warp role (warp 14): persistent scheduler loop issuing the - per-chunk Q/K/V/Gate G->S loads.""" + per-chunk Q/K/V/Gate G->S loads, and staging beta one chunk ahead.""" nvvm.setmaxregister(cfg.num_regs_other, nvvm.SetMaxRegisterAction.DECREASE) raw_index = PipelineState.start(phase=1) @@ -266,6 +272,7 @@ def tmaldg_warp( tma_granu_elems=64, tma_subtile_stride_elems=(cfg.b_t * 64), ) + gate_granu = cutlass.const_expr(128 // (cfg.gate_dtype.width // 8)) sGate_tma = SmemTile( base=sGate_raw, elems_per_stage=(cfg.d_k * cfg.b_t), @@ -273,8 +280,8 @@ def tmaldg_warp( leading_byte_offset=0, stride_byte_offset=0, layout=0, - tma_loads_per_tile=(cfg.d_k // 32), - tma_granu_elems=32, + tma_loads_per_tile=(cfg.d_k // gate_granu), + tma_granu_elems=gate_granu, tma_subtile_stride_elems=(cfg.b_t * 32), ) tile_idx = cutlass.Int32(bidx) @@ -296,9 +303,32 @@ def tmaldg_warp( tma_tensormap_acquire(desc_k_slot) tma_tensormap_acquire(desc_v_slot) tma_tensormap_acquire(desc_gate_slot) + + # ---- Beta prefetch ----------------------------------------------------------- + beta_carry = cutlass.Float32(0.0) + beta_token = compute_start * cfg.b_t + lane_idx + if lane_idx < cfg.b_t: + if beta_token < batch_seqlen: + beta_carry = mBeta[batch_start + beta_token, head_o].to(cutlass.Float32) + if cutlass.const_expr(cfg.beta_sigmoid): + beta_carry = sigmoid(beta_carry).to(mBeta.element_type).to(cutlass.Float32) + for chunk_idx in cutlass.range(compute_start, write_end, 1, unroll=1): chunk_start = chunk_idx * cfg.b_t + # ---- Beta: store from the previous iteration ----------------------------- + bars.mb_beta_done[raw_bar_index.idx].wait(raw_bar_index.phase ^ cutlass.Int32(1)) + if lane_idx < cfg.b_t: + sBeta_raw[raw_bar_index.idx * cfg.b_t + lane_idx] = beta_carry + bars.mb_beta_ready[raw_bar_index.idx].arrive() + beta_carry = cutlass.Float32(0.0) + beta_token = (chunk_idx + 1) * cfg.b_t + lane_idx + if lane_idx < cfg.b_t: + if beta_token < batch_seqlen: + beta_carry = mBeta[batch_start + beta_token, head_o].to(cutlass.Float32) + if cutlass.const_expr(cfg.beta_sigmoid): + beta_carry = sigmoid(beta_carry).to(mBeta.element_type).to(cutlass.Float32) + # ---- Q load -------------------------------------------------------------- bars.mb_q_done[raw_index.idx].wait(raw_index.phase) if elect_one: @@ -330,6 +360,8 @@ def tmaldg_warp( raw_index = advance(raw_index, cfg.smem_raw_stages) raw_bar_index = advance(raw_bar_index, cfg.smem_raw_bar_stages) tile_idx, scheduler_state = scheduler_publish_next(cfg, bars, sScheduler, mScheduler, scheduler_state, tile_idx, num_ctas, elect_one) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -1041,8 +1073,7 @@ def compute0_warp_group( mDt_bias, sK_inv_raw, sGate_raw, - mBeta, - sBeta_raw, + sGate_load_ptr, sK_raw, sQ_raw, sK_decay_raw, @@ -1093,25 +1124,14 @@ def compute0_warp_group( qk_scale_ready_stage = state_scale_diag_stage sQ_ptr = sQ_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sK_ptr = sK_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) - sGate_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) + sGate_ptr = sGate_load_ptr + raw_stage * cfg.gate_stage_elems + sGate_exchange_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sK_inv_ptr = sK_inv_raw.data_ptr() + decay_stage * (cfg.b_t * cfg.d_k) sK_decay_ptr = sK_decay_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) sQ_decay_ptr = sQ_decay_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) sK_restore_ptr = sK_restore_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) sState_scale_diag_ptr = sState_scale_diag_raw.data_ptr() + state_scale_diag_stage * ((cfg.d_k // 16) * 256) - # ---- Beta scalars -------------------------------------------------------- - if cg0_local_warp == 0: - bars.mb_beta_done[raw_bar_stage].wait(((cum_chunk // cfg.smem_raw_bar_stages) + 1) % 2) - if lane_idx < cfg.b_t: - token_idx = chunk_idx * cfg.b_t + lane_idx - beta_value = cutlass.Float32(0.0) - if token_idx < batch_seqlen: - beta_value = mBeta[batch_start + token_idx, head_o].to(cutlass.Float32) - if cutlass.const_expr(cfg.beta_sigmoid): - beta_value = sigmoid(beta_value).to(mBeta.element_type).to(cutlass.Float32) - sBeta_raw[raw_bar_stage * cfg.b_t + lane_idx] = beta_value - bars.mb_beta_ready[raw_bar_stage].arrive() bars.mb_gate_ready[raw_bar_stage].wait((cum_chunk // cfg.smem_raw_bar_stages) % 2) row_group_start = cg0_local_warp * (cfg.b_t // cfg.cg0_warps_per_group) @@ -1126,9 +1146,17 @@ def compute0_warp_group( prefix_seg_base = f32_segment * (cfg.b_t * 32) prefix_col = channel_dim - f32_segment * 32 gate_raw = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) - for row in cutlass.range_constexpr(cfg.b_t): - prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - gate_raw[row] = (sGate_ptr + prefix_idx).load() + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + for row in cutlass.range_constexpr(cfg.b_t): + prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) + gate_raw[row] = (sGate_ptr + prefix_idx).load() + else: + raw_segment = channel_dim // 64 + raw_seg_base = raw_segment * (cfg.b_t * 64) + raw_col = channel_dim - raw_segment * 64 + for row in cutlass.range_constexpr(cfg.b_t): + raw_idx = raw_seg_base + swizzle_xor_128b(row, row * 64 + raw_col, elem_bytes=2) + gate_raw[row] = (sGate_ptr + raw_idx).load().to(cutlass.Float32) g_prefix_regs = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) if cutlass.const_expr(cfg.safe_gate): for row in cutlass.range_constexpr(cfg.b_t): @@ -1172,9 +1200,11 @@ def compute0_warp_group( g_prefix_regs[row] = cute.math.exp2(g_prefix_regs[row], fastmath=True) exp_g_last = g_prefix_regs[cfg.b_t - 1] + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + nvvm.barrier_cta_sync(cfg.cg0_group_sync_barrier_base_id + cg0_group_id, thread_count=cfg.cg0_threads_per_group) for row in cutlass.range_constexpr(cfg.b_t): prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - (sGate_ptr + prefix_idx).store(g_prefix_regs[row]) + (sGate_exchange_ptr + prefix_idx).store(g_prefix_regs[row]) # ---- state-scale diag: stage exp2(g last) decay blocks ------------------- bars.mb_state_scale_diag_done[state_scale_diag_stage].wait(diag_ring_phase ^ cutlass.Int32(1)) @@ -1245,9 +1275,9 @@ def compute0_warp_group( f32_segment = f32_dim_base // 32 f32_segment_dim = f32_dim_base - f32_segment * 32 g_prefix_idx = f32_segment * (cfg.b_t * 32) + decay_row * 32 + swizzle_xor_128b(decay_row, f32_segment_dim, elem_bytes=4) - exp_g_frag = (sGate_ptr + g_prefix_idx).load(count=4, alignment=16) + exp_g_frag = (sGate_exchange_ptr + g_prefix_idx).load(count=4, alignment=16) exp_g_last_idx = f32_segment * (cfg.b_t * 32) + (cfg.b_t - 1) * 32 + swizzle_xor_128b((cfg.b_t - 1), f32_segment_dim, elem_bytes=4) - exp_g_last_frag = (sGate_ptr + exp_g_last_idx).load(count=4, alignment=16) + exp_g_last_frag = (sGate_exchange_ptr + exp_g_last_idx).load(count=4, alignment=16) f32_reg_base = reg_base + f32_group * 4 for j in cutlass.range_constexpr(4): exp_g_regs[f32_reg_base + j] = exp_g_frag[j] @@ -1920,6 +1950,7 @@ def host( grid=grid_shape, block=(cfg.threads_per_cta, 1, 1), stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -1947,6 +1978,8 @@ def frost_kda_prefill( checkpoint_every_n_tokens: cutlass.Int32, ) -> None: """BT=16 KDA forward kernel (persistent, tile-scheduled).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx()[0] @@ -1958,9 +1991,8 @@ def frost_kda_prefill( if cutlass.const_expr(cfg.dynamic_scheduling): assert mScheduler is not None and mScheduler.element_type == cutlass.Int32 assert mQ.element_type == cfg.io_dtype and mK.element_type == cfg.io_dtype and mV.element_type == cfg.io_dtype - assert mGate.element_type == cutlass.Float32 - beta_expected = cfg.io_dtype if cutlass.const_expr(cfg.beta_sigmoid) else cutlass.Float32 - assert mBeta.element_type == beta_expected + assert mGate.element_type == cfg.gate_dtype + assert mBeta.element_type in (cutlass.Float32, cfg.io_dtype) assert cu_seqlens.element_type in (cutlass.Int32, cutlass.Int64) if cutlass.const_expr(cfg.use_initial_state): assert mState_init is not None and mState_init.element_type in (cutlass.BFloat16, cutlass.Float32) @@ -1993,6 +2025,10 @@ def frost_kda_prefill( sK_raw = cutlass.Array(mK.element_type, cfg.k_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sV_raw = cutlass.Array(mV.element_type, cfg.v_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sGate_raw = cutlass.Array(cutlass.Float32, cfg.gate_cosize, space=SMEM, alignment=1024) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + sGate_load_ptr = sGate_raw.data_ptr() + else: + sGate_load_ptr = cute.make_ptr(cfg.gate_dtype, sGate_raw.data_ptr().toint(), mem_space=SMEM, assumed_align=1024) sState_scale_diag_raw = cutlass.Array(cfg.io_dtype, cfg.state_scale_diag_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sK_inv_raw = cutlass.Array(cfg.io_dtype, cfg.k_inv_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sO_raw = cutlass.Array( @@ -2125,6 +2161,8 @@ def frost_kda_prefill( sK_raw, sV_raw, sGate_raw, + mBeta, + sBeta_raw, desc_q_base, desc_k_base, desc_v_base, @@ -2201,8 +2239,7 @@ def frost_kda_prefill( mDt_bias, sK_inv_raw, sGate_raw, - mBeta, - sBeta_raw, + sGate_load_ptr, sK_raw, sQ_raw, sK_decay_raw, @@ -2245,6 +2282,7 @@ class KdaCfg: io_dtype: Type[cutlass.Numeric] state_dtype: Type[cutlass.Numeric] + gate_dtype: Type[cutlass.Numeric] use_initial_state: bool store_final_state: bool enable_checkpoints: bool @@ -2308,6 +2346,7 @@ class KdaCfg: k_cosize: int = 0 v_cosize: int = 0 gate_cosize: int = 0 + gate_stage_elems: int = 0 beta_cosize: int = 0 k_inv_cosize: int = 0 k_decay_cosize: int = 0 @@ -2327,6 +2366,7 @@ class KdaCfg: def build_cfg( io_dtype: Type[cutlass.Numeric], state_dtype: Type[cutlass.Numeric], + gate_dtype: Type[cutlass.Numeric], *, use_initial_state: bool, store_final_state: bool, @@ -2349,6 +2389,7 @@ def build_cfg( cfg = KdaCfg( io_dtype=io_dtype, state_dtype=state_dtype, + gate_dtype=gate_dtype, use_initial_state=use_initial_state, store_final_state=store_final_state, enable_checkpoints=enable_checkpoints, @@ -2385,6 +2426,7 @@ def build_cfg( cfg.k_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t cfg.v_cosize = cfg.smem_raw_stages * cfg.d_v * cfg.b_t cfg.gate_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t + cfg.gate_stage_elems = (cfg.d_k * cfg.b_t) * (4 // (cfg.gate_dtype.width // 8)) cfg.beta_cosize = cfg.smem_raw_bar_stages * cfg.b_t cfg.k_inv_cosize = cfg.smem_decay_stages * cfg.b_t * cfg.d_k cfg.k_decay_cosize = cfg.smem_decay_stages * cfg.d_k * cfg.b_t @@ -2396,7 +2438,7 @@ def build_cfg( cfg.tma_q_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_k_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_v_bytes = cfg.d_v * cfg.b_t * (cfg.io_dtype.width // 8) - cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * 4 + cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * (cfg.gate_dtype.width // 8) return cfg @@ -2475,6 +2517,7 @@ def frost_kda_prefill_prologue( order_gen: cutlass.Constexpr[bool], has_scheduler: cutlass.Constexpr[bool], b_t: cutlass.Constexpr[int], + num_ctas: cutlass.Constexpr[int], base_q: cutlass.GridConstant[cuda.tensor_map.TensorMap], base_k: cutlass.GridConstant[cuda.tensor_map.TensorMap], base_v: cutlass.GridConstant[cuda.tensor_map.TensorMap], @@ -2502,66 +2545,73 @@ def frost_kda_prefill_prologue( checkpoint_entry_stride: cutlass.Int32, checkpoint_every_n: cutlass.Int32, ) -> None: - """Single-CTA prologue: LPT-order the work-item table and zero the scheduler - rings via :func:`order_body`, then build the per-batch TMA-descriptor - arrays via :func:`build_descs_body`, one warp per array (the extra warps - only take part in the order phase).""" + """Two-CTA prologue: block 0 LPT-orders the work-item table and zeroes the + scheduler rings via :func:`order_body`, block 1 builds the per-batch + TMA-descriptor arrays via :func:`build_descs_body`, one warp per array.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) + bidx = cutlass.Int32(cute.arch.block_idx()[0]) sKey = cutlass.Array(cutlass.Int32, ORDER_CAPACITY, space=cutlass.AddressSpace.smem, alignment=16) sIdx = cutlass.Array(cutlass.Int32, ORDER_CAPACITY, space=cutlass.AddressSpace.smem, alignment=16) sSpread = cutlass.Array(cutlass.Int32, 2, space=cutlass.AddressSpace.smem, alignment=8) n_heads_out = cutlass.Int32(gate.shape[1]) - order_body( - order_gen, - has_scheduler, - b_t, - ORDER_THREADS, - ORDER_ELEMENTS, - tidx, - n_heads_out, - n_heads_out * n_batch, - cu_seqlens, - mStaging, - mCount, - mWorkItems, - mScheduler, - sKey, - sIdx, - sSpread, - ) - build_descs_body( - widx, - base_q, - base_k, - base_v, - base_gate, - base_o, - base_checkpoint, - desc_workspace, - cu_seqlens, - q, - k, - v, - gate, - o, - state_checkpoints, - n_batch, - q_token_stride, - k_token_stride, - v_token_stride, - gate_token_stride, - o_token_stride, - checkpoint_entry_stride, - checkpoint_every_n, - ) + if bidx == cutlass.Int32(0): + order_body( + order_gen, + has_scheduler, + b_t, + ORDER_THREADS, + ORDER_ELEMENTS, + tidx, + n_heads_out, + n_heads_out * n_batch, + cu_seqlens, + mStaging, + mCount, + mWorkItems, + mScheduler, + sKey, + sIdx, + sSpread, + num_ctas, + ) + else: + build_descs_body( + widx, + base_q, + base_k, + base_v, + base_gate, + base_o, + base_checkpoint, + desc_workspace, + cu_seqlens, + q, + k, + v, + gate, + o, + state_checkpoints, + n_batch, + q_token_stride, + k_token_stride, + v_token_stride, + gate_token_stride, + o_token_stride, + checkpoint_entry_stride, + checkpoint_every_n, + ) @cute.jit def prologue( io_dtype: cutlass.Constexpr, b_t: cutlass.Constexpr[int], + num_ctas: cutlass.Constexpr[int], order_gen: cutlass.Constexpr[bool], has_scheduler: cutlass.Constexpr[bool], q: cute.Tensor, @@ -2581,7 +2631,7 @@ def prologue( ): """One-launch prologue: LPT-order the work items and build the 6 per-(batch, head) TMA-descriptor arrays (q, k, v, gate, o, - state_checkpoints) into ``tensormap_workspace``.""" + state_checkpoints) into ``tensormap_workspace``, one block each.""" h_q = q.shape[1] h_k = k.shape[1] h_v = v.shape[1] @@ -2603,7 +2653,8 @@ def prologue( base_q = cuda.create_tensor_map_tiled_from_view(q_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_k = cuda.create_tensor_map_tiled_from_view(k_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_v = cuda.create_tensor_map_tiled_from_view(v_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) - base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(32, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) + gate_granu_elems = 128 // (gate.element_type.width // 8) + base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(gate_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_o = cuda.create_tensor_map_tiled_from_view(o_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_checkpoint = base_o @@ -2620,6 +2671,7 @@ def prologue( order_gen, has_scheduler, b_t, + num_ctas, base_q, base_k, base_v, @@ -2646,7 +2698,7 @@ def prologue( cutlass.Int32(o.stride[0]), cutlass.Int32(state_checkpoints.stride[0] if state_checkpoints is not None else 0), checkpoint_every_n, - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(2, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) # ---- Torch adapter / host-side compilation ------------------------------------------- @@ -2656,7 +2708,9 @@ def prologue( def get_compiled_cache( io_dtype_str: str, state_dtype_str: str, + gate_dtype_str: str, cu_dtype_str: str, + beta_dtype_str: str, HQ: int, HK: int, HV: int, @@ -2677,6 +2731,7 @@ def get_compiled_cache( def compile( io_dtype, state_dtype, + gate_dtype, use_initial_state: bool, store_final_state: bool, enable_checkpoints: bool, @@ -2714,6 +2769,7 @@ def compile( cfg = build_cfg( io_dtype, state_dtype, + gate_dtype, use_initial_state=use_initial_state, store_final_state=store_final_state, enable_checkpoints=enable_checkpoints, @@ -2791,7 +2847,8 @@ def chunk_kda_sm100( q: ``(total_tokens, HQ, DK)`` float16/bfloat16 k: ``(total_tokens, HK, DK)`` float16/bfloat16 v: ``(total_tokens, HV, DV)`` float16/bfloat16 - gate: ``(total_tokens, HO, DK)`` float32. Natural-log decay unless + gate: ``(total_tokens, HO, DK)`` float32/bfloat16/float16 (16-bit is + widened to fp32 on the SMEM read). Natural-log decay unless ``safe_gate``, which applies the safe-gate transform ``lower_bound * sigmoid(exp(a_log) * (gate + dt_bias))``. beta: ``(total_tokens, HO)``. Post-sigmoid float32, or io-dtype @@ -2872,7 +2929,9 @@ def chunk_kda_sm100( cache = get_compiled_cache( str(q.dtype), str(state_dtype_src), + str(gate.dtype), str(cu_seqlens.dtype), + str(beta.dtype), HQ, HK, HV, @@ -2890,6 +2949,7 @@ def chunk_kda_sm100( if "compiled" not in cache: io_dtype = get_dtype(q.dtype) state_dtype = get_dtype(state_dtype_src) + gate_dtype = get_dtype(gate.dtype) q_cute = from_dlpack(q, assumed_align=16).mark_layout_dynamic(leading_dim=2) k_cute = from_dlpack(k, assumed_align=16).mark_layout_dynamic(leading_dim=2) v_cute = from_dlpack(v, assumed_align=16).mark_layout_dynamic(leading_dim=2) @@ -2921,6 +2981,7 @@ def chunk_kda_sm100( cache["compiled"] = compile( io_dtype, state_dtype, + gate_dtype, use_initial_state, store_final_state, enable_checkpoints, @@ -2982,6 +3043,7 @@ def chunk_kda_sm100( prologue, io_dtype, CFG.B_T, + multiprocessor_count(current_device()), order_gen, dynamic_scheduling, q_pl, diff --git a/python/cudnn/linear_attention/frost/kernel/kda_recompute_f16.py b/python/cudnn/linear_attention/frost/kernel/kda_recompute_f16.py index 062088b3d6..31614e099a 100644 --- a/python/cudnn/linear_attention/frost/kernel/kda_recompute_f16.py +++ b/python/cudnn/linear_attention/frost/kernel/kda_recompute_f16.py @@ -34,6 +34,8 @@ from .kda_recompute_config import CFG from cudnn.frost.tile_dsl.barrier import ( + launch_dependent_grids, + wait_on_dependent_grids, advance, MBarrier, PipelineState, @@ -56,6 +58,8 @@ sub_f16x2, ) +USE_PDL = True + LOG2_E: float = 1.4426950408889634 DEFAULT_GATE_LOWER_BOUND: float = -5.0 L2_NORM_EPS: float = 1.0e-12 @@ -235,6 +239,7 @@ def tmaldg_warp( tma_granu_elems=64, tma_subtile_stride_elems=(cfg.b_t * 64), ) + gate_granu = cutlass.const_expr(128 // (cfg.gate_dtype.width // 8)) sGate_tma = SmemTile( base=sGate_raw, elems_per_stage=(cfg.d_k * cfg.b_t), @@ -242,8 +247,8 @@ def tmaldg_warp( leading_byte_offset=0, stride_byte_offset=0, layout=0, - tma_loads_per_tile=(cfg.d_k // 32), - tma_granu_elems=32, + tma_loads_per_tile=(cfg.d_k // gate_granu), + tma_granu_elems=gate_granu, tma_subtile_stride_elems=(cfg.b_t * 32), ) tile_idx = cutlass.Int32(bidx) @@ -288,6 +293,8 @@ def tmaldg_warp( raw_index = advance(raw_index, cfg.smem_raw_stages) tile_idx, scheduler_state = scheduler_publish_next(cfg, bars, sScheduler, mScheduler, scheduler_state, tile_idx, num_ctas, elect_one) + if cutlass.const_expr(USE_PDL): + launch_dependent_grids() @cute.jit @@ -808,6 +815,7 @@ def compute0_warp_group( mDt_bias, sK_inv_raw, sGate_raw, + sGate_load_ptr, mBeta, sBeta_raw, sK_raw, @@ -856,7 +864,8 @@ def compute0_warp_group( state_scale_diag_stage = diag_ring_stage qk_scale_ready_stage = state_scale_diag_stage sK_ptr = sK_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) - sGate_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) + sGate_ptr = sGate_load_ptr + raw_stage * cfg.gate_stage_elems + sGate_exchange_ptr = sGate_raw.data_ptr() + raw_stage * (cfg.d_k * cfg.b_t) sK_inv_ptr = sK_inv_raw.data_ptr() + decay_stage * (cfg.b_t * cfg.d_k) sK_decay_ptr = sK_decay_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) sK_restore_ptr = sK_restore_raw.data_ptr() + decay_stage * (cfg.d_k * cfg.b_t) @@ -888,9 +897,17 @@ def compute0_warp_group( prefix_seg_base = f32_segment * (cfg.b_t * 32) prefix_col = channel_dim - f32_segment * 32 gate_raw = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) - for row in cutlass.range_constexpr(cfg.b_t): - prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - gate_raw[row] = (sGate_ptr + prefix_idx).load() + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + for row in cutlass.range_constexpr(cfg.b_t): + prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) + gate_raw[row] = (sGate_ptr + prefix_idx).load() + else: + raw_segment = channel_dim // 64 + raw_seg_base = raw_segment * (cfg.b_t * 64) + raw_col = channel_dim - raw_segment * 64 + for row in cutlass.range_constexpr(cfg.b_t): + raw_idx = raw_seg_base + swizzle_xor_128b(row, row * 64 + raw_col, elem_bytes=2) + gate_raw[row] = (sGate_ptr + raw_idx).load().to(cutlass.Float32) g_prefix_regs = cutlass.Array(cutlass.Float32, cfg.b_t, alignment=16) if cutlass.const_expr(cfg.safe_gate): for row in cutlass.range_constexpr(cfg.b_t): @@ -934,9 +951,11 @@ def compute0_warp_group( g_prefix_regs[row] = cute.math.exp2(g_prefix_regs[row], fastmath=True) exp_g_last = g_prefix_regs[cfg.b_t - 1] + if cutlass.const_expr(cfg.gate_dtype != cutlass.Float32): + nvvm.barrier_cta_sync(cfg.cg0_group_sync_barrier_base_id + cg0_group_id, thread_count=cfg.cg0_threads_per_group) for row in cutlass.range_constexpr(cfg.b_t): prefix_idx = prefix_seg_base + swizzle_xor_128b(row, row * 32 + prefix_col, elem_bytes=4) - (sGate_ptr + prefix_idx).store(g_prefix_regs[row]) + (sGate_exchange_ptr + prefix_idx).store(g_prefix_regs[row]) # ---- state-scale diag: stage exp2(g last) decay blocks ------------------- bars.mb_state_scale_diag_done[state_scale_diag_stage].wait(diag_ring_phase ^ cutlass.Int32(1)) @@ -993,9 +1012,9 @@ def compute0_warp_group( f32_segment = f32_dim_base // 32 f32_segment_dim = f32_dim_base - f32_segment * 32 g_prefix_idx = f32_segment * (cfg.b_t * 32) + decay_row * 32 + swizzle_xor_128b(decay_row, f32_segment_dim, elem_bytes=4) - exp_g_frag = (sGate_ptr + g_prefix_idx).load(count=4, alignment=16) + exp_g_frag = (sGate_exchange_ptr + g_prefix_idx).load(count=4, alignment=16) exp_g_last_idx = f32_segment * (cfg.b_t * 32) + (cfg.b_t - 1) * 32 + swizzle_xor_128b((cfg.b_t - 1), f32_segment_dim, elem_bytes=4) - exp_g_last_frag = (sGate_ptr + exp_g_last_idx).load(count=4, alignment=16) + exp_g_last_frag = (sGate_exchange_ptr + exp_g_last_idx).load(count=4, alignment=16) f32_reg_base = reg_base + f32_group * 4 for j in cutlass.range_constexpr(4): exp_g_regs[f32_reg_base + j] = exp_g_frag[j] @@ -1550,6 +1569,7 @@ def host( grid=grid_shape, block=(cfg.threads_per_cta, 1, 1), stream=stream, + use_pdl=USE_PDL, min_blocks_per_mp=1, ) @@ -1575,6 +1595,8 @@ def frost_kda_recompute( ) -> None: """BT=16 KDA recompute (state/checkpoints-only) persistent kernel body: every warp role runs a tile-scheduler loop over the tiles.""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() tidx, _, _ = cute.arch.thread_idx() bidx = cute.arch.block_idx()[0] @@ -1586,9 +1608,8 @@ def frost_kda_recompute( if cutlass.const_expr(cfg.dynamic_scheduling): assert mScheduler is not None and mScheduler.element_type == cutlass.Int32 assert mK.element_type == cfg.io_dtype and mV.element_type == cfg.io_dtype - assert mGate.element_type == cutlass.Float32 - beta_expected = cfg.io_dtype if cutlass.const_expr(cfg.beta_sigmoid) else cutlass.Float32 - assert mBeta.element_type == beta_expected + assert mGate.element_type == cfg.gate_dtype + assert mBeta.element_type in (cutlass.Float32, cfg.io_dtype) assert cu_seqlens.element_type in (cutlass.Int32, cutlass.Int64) if cutlass.const_expr(cfg.use_initial_state): assert mState_init is not None and mState_init.element_type in (cutlass.BFloat16, cutlass.Float32) @@ -1617,6 +1638,10 @@ def frost_kda_recompute( sK_raw = cutlass.Array(mK.element_type, cfg.k_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sV_raw = cutlass.Array(mV.element_type, cfg.v_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sGate_raw = cutlass.Array(cutlass.Float32, cfg.gate_cosize, space=SMEM, alignment=1024) + if cutlass.const_expr(cfg.gate_dtype == cutlass.Float32): + sGate_load_ptr = sGate_raw.data_ptr() + else: + sGate_load_ptr = cute.make_ptr(cfg.gate_dtype, sGate_raw.data_ptr().toint(), mem_space=SMEM, assumed_align=1024) sState_scale_diag_raw = cutlass.Array(cfg.io_dtype, cfg.state_scale_diag_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sK_inv_raw = cutlass.Array(cfg.io_dtype, cfg.k_inv_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) sBeta_raw = cutlass.Array(cutlass.Float32, cfg.beta_cosize, space=SMEM, alignment=cfg.buffer_align_bytes) @@ -1789,6 +1814,7 @@ def frost_kda_recompute( mDt_bias, sK_inv_raw, sGate_raw, + sGate_load_ptr, mBeta, sBeta_raw, sK_raw, @@ -1828,6 +1854,7 @@ class KdaRecomputeCfg: io_dtype: Type[cutlass.Numeric] state_dtype: Type[cutlass.Numeric] + gate_dtype: Type[cutlass.Numeric] use_initial_state: bool store_final_state: bool enable_checkpoints: bool @@ -1885,6 +1912,7 @@ class KdaRecomputeCfg: k_cosize: int = 0 v_cosize: int = 0 gate_cosize: int = 0 + gate_stage_elems: int = 0 beta_cosize: int = 0 k_inv_cosize: int = 0 k_decay_cosize: int = 0 @@ -1901,6 +1929,7 @@ class KdaRecomputeCfg: def build_cfg( io_dtype: Type[cutlass.Numeric], state_dtype: Type[cutlass.Numeric], + gate_dtype: Type[cutlass.Numeric], *, use_initial_state: bool, store_final_state: bool, @@ -1922,6 +1951,7 @@ def build_cfg( cfg = KdaRecomputeCfg( io_dtype=io_dtype, state_dtype=state_dtype, + gate_dtype=gate_dtype, use_initial_state=use_initial_state, store_final_state=store_final_state, enable_checkpoints=enable_checkpoints, @@ -1956,6 +1986,7 @@ def build_cfg( cfg.k_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t cfg.v_cosize = cfg.smem_raw_stages * cfg.d_v * cfg.b_t cfg.gate_cosize = cfg.smem_raw_stages * cfg.d_k * cfg.b_t + cfg.gate_stage_elems = (cfg.d_k * cfg.b_t) * (4 // (cfg.gate_dtype.width // 8)) cfg.beta_cosize = cfg.smem_raw_stages * cfg.b_t cfg.k_inv_cosize = cfg.smem_decay_stages * cfg.b_t * cfg.d_k cfg.k_decay_cosize = cfg.smem_decay_stages * cfg.d_k * cfg.b_t @@ -1964,7 +1995,7 @@ def build_cfg( cfg.intermediate_cosize = cfg.smem_intermediate_stages * 2 * cfg.b_t * cfg.b_t cfg.tma_k_bytes = cfg.d_k * cfg.b_t * (cfg.io_dtype.width // 8) cfg.tma_v_bytes = cfg.d_v * cfg.b_t * (cfg.io_dtype.width // 8) - cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * 4 + cfg.tma_gate_bytes = cfg.d_k * cfg.b_t * (cfg.gate_dtype.width // 8) return cfg @@ -2054,6 +2085,9 @@ def frost_kda_recompute_prologue( consumers' scheduler rings via :func:`order_body`; it then builds the per-batch TMA-descriptor arrays via :func:`build_descs_body`, one warp per array (the extra warps only take part in the order phase).""" + if cutlass.const_expr(USE_PDL): + wait_on_dependent_grids() + launch_dependent_grids() tidx, _, _ = cute.arch.thread_idx() tidx = cutlass.Int32(tidx) widx = tidx // cutlass.Int32(32) @@ -2141,7 +2175,8 @@ def prologue( swz = cuda.TensorMapSwizzle.s128b base_k = cuda.create_tensor_map_tiled_from_view(k_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_v = cuda.create_tensor_map_tiled_from_view(v_headed, box_dims=(tma_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) - base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(32, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) + gate_granu_elems = 128 // (gate.element_type.width // 8) + base_gate = cuda.create_tensor_map_tiled_from_view(gate_headed, box_dims=(gate_granu_elems, 1, b_t), stride_order=(0, 1, 2), swizzle=swz) base_checkpoint = base_gate if cutlass.const_expr(state_checkpoints is not None): @@ -2178,7 +2213,7 @@ def prologue( cutlass.Int32(gate.stride[0]), cutlass.Int32(state_checkpoints.stride[0] if state_checkpoints is not None else 0), checkpoint_every_n, - ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream) + ).launch(grid=(1, 1, 1), block=(ORDER_THREADS, 1, 1), stream=stream, use_pdl=USE_PDL) # ---- Torch adapter / host-side compilation ------------------------------------------- @@ -2188,7 +2223,9 @@ def prologue( def get_compiled_cache( io_dtype_str: str, state_dtype_str: str, + gate_dtype_str: str, cu_dtype_str: str, + beta_dtype_str: str, HO: int, HK: int, HV: int, @@ -2210,6 +2247,7 @@ def get_compiled_cache( def compile( io_dtype, state_dtype, + gate_dtype, use_initial_state: bool, store_final_state: bool, enable_checkpoints: bool, @@ -2243,6 +2281,7 @@ def compile( cfg = build_cfg( io_dtype, state_dtype, + gate_dtype, use_initial_state=use_initial_state, store_final_state=store_final_state, enable_checkpoints=enable_checkpoints, @@ -2315,7 +2354,8 @@ def chunk_kda_recompute_sm100( Args: k: ``(total_tokens, HK, DK)`` float16/bfloat16 v: ``(total_tokens, HV, DV)`` float16/bfloat16 - gate: ``(total_tokens, HO, DK)`` float32. Natural-log decay unless + gate: ``(total_tokens, HO, DK)`` float32/bfloat16/float16 (16-bit is widened to fp32 on the SMEM read). + Natural-log decay unless ``safe_gate``, which applies the safe-gate transform ``lower_bound * sigmoid(exp(a_log) * (gate + dt_bias))``. beta: ``(total_tokens, HO)``. Post-sigmoid float32, or io-dtype @@ -2395,7 +2435,9 @@ def chunk_kda_recompute_sm100( cache = get_compiled_cache( str(k.dtype), str(state_dtype_src), + str(gate.dtype), str(cu_seqlens.dtype), + str(beta.dtype), HO, HK, HV, @@ -2414,6 +2456,7 @@ def chunk_kda_recompute_sm100( if "compiled" not in cache: io_dtype = get_dtype(k.dtype) state_dtype = get_dtype(state_dtype_src) + gate_dtype = get_dtype(gate.dtype) k_cute = from_dlpack(k, assumed_align=16).mark_layout_dynamic(leading_dim=2) v_cute = from_dlpack(v, assumed_align=16).mark_layout_dynamic(leading_dim=2) gate_cute = from_dlpack(gate, assumed_align=16).mark_layout_dynamic(leading_dim=2) @@ -2443,6 +2486,7 @@ def chunk_kda_recompute_sm100( cache["compiled"] = compile( io_dtype, state_dtype, + gate_dtype, use_initial_state, store_final_state, enable_checkpoints, diff --git a/python/cudnn/linear_attention/ops/gdn.py b/python/cudnn/linear_attention/ops/gdn.py index cc177f4df7..42d035cd0c 100644 --- a/python/cudnn/linear_attention/ops/gdn.py +++ b/python/cudnn/linear_attention/ops/gdn.py @@ -108,8 +108,10 @@ def torch_dtype_to_cudnn(dtype: torch.dtype): def check_dtype(name, t, want) -> None: - if t.dtype != want: - raise TypeError(f"gated_delta_net: {name} must be {want} (kernel-native; callers convert), got {t.dtype}") + wants = want if isinstance(want, tuple) else (want,) + if t.dtype not in wants: + names = " or ".join(str(w) for w in wants) + raise TypeError(f"gated_delta_net: {name} must be {names} (kernel-native; callers convert), got {t.dtype}") def make_fprop_cache_key( @@ -126,13 +128,15 @@ def make_fprop_cache_key( k_shape, v_shape, cu_dtype, + g_dtype, + beta_dtype, + state_dtype, scale, output_final_state, use_qk_l2norm, batch_invariant, use_beta_sigmoid, safe_gate, - has_initial_state, checkpoint, device, plan_name, @@ -152,13 +156,15 @@ def make_fprop_cache_key( k_shape, v_shape, cu_dtype, + g_dtype, + beta_dtype, + state_dtype, float(scale), bool(output_final_state), bool(use_qk_l2norm), bool(batch_invariant), bool(use_beta_sigmoid), bool(safe_gate), - bool(has_initial_state), checkpoint, device, plan_name, @@ -180,8 +186,10 @@ def make_bprop_cache_key( k_shape, v_shape, cu_dtype, - has_initial_state, - has_d_final_state, + g_dtype, + beta_dtype, + state_dtype, + dstate_in_dtype, checkpoint_rows, scale, use_qk_l2norm, @@ -207,8 +215,10 @@ def make_bprop_cache_key( k_shape, v_shape, cu_dtype, - bool(has_initial_state), - bool(has_d_final_state), + g_dtype, + beta_dtype, + state_dtype, + dstate_in_dtype, checkpoint_rows, float(scale), bool(use_qk_l2norm), @@ -338,11 +348,8 @@ def gdn_fwd( if cu_seqlens.dtype not in (torch.int32, torch.int64): raise ValueError(f"gated_delta_net: cu_seqlens must be int32 or int64; got {cu_seqlens.dtype}") cu = cu_seqlens - check_dtype("g", g, torch.float32) - if use_beta_sigmoid_in_kernel: - check_dtype("beta", beta, q.dtype) - else: - check_dtype("beta", beta, torch.float32) + check_dtype("g", g, (torch.float32, torch.bfloat16, torch.float16)) + check_dtype("beta", beta, q.dtype if use_beta_sigmoid_in_kernel else (torch.float32, q.dtype)) if safe_gate: if a_log is None or dt_bias is None: raise ValueError("gated_delta_net: safe_gate requires a_log and dt_bias") @@ -351,7 +358,7 @@ def gdn_fwd( elif a_log is not None or dt_bias is not None: raise ValueError("gated_delta_net: a_log/dt_bias require safe_gate=True") if initial_state is not None: - check_dtype("initial_state", initial_state, torch.float32) + check_dtype("initial_state", initial_state, (torch.float32, torch.bfloat16)) if initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") for tensor_name, tensor in ( @@ -366,9 +373,8 @@ def gdn_fwd( ): if tensor is not None and tensor.device != device: raise ValueError(f"gated_delta_net: {tensor_name} must be on q's device ({device}); got {tensor.device}") - g32 = g - beta32 = beta state0 = initial_state if initial_state is not None else None + state_out_dtype = state0.dtype if state0 is not None else torch.float32 checkpoint = int(checkpoint_every_n_tokens) cache_key = make_fprop_cache_key( @@ -385,13 +391,15 @@ def gdn_fwd( tuple(k.shape), tuple(v.shape), cu_seqlens.dtype, + g.dtype, + beta.dtype, + state0.dtype if state0 is not None else None, scale, output_final_state, use_qk_l2norm_in_kernel, batch_invariant, use_beta_sigmoid_in_kernel, safe_gate, - state0 is not None, checkpoint, device, plan_name, @@ -406,9 +414,9 @@ def gdn_fwd( K, V, torch_dtype_to_cudnn(q.dtype), - cudnn.data_type.FLOAT, + torch_dtype_to_cudnn(g.dtype), torch_dtype_to_cudnn(beta.dtype), - cudnn.data_type.FLOAT if state0 is not None else None, + torch_dtype_to_cudnn(state0.dtype) if state0 is not None else None, torch_dtype_to_cudnn(cu_seqlens.dtype), float(scale), bool(output_final_state), @@ -428,8 +436,8 @@ def gdn_fwd( t["q"]: q, t["k"]: k, t["v"]: v, - t["g"]: g32, - t["beta"]: beta32, + t["g"]: g, + t["beta"]: beta, t["cu"]: cu, t["O"]: o, } @@ -438,9 +446,9 @@ def gdn_fwd( if safe_gate: variant_pack[t["a_log"]] = a_log variant_pack[t["dt_bias"]] = dt_bias - final_state = torch.empty(0, dtype=torch.float32, device=device) + final_state = torch.empty(0, dtype=state_out_dtype, device=device) if output_final_state: - final_state = torch.empty(N, HO, V, K, dtype=torch.float32, device=device) + final_state = torch.empty(N, HO, V, K, dtype=state_out_dtype, device=device) variant_pack[t["fs"]] = final_state state_checkpoints = torch.empty(0, dtype=q.dtype, device=device) if checkpoint > 0: @@ -483,7 +491,8 @@ def gdn_fwd_fake( if initial_state is not None and initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") o = q.new_empty(total, HO, V) - final = q.new_empty((N, HO, V, K) if output_final_state else (0,), dtype=torch.float32) + state_dtype = initial_state.dtype if initial_state is not None else torch.float32 + final = q.new_empty((N, HO, V, K) if output_final_state else (0,), dtype=state_dtype) if checkpoint_every_n_tokens > 0: total_checkpoints = max(total // int(checkpoint_every_n_tokens) + N, 1) state_checkpoints = q.new_empty(total_checkpoints, HO, V, K) @@ -616,12 +625,7 @@ def gdn_bwd( ``state_checkpoints`` is the forward's per-chunk state series (io dtype, chunk cadence); when given, the engine consumes it instead of running the checkpoint recompute pass. Returns ``(dq, dk, dv, dg, dbeta, - d_initial_state, d_a_log, d_dt_bias)``; ``d_initial_state`` is a - zero-size tensor when ``initial_state`` is ``None``, and ``d_a_log`` / - ``d_dt_bias`` are zero-size tensors unless ``safe_gate``. With - ``safe_gate``, ``g`` is the raw logits and ``dg`` is the raw-logit - gradient; with ``use_beta_sigmoid_in_kernel``, ``beta`` is io-dtype - logits and ``dbeta`` is the raw-logit gradient. + d_initial_state, d_a_log, d_dt_bias)``. """ total, H, K = q.shape if 0 in dO.stride(): @@ -637,11 +641,8 @@ def gdn_bwd( if cu_seqlens.dtype not in (torch.int32, torch.int64): raise ValueError(f"gated_delta_net: cu_seqlens must be int32 or int64; got {cu_seqlens.dtype}") cu = cu_seqlens - check_dtype("g", g, torch.float32) - if use_beta_sigmoid_in_kernel: - check_dtype("beta", beta, q.dtype) - else: - check_dtype("beta", beta, torch.float32) + check_dtype("g", g, (torch.float32, torch.bfloat16, torch.float16)) + check_dtype("beta", beta, q.dtype if use_beta_sigmoid_in_kernel else (torch.float32, q.dtype)) if safe_gate: if a_log is None or dt_bias is None: raise ValueError("gated_delta_net: safe_gate requires a_log and dt_bias") @@ -650,9 +651,14 @@ def gdn_bwd( elif a_log is not None or dt_bias is not None: raise ValueError("gated_delta_net: a_log/dt_bias require safe_gate=True") if initial_state is not None: - check_dtype("initial_state", initial_state, torch.float32) + check_dtype("initial_state", initial_state, (torch.float32, torch.bfloat16)) if initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") + dstate_dtype = initial_state.dtype if initial_state is not None else torch.float32 + if d_final_state is not None: + check_dtype("d_final_state", d_final_state, (torch.float32, torch.bfloat16)) + if d_final_state.dtype != dstate_dtype: + raise TypeError(f"gated_delta_net: d_final_state must be {dstate_dtype} (one state dtype per kernel)") if state_checkpoints is not None: check_dtype("state_checkpoints", state_checkpoints, q.dtype) for tensor_name, tensor in ( @@ -669,11 +675,7 @@ def gdn_bwd( ): if tensor is not None and tensor.device != device: raise ValueError(f"gated_delta_net: {tensor_name} must be on q's device ({device}); got {tensor.device}") - g32 = g - beta32 = beta state0 = initial_state if initial_state is not None else None - if d_final_state is not None: - check_dtype("d_final_state", d_final_state, torch.float32) dstate_in = d_final_state if d_final_state is not None else None cache_key = make_bprop_cache_key( @@ -691,8 +693,10 @@ def gdn_bwd( tuple(k.shape), tuple(v.shape), cu_seqlens.dtype, - state0 is not None, - dstate_in is not None, + g.dtype, + beta.dtype, + state0.dtype if state0 is not None else None, + dstate_in.dtype if dstate_in is not None else None, state_checkpoints.shape[0] if state_checkpoints is not None else None, scale, use_qk_l2norm_in_kernel, @@ -712,10 +716,10 @@ def gdn_bwd( K, V, torch_dtype_to_cudnn(q.dtype), - cudnn.data_type.FLOAT, + torch_dtype_to_cudnn(g.dtype), torch_dtype_to_cudnn(beta.dtype), - cudnn.data_type.FLOAT if state0 is not None else None, - cudnn.data_type.FLOAT if dstate_in is not None else None, + torch_dtype_to_cudnn(state0.dtype) if state0 is not None else None, + torch_dtype_to_cudnn(dstate_in.dtype) if dstate_in is not None else None, torch_dtype_to_cudnn(cu_seqlens.dtype), state_checkpoints.shape[0] if state_checkpoints is not None else None, float(scale), @@ -732,26 +736,26 @@ def gdn_bwd( dq = torch.empty(total, H, K, dtype=q.dtype, device=device) dk = torch.empty(total, HK, K, dtype=q.dtype, device=device) dv = torch.empty(total, HV, V, dtype=q.dtype, device=device) - dg32 = torch.empty(total, HO, dtype=torch.float32, device=device) + dg = torch.empty(total, HO, dtype=g.dtype, device=device) dbeta = torch.empty(total, HO, dtype=beta.dtype, device=device) variant_pack = { t["q"]: q, t["k"]: k, t["v"]: v, - t["g"]: g32, - t["beta"]: beta32, + t["g"]: g, + t["beta"]: beta, t["cu"]: cu, t["dO"]: dO, t["dQ"]: dq, t["dK"]: dk, t["dV"]: dv, - t["dG"]: dg32, + t["dG"]: dg, t["dBeta"]: dbeta, } dstate0 = None if state0 is not None: variant_pack[t["state0"]] = state0 - dstate0 = torch.empty_like(state0) + dstate0 = torch.empty(state0.shape, dtype=dstate_dtype, device=device) variant_pack[t["dstate0"]] = dstate0 if dstate_in is not None: variant_pack[t["dfs"]] = dstate_in @@ -768,8 +772,8 @@ def gdn_bwd( variant_pack[t["d_dt_bias"]] = d_dt_bias graph.execute(variant_pack, workspace=graph_workspace(graph, device), handle=get_handle(device)) if dstate0 is None: - dstate0 = torch.empty(0, dtype=torch.float32, device=device) - return dq, dk, dv, dg32, dbeta, dstate0, d_a_log, d_dt_bias + dstate0 = torch.empty(0, dtype=dstate_dtype, device=device) + return dq, dk, dv, dg, dbeta, dstate0, d_a_log, d_dt_bias @gdn_bwd.register_fake @@ -795,7 +799,10 @@ def gdn_bwd_fake( ): if safe_gate and (a_log is None or dt_bias is None): raise ValueError("gated_delta_net: safe_gate requires a_log and dt_bias") - dstate0 = torch.empty_like(initial_state) if initial_state is not None else q.new_empty(0, dtype=torch.float32) + dstate_dtype = initial_state.dtype if initial_state is not None else torch.float32 + if d_final_state is not None and d_final_state.dtype != dstate_dtype: + raise TypeError(f"gated_delta_net: d_final_state must be {dstate_dtype} (one state dtype per kernel)") + dstate0 = initial_state.new_empty(initial_state.shape, dtype=dstate_dtype) if initial_state is not None else q.new_empty(0, dtype=dstate_dtype) d_a_log = torch.empty_like(a_log) if safe_gate else q.new_empty(0, dtype=torch.float32) d_dt_bias = torch.empty_like(dt_bias) if safe_gate else q.new_empty(0, dtype=torch.float32) return ( @@ -952,19 +959,22 @@ def gated_delta_net( A dense batch of N equal-length sequences is expressed as ``cu_seqlens = [0, T, 2T, ...]`` over the flattened tokens. - Dtypes are kernel-native and strict (callers convert): ``g`` and the - states are float32; ``final_state``, ``dG`` and ``d_initial_state`` are - returned in float32. ``beta`` and ``dBeta`` are float32, or io dtype - under ``use_beta_sigmoid_in_kernel``. + Dtypes are kernel-native and strict (callers convert). ``g`` is float32, + bfloat16 or float16 and ``dG`` comes back in the same dtype. ``beta`` and + ``dBeta`` are float32 or the io dtype (io-dtype logits under + ``use_beta_sigmoid_in_kernel``). ``initial_state`` is float32 or bfloat16 + and ``final_state`` and the state gradients (``d_final_state``, + ``d_initial_state``) follow it. Args: g: log-space scalar decay per token (``alpha = exp(g) in (0, 1]``), or raw pre-activation logits when ``safe_gate=True``. - beta: per-token write strength (float32), or io-dtype logits when + beta: per-token write strength (float32 or the io dtype), or io-dtype logits when ``use_beta_sigmoid_in_kernel=True``. - cu_seqlens: ``[N+1]`` int32 sequence boundaries over the packed tokens. + cu_seqlens: ``[N+1]`` int32/int64 sequence boundaries over the packed tokens. scale: attention scale applied to ``q``. Defaults to ``1 / sqrt(K)``. - initial_state: optional recurrent state (otherwise zero). + initial_state: optional recurrent state (otherwise zero); float32 or + bfloat16, and ``final_state`` comes back in the same dtype. output_final_state: if ``True``, also return the per-sequence state after the last token. use_qk_l2norm_in_kernel: if ``True``, L2-normalize the Q/K rows inside diff --git a/python/cudnn/linear_attention/ops/gdn2.py b/python/cudnn/linear_attention/ops/gdn2.py index f22a4a563e..69021e185b 100644 --- a/python/cudnn/linear_attention/ops/gdn2.py +++ b/python/cudnn/linear_attention/ops/gdn2.py @@ -107,8 +107,10 @@ def torch_dtype_to_cudnn(dtype: torch.dtype): def check_dtype(name, t, want) -> None: - if t.dtype != want: - raise TypeError(f"gated_delta_net_v2: {name} must be {want} (kernel-native; callers convert), got {t.dtype}") + wants = want if isinstance(want, tuple) else (want,) + if t.dtype not in wants: + names = " or ".join(str(w) for w in wants) + raise TypeError(f"gated_delta_net_v2: {name} must be {names} (kernel-native; callers convert), got {t.dtype}") def make_fprop_cache_key( @@ -125,6 +127,7 @@ def make_fprop_cache_key( k_shape, v_shape, cu_dtype, + g_dtype, scale, output_final_state, use_qk_l2norm, @@ -133,7 +136,7 @@ def make_fprop_cache_key( beta_guard, safe_gate, gate_lower_bound, - has_initial_state, + state_dtype, checkpoint, device, plan_name, @@ -153,6 +156,7 @@ def make_fprop_cache_key( k_shape, v_shape, cu_dtype, + g_dtype, float(scale), bool(output_final_state), bool(use_qk_l2norm), @@ -161,7 +165,7 @@ def make_fprop_cache_key( bool(beta_guard), bool(safe_gate), float(gate_lower_bound) if gate_lower_bound is not None else None, - bool(has_initial_state), + state_dtype, checkpoint, device, plan_name, @@ -183,6 +187,7 @@ def make_bprop_cache_key( k_shape, v_shape, cu_dtype, + g_dtype, state_dtype, dstate_in_dtype, checkpoint_rows, @@ -212,6 +217,7 @@ def make_bprop_cache_key( k_shape, v_shape, cu_dtype, + g_dtype, state_dtype, dstate_in_dtype, checkpoint_rows, @@ -356,7 +362,7 @@ def gdn2_fwd( if cu_seqlens.dtype not in (torch.int32, torch.int64): raise ValueError(f"gated_delta_net_v2: cu_seqlens must be int32 or int64; got {cu_seqlens.dtype}") cu = cu_seqlens - check_dtype("g", g, torch.float32) + check_dtype("g", g, (torch.float32, torch.bfloat16, torch.float16)) check_dtype("beta", beta, q.dtype) check_dtype("w", w, q.dtype) if safe_gate: @@ -367,10 +373,9 @@ def gdn2_fwd( elif a_log is not None or dt_bias is not None: raise ValueError("gated_delta_net_v2: a_log/dt_bias require safe_gate=True") if initial_state is not None: - check_dtype("initial_state", initial_state, torch.float32) + check_dtype("initial_state", initial_state, (torch.float32, torch.bfloat16)) if initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") - g32 = g beta_io = beta w_io = w for tensor_name, tensor in ( @@ -403,6 +408,7 @@ def gdn2_fwd( tuple(k.shape), tuple(v.shape), cu_seqlens.dtype, + g.dtype, scale, output_final_state, use_qk_l2norm_in_kernel, @@ -411,7 +417,7 @@ def gdn2_fwd( beta_guard, safe_gate, gate_lower_bound, - state0 is not None, + state0.dtype if state0 is not None else None, checkpoint, device, plan_name, @@ -426,9 +432,9 @@ def gdn2_fwd( K, V, torch_dtype_to_cudnn(q.dtype), - cudnn.data_type.FLOAT, + torch_dtype_to_cudnn(g.dtype), torch_dtype_to_cudnn(q.dtype), - cudnn.data_type.FLOAT if state0 is not None else None, + torch_dtype_to_cudnn(state0.dtype) if state0 is not None else None, torch_dtype_to_cudnn(cu_seqlens.dtype), float(scale), bool(output_final_state), @@ -449,7 +455,7 @@ def gdn2_fwd( t["q"]: q, t["k"]: k, t["v"]: v, - t["g"]: g32, + t["g"]: g, t["beta"]: beta_io, t["w"]: w_io, t["cu"]: cu, @@ -460,9 +466,10 @@ def gdn2_fwd( if safe_gate: variant_pack[t["a_log"]] = a_log variant_pack[t["dt_bias"]] = dt_bias - final_state = torch.empty(0, dtype=torch.float32, device=device) + state_out_dtype = state0.dtype if state0 is not None else torch.float32 + final_state = torch.empty(0, dtype=state_out_dtype, device=device) if output_final_state: - final_state = torch.empty(N, HO, V, K, dtype=torch.float32, device=device) + final_state = torch.empty(N, HO, V, K, dtype=state_out_dtype, device=device) variant_pack[t["fs"]] = final_state state_checkpoints = torch.empty(0, dtype=q.dtype, device=device) if checkpoint > 0: @@ -508,7 +515,8 @@ def gdn2_fwd_fake( if initial_state is not None and initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") o = q.new_empty(total, HO, V) - final = q.new_empty((N, HO, V, K) if output_final_state else (0,), dtype=torch.float32) + state_dtype = initial_state.dtype if initial_state is not None else torch.float32 + final = q.new_empty((N, HO, V, K) if output_final_state else (0,), dtype=state_dtype) if checkpoint_every_n_tokens > 0: total_checkpoints = max(total // int(checkpoint_every_n_tokens) + N, 1) state_checkpoints = q.new_empty(total_checkpoints, HO, V, K) @@ -652,12 +660,7 @@ def gdn2_bwd( ``state_checkpoints`` is the forward's per-chunk state series (io dtype, chunk cadence); when given, the engine consumes it instead of running the checkpoint recompute pass. Returns ``(dq, dk, dv, dg, dbeta, dw, - d_initial_state, d_a_log, d_dt_bias)``; ``d_initial_state`` is a - zero-size tensor when ``initial_state`` is ``None``, and ``d_a_log`` / - ``d_dt_bias`` are zero-size tensors unless ``safe_gate``. With - ``safe_gate``, ``g`` is the raw logits and ``dg`` is the raw-logit - gradient; with ``use_beta_sigmoid_in_kernel``, ``beta`` is io-dtype - logits and ``dbeta`` is the raw-logit gradient. + d_initial_state, d_a_log, d_dt_bias)``. """ total, H, K = q.shape if 0 in dO.stride(): @@ -674,7 +677,7 @@ def gdn2_bwd( if cu_seqlens.dtype not in (torch.int32, torch.int64): raise ValueError(f"gated_delta_net_v2: cu_seqlens must be int32 or int64; got {cu_seqlens.dtype}") cu = cu_seqlens - check_dtype("g", g, torch.float32) + check_dtype("g", g, (torch.float32, torch.bfloat16, torch.float16)) check_dtype("beta", beta, q.dtype) check_dtype("w", w, q.dtype) if safe_gate: @@ -685,11 +688,14 @@ def gdn2_bwd( elif a_log is not None or dt_bias is not None: raise ValueError("gated_delta_net_v2: a_log/dt_bias require safe_gate=True") if initial_state is not None: - check_dtype("initial_state", initial_state, torch.float32) + check_dtype("initial_state", initial_state, (torch.float32, torch.bfloat16)) if initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") + dstate_dtype = initial_state.dtype if initial_state is not None else torch.float32 if d_final_state is not None: - check_dtype("d_final_state", d_final_state, torch.float32) + check_dtype("d_final_state", d_final_state, (torch.float32, torch.bfloat16)) + if d_final_state.dtype != dstate_dtype: + raise TypeError(f"gated_delta_net_v2: d_final_state must be {dstate_dtype} (one state dtype per kernel)") if state_checkpoints is not None: check_dtype("state_checkpoints", state_checkpoints, q.dtype) for tensor_name, tensor in ( @@ -725,6 +731,7 @@ def gdn2_bwd( tuple(k.shape), tuple(v.shape), cu_seqlens.dtype, + g.dtype, state0.dtype if state0 is not None else None, dstate_in.dtype if dstate_in is not None else None, state_checkpoints.shape[0] if state_checkpoints is not None else None, @@ -748,7 +755,7 @@ def gdn2_bwd( K, V, torch_dtype_to_cudnn(q.dtype), - cudnn.data_type.FLOAT, + torch_dtype_to_cudnn(g.dtype), torch_dtype_to_cudnn(q.dtype), torch_dtype_to_cudnn(state0.dtype) if state0 is not None else None, torch_dtype_to_cudnn(dstate_in.dtype) if dstate_in is not None else None, @@ -769,7 +776,7 @@ def gdn2_bwd( dq = torch.empty(total, H, K, dtype=q.dtype, device=device) dk = torch.empty(total, HK, K, dtype=q.dtype, device=device) dv = torch.empty(total, HV, V, dtype=q.dtype, device=device) - dg = torch.empty(total, HO, K, dtype=torch.float32, device=device) + dg = torch.empty(total, HO, K, dtype=g.dtype, device=device) dbeta = torch.empty(total, HO, K, dtype=beta.dtype, device=device) dw = torch.empty(total, HO, V, dtype=w.dtype, device=device) variant_pack = { @@ -791,7 +798,7 @@ def gdn2_bwd( dstate0 = None if state0 is not None: variant_pack[t["state0"]] = state0 - dstate0 = torch.empty_like(state0) + dstate0 = torch.empty(state0.shape, dtype=dstate_dtype, device=device) variant_pack[t["dstate0"]] = dstate0 if dstate_in is not None: variant_pack[t["dfs"]] = dstate_in @@ -808,7 +815,7 @@ def gdn2_bwd( variant_pack[t["d_dt_bias"]] = d_dt_bias graph.execute(variant_pack, workspace=graph_workspace(graph, device), handle=get_handle(device)) if dstate0 is None: - dstate0 = torch.empty(0, dtype=torch.float32, device=device) + dstate0 = torch.empty(0, dtype=dstate_dtype, device=device) return dq, dk, dv, dg, dbeta, dw, dstate0, d_a_log, d_dt_bias @@ -838,14 +845,17 @@ def gdn2_bwd_fake( ): if safe_gate and (a_log is None or dt_bias is None): raise ValueError("gated_delta_net_v2: safe_gate requires a_log and dt_bias") - dstate0 = torch.empty_like(initial_state) if initial_state is not None else q.new_empty(0, dtype=torch.float32) + dstate_dtype = initial_state.dtype if initial_state is not None else torch.float32 + if d_final_state is not None and d_final_state.dtype != dstate_dtype: + raise TypeError(f"gated_delta_net_v2: d_final_state must be {dstate_dtype} (one state dtype per kernel)") + dstate0 = initial_state.new_empty(initial_state.shape, dtype=dstate_dtype) if initial_state is not None else q.new_empty(0, dtype=dstate_dtype) d_a_log = torch.empty_like(a_log) if safe_gate else q.new_empty(0, dtype=torch.float32) d_dt_bias = torch.empty_like(dt_bias) if safe_gate else q.new_empty(0, dtype=torch.float32) return ( torch.empty_like(q), torch.empty_like(k), torch.empty_like(v), - g.new_empty(g.shape, dtype=torch.float32), + torch.empty_like(g), torch.empty_like(beta), torch.empty_like(w), dstate0, @@ -1011,15 +1021,20 @@ def gated_delta_net_v2( A dense batch of N equal-length sequences is expressed as ``cu_seqlens = [0, T, 2T, ...]`` over the flattened tokens. + ``g`` is float32, bfloat16 or float16 and ``dG`` comes back in the same + dtype. ``initial_state`` is float32 or bfloat16 and ``final_state`` and + the state gradients follow it. + Args: g: per-key-channel log-space decay (``alpha = exp(g)``), or raw pre-activation logits when ``safe_gate=True``. beta: per-key erase gate (io dtype, post-activation), or io-dtype logits when ``use_beta_sigmoid_in_kernel=True``. w: per-value write gate (io dtype, post-activation). - cu_seqlens: ``[N+1]`` int32 sequence boundaries over the packed tokens. + cu_seqlens: ``[N+1]`` int32/int64 sequence boundaries over the packed tokens. scale: attention scale applied to ``q``. Defaults to ``1 / sqrt(K)``. - initial_state: optional recurrent state (otherwise zero). + initial_state: optional recurrent state (otherwise zero); float32 or + bfloat16, and ``final_state`` comes back in the same dtype. output_final_state: if ``True``, also return the per-sequence state after the last token. use_qk_l2norm_in_kernel: if ``True``, L2-normalize the Q/K rows inside diff --git a/python/cudnn/linear_attention/ops/kda.py b/python/cudnn/linear_attention/ops/kda.py index 3ef479c36d..ddbd17591b 100644 --- a/python/cudnn/linear_attention/ops/kda.py +++ b/python/cudnn/linear_attention/ops/kda.py @@ -110,8 +110,10 @@ def torch_dtype_to_cudnn(dtype: torch.dtype): def check_dtype(name, t, want) -> None: - if t.dtype != want: - raise TypeError(f"kimi_delta_attention: {name} must be {want} (kernel-native; callers convert), got {t.dtype}") + wants = want if isinstance(want, tuple) else (want,) + if t.dtype not in wants: + names = " or ".join(str(w) for w in wants) + raise TypeError(f"kimi_delta_attention: {name} must be {names} (kernel-native; callers convert), got {t.dtype}") def make_fprop_cache_key( @@ -128,6 +130,9 @@ def make_fprop_cache_key( k_shape, v_shape, cu_dtype, + g_dtype, + beta_dtype, + state_dtype, scale, output_final_state, use_qk_l2norm, @@ -135,7 +140,6 @@ def make_fprop_cache_key( use_beta_sigmoid, safe_gate, gate_lower_bound, - has_initial_state, checkpoint, device, plan_name, @@ -155,6 +159,9 @@ def make_fprop_cache_key( k_shape, v_shape, cu_dtype, + g_dtype, + beta_dtype, + state_dtype, float(scale), bool(output_final_state), bool(use_qk_l2norm), @@ -162,7 +169,6 @@ def make_fprop_cache_key( bool(use_beta_sigmoid), bool(safe_gate), float(gate_lower_bound) if gate_lower_bound is not None else None, - bool(has_initial_state), checkpoint, device, plan_name, @@ -352,11 +358,8 @@ def kda_fwd( if cu_seqlens.dtype not in (torch.int32, torch.int64): raise ValueError(f"kimi_delta_attention: cu_seqlens must be int32 or int64; got {cu_seqlens.dtype}") cu = cu_seqlens - check_dtype("g", g, torch.float32) - if use_beta_sigmoid_in_kernel: - check_dtype("beta", beta, q.dtype) - else: - check_dtype("beta", beta, torch.float32) + check_dtype("g", g, (torch.float32, torch.bfloat16, torch.float16)) + check_dtype("beta", beta, q.dtype if use_beta_sigmoid_in_kernel else (torch.float32, q.dtype)) if safe_gate: if a_log is None or dt_bias is None: raise ValueError("kimi_delta_attention: safe_gate requires a_log and dt_bias") @@ -365,7 +368,7 @@ def kda_fwd( elif a_log is not None or dt_bias is not None: raise ValueError("kimi_delta_attention: a_log/dt_bias require safe_gate=True") if initial_state is not None: - check_dtype("initial_state", initial_state, torch.float32) + check_dtype("initial_state", initial_state, (torch.float32, torch.bfloat16)) if initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") for tensor_name, tensor in ( @@ -397,6 +400,9 @@ def kda_fwd( tuple(k.shape), tuple(v.shape), cu_seqlens.dtype, + g.dtype, + beta.dtype, + state0.dtype if state0 is not None else None, scale, output_final_state, use_qk_l2norm_in_kernel, @@ -404,7 +410,6 @@ def kda_fwd( use_beta_sigmoid_in_kernel, safe_gate, gate_lower_bound, - state0 is not None, checkpoint, device, plan_name, @@ -419,9 +424,9 @@ def kda_fwd( K, V, torch_dtype_to_cudnn(q.dtype), - cudnn.data_type.FLOAT, + torch_dtype_to_cudnn(g.dtype), torch_dtype_to_cudnn(beta.dtype), - cudnn.data_type.FLOAT if state0 is not None else None, + torch_dtype_to_cudnn(state0.dtype) if state0 is not None else None, torch_dtype_to_cudnn(cu_seqlens.dtype), float(scale), bool(output_final_state), @@ -451,9 +456,10 @@ def kda_fwd( if safe_gate: variant_pack[t["a_log"]] = a_log variant_pack[t["dt_bias"]] = dt_bias - final_state = torch.empty(0, dtype=torch.float32, device=device) + state_out_dtype = state0.dtype if state0 is not None else torch.float32 + final_state = torch.empty(0, dtype=state_out_dtype, device=device) if output_final_state: - final_state = torch.empty(N, HO, V, K, dtype=torch.float32, device=device) + final_state = torch.empty(N, HO, V, K, dtype=state_out_dtype, device=device) variant_pack[t["fs"]] = final_state state_checkpoints = torch.empty(0, dtype=q.dtype, device=device) if checkpoint > 0: @@ -497,7 +503,8 @@ def kda_fwd_fake( if initial_state is not None and initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") o = q.new_empty(total, HO, V) - final = q.new_empty((N, HO, V, K) if output_final_state else (0,), dtype=torch.float32) + state_dtype = initial_state.dtype if initial_state is not None else torch.float32 + final = q.new_empty((N, HO, V, K) if output_final_state else (0,), dtype=state_dtype) if checkpoint_every_n_tokens > 0: total_checkpoints = max(total // int(checkpoint_every_n_tokens) + N, 1) state_checkpoints = q.new_empty(total_checkpoints, HO, V, K) @@ -633,12 +640,7 @@ def kda_bwd( ``state_checkpoints`` is the forward's per-chunk state series (io dtype, chunk cadence); when given, the engine consumes it instead of running the checkpoint recompute pass. Returns ``(dq, dk, dv, dg, dbeta, - d_initial_state, d_a_log, d_dt_bias)``; ``d_initial_state`` is a - zero-size tensor when ``initial_state`` is ``None``, and ``d_a_log`` / - ``d_dt_bias`` are zero-size tensors unless ``safe_gate``. With - ``safe_gate``, ``g`` is the raw logits and ``dg`` is the raw-logit - gradient; with ``use_beta_sigmoid_in_kernel``, ``beta`` is io-dtype - logits and ``dbeta`` is the raw-logit gradient. + d_initial_state, d_a_log, d_dt_bias)``. """ total, H, K = q.shape if 0 in dO.stride(): @@ -655,11 +657,8 @@ def kda_bwd( if cu_seqlens.dtype not in (torch.int32, torch.int64): raise ValueError(f"kimi_delta_attention: cu_seqlens must be int32 or int64; got {cu_seqlens.dtype}") cu = cu_seqlens - check_dtype("g", g, torch.float32) - if use_beta_sigmoid_in_kernel: - check_dtype("beta", beta, q.dtype) - else: - check_dtype("beta", beta, torch.float32) + check_dtype("g", g, (torch.float32, torch.bfloat16, torch.float16)) + check_dtype("beta", beta, q.dtype if use_beta_sigmoid_in_kernel else (torch.float32, q.dtype)) if safe_gate: if a_log is None or dt_bias is None: raise ValueError("kimi_delta_attention: safe_gate requires a_log and dt_bias") @@ -668,11 +667,14 @@ def kda_bwd( elif a_log is not None or dt_bias is not None: raise ValueError("kimi_delta_attention: a_log/dt_bias require safe_gate=True") if initial_state is not None: - check_dtype("initial_state", initial_state, torch.float32) + check_dtype("initial_state", initial_state, (torch.float32, torch.bfloat16)) if initial_state.shape[0] != N: raise ValueError(f"initial_state must carry one state per sequence: got {initial_state.shape[0]} for {N} sequences") + dstate_dtype = initial_state.dtype if initial_state is not None else torch.float32 if d_final_state is not None: - check_dtype("d_final_state", d_final_state, torch.float32) + check_dtype("d_final_state", d_final_state, (torch.float32, torch.bfloat16)) + if d_final_state.dtype != dstate_dtype: + raise TypeError(f"kimi_delta_attention: d_final_state must be {dstate_dtype} (one state dtype per kernel)") if state_checkpoints is not None: check_dtype("state_checkpoints", state_checkpoints, q.dtype) for tensor_name, tensor in ( @@ -770,7 +772,7 @@ def kda_bwd( dstate0 = None if state0 is not None: variant_pack[t["state0"]] = state0 - dstate0 = torch.empty_like(state0) + dstate0 = torch.empty(state0.shape, dtype=dstate_dtype, device=device) variant_pack[t["dstate0"]] = dstate0 if dstate_in is not None: variant_pack[t["dfs"]] = dstate_in @@ -787,7 +789,7 @@ def kda_bwd( variant_pack[t["d_dt_bias"]] = d_dt_bias graph.execute(variant_pack, workspace=graph_workspace(graph, device), handle=get_handle(device)) if dstate0 is None: - dstate0 = torch.empty(0, dtype=torch.float32, device=device) + dstate0 = torch.empty(0, dtype=dstate_dtype, device=device) return dq, dk, dv, dg, dbeta, dstate0, d_a_log, d_dt_bias @@ -815,7 +817,10 @@ def kda_bwd_fake( ): if safe_gate and (a_log is None or dt_bias is None): raise ValueError("kimi_delta_attention: safe_gate requires a_log and dt_bias") - dstate0 = torch.empty_like(initial_state) if initial_state is not None else q.new_empty(0, dtype=torch.float32) + dstate_dtype = initial_state.dtype if initial_state is not None else torch.float32 + if d_final_state is not None and d_final_state.dtype != dstate_dtype: + raise TypeError(f"kimi_delta_attention: d_final_state must be {dstate_dtype} (one state dtype per kernel)") + dstate0 = initial_state.new_empty(initial_state.shape, dtype=dstate_dtype) if initial_state is not None else q.new_empty(0, dtype=dstate_dtype) d_a_log = torch.empty_like(a_log) if safe_gate else q.new_empty(0, dtype=torch.float32) d_dt_bias = torch.empty_like(dt_bias) if safe_gate else q.new_empty(0, dtype=torch.float32) return ( @@ -978,19 +983,22 @@ def kimi_delta_attention( A dense batch of N equal-length sequences is expressed as ``cu_seqlens = [0, T, 2T, ...]`` over the flattened tokens. - Dtypes are kernel-native and strict (callers convert): ``g`` and the - states are float32; ``final_state``, ``dG`` and ``d_initial_state`` are - returned in float32. ``beta`` and ``dBeta`` are float32, or io dtype - under ``use_beta_sigmoid_in_kernel``. + Dtypes are kernel-native and strict (callers convert). ``g`` is float32, + bfloat16 or float16 and ``dG`` comes back in the same dtype. ``beta`` and + ``dBeta`` are float32 or the io dtype (io-dtype logits under + ``use_beta_sigmoid_in_kernel``). ``initial_state`` is float32 or bfloat16 + and ``final_state`` and the state gradients (``d_final_state``, + ``d_initial_state``) follow it. Args: g: per-key-channel log-space decay (``alpha = exp(g) in (0, 1]^K``), or raw pre-activation logits when ``safe_gate=True``. - beta: per-token scalar write strength (float32 post-sigmoid), or - io-dtype logits when ``use_beta_sigmoid_in_kernel=True``. - cu_seqlens: ``[N+1]`` int32 sequence boundaries over the packed tokens. + beta: per-token scalar write strength (float32 or the io dtype, + post-sigmoid), or io-dtype logits when ``use_beta_sigmoid_in_kernel=True``. + cu_seqlens: ``[N+1]`` int32/int64 sequence boundaries over the packed tokens. scale: attention scale applied to ``q``. Defaults to ``1 / sqrt(K)``. - initial_state: optional recurrent state (otherwise zero). + initial_state: optional recurrent state (otherwise zero); float32 or + bfloat16, and ``final_state`` comes back in the same dtype. output_final_state: if ``True``, also return the per-sequence state after the last token. use_qk_l2norm_in_kernel: if ``True``, L2-normalize the Q/K rows inside diff --git a/test/python/linear_attention/test_la.py b/test/python/linear_attention/test_la.py index 60c8afba31..f8ddd38f43 100644 --- a/test/python/linear_attention/test_la.py +++ b/test/python/linear_attention/test_la.py @@ -42,7 +42,9 @@ ] VARIANTS = ("gdn", "kda", "gdn2") -SPLIT_T = 4096 # long enough that the work-item table cuts +CHANNEL_VARIANTS = ("kda", "gdn2") +STATE_DTYPES = (torch.float32, torch.bfloat16) +SPLIT_T = 4096 CHUNK = {"gdn": 64, "kda": 16, "gdn2": 16} FWD_TOL = {torch.bfloat16: 2e-2, torch.float16: 1e-2} @@ -77,7 +79,8 @@ ] SEED = 888 -DTYPE_IDS = {torch.bfloat16: "bf16", torch.float16: "fp16"} +DTYPE_IDS = {torch.bfloat16: "bf16", torch.float16: "fp16", torch.float32: "fp32"} +OP_NAMES = {"gdn": "gated_delta_net", "kda": "kimi_delta_attention", "gdn2": "gated_delta_net_v2"} # --------------------------------------------------------------------------- @@ -176,6 +179,16 @@ def waive_unsupported(backend, variant): pytest.skip(f"{backend.name} {variant} declined: {exc}") +@contextlib.contextmanager +def waive_declined(what): + """Same waiver for the tests that pin no backend: default routing picks the + engine, so a config no engine serves is a skip, not a failure.""" + try: + yield + except cudnn.cudnnGraphNotSupportedError as exc: + pytest.skip(f"{what} declined: {exc}") + + # --------------------------------------------------------------------------- # Case generation and dispatch # --------------------------------------------------------------------------- @@ -206,7 +219,27 @@ def gen_gates(variant, B, T, HO, K, V, dtype, *, alpha=True, beta=True, w=True, return {"g": g, "beta": b} -def make_case(variant, dtype, *, B=1, T=None, seq_lens=None, H=2, HK=None, HV=None, K=128, V=128, alpha=True, beta=True, w=True, lo=None, seed=SEED): +def make_case( + variant, + dtype, + *, + B=1, + T=None, + seq_lens=None, + H=2, + HK=None, + HV=None, + K=128, + V=128, + alpha=True, + beta=True, + w=True, + lo=None, + gate_dtype=None, + beta_dtype=None, + cu_dtype=torch.int32, + seed=SEED, +): """Dense ``(B, T)`` or packed varlen (``seq_lens``, B == 1) inputs plus the matching ``cu_seqlens``. ``HK`` defaults to ``H``; ``HK == HV < H`` is canonical (native grouped K) GQA.""" @@ -219,10 +252,10 @@ def make_case(variant, dtype, *, B=1, T=None, seq_lens=None, H=2, HK=None, HV=No bounds = [0] for sl in seq_lens: bounds.append(bounds[-1] + sl) - cu = torch.tensor(bounds, dtype=torch.int32, device="cuda") + cu = torch.tensor(bounds, dtype=cu_dtype, device="cuda") B, T, N, varlen = 1, total, len(seq_lens), True else: - cu = torch.arange(0, B + 1, dtype=torch.int32, device="cuda") * T + cu = torch.arange(0, B + 1, dtype=cu_dtype, device="cuda") * T N, varlen = B, False q, k, v = gen_qkv(B, T, H, HV, K, V, dtype) if HK != H: @@ -230,6 +263,10 @@ def make_case(variant, dtype, *, B=1, T=None, seq_lens=None, H=2, HK=None, HV=No k = F.normalize(multidist_randu(B * T * HK, K, device="cuda").reshape(B, T, HK, K), p=2.0, dim=-1).to(dtype).contiguous() gates = gen_gates(variant, B, T, HO, K, V, dtype, alpha=alpha, beta=beta, w=w, lo=lo) + if gate_dtype is not None: + gates["g"] = gates["g"].to(gate_dtype) + if beta_dtype is not None: + gates["beta"] = gates["beta"].to(beta_dtype) return Case(variant=variant, dtype=dtype, q=q, k=k, v=v, gates=gates, cu=cu, B=B, T=T, N=N, H=H, HK=HK, HV=HV, HO=HO, K=K, V=V, varlen=varlen) @@ -279,16 +316,18 @@ def assert_rms_close(name, out, want, tol): assert r < tol, f"{name} rms ratio {r:.4g} >= {tol}" -def assert_fwd_parity(backend, case, *, scale=None, use_initial_state=False, l2norm=False, beta_guard=False, seed=SEED + 1): +def assert_fwd_parity(backend, case, *, scale=None, use_initial_state=False, state_dtype=torch.float32, l2norm=False, beta_guard=False, seed=SEED + 1): set_seed(seed) state0 = None if use_initial_state: - state0 = torch.randn(case.N, case.HO, case.V, case.K, device="cuda", dtype=torch.float32) * 0.05 + state0 = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda", dtype=torch.float32) * 0.05).to(state_dtype) op_kw = dict(scale=scale, initial_state=state0, output_final_state=True, use_qk_l2norm_in_kernel=l2norm) if beta_guard: op_kw["beta_guard"] = True o, fs = run_fwd(backend, case, **op_kw) o_ref, fs_ref = reference(case, scale=scale, initial_state=state0, l2norm=l2norm, beta_guard=beta_guard) + if state0 is not None: + assert fs.dtype == state_dtype, f"final_state is {fs.dtype}, initial_state is {state_dtype}" assert_rms_close("o", o, o_ref, FWD_TOL[case.dtype]) if fs is not None and fs.numel(): assert_rms_close("final_state", fs, fs_ref, STATE_TOL[case.dtype]) @@ -516,13 +555,16 @@ def test_fwd_strong_decay_varlen(backend, variant): @pytest.mark.parametrize("variant", VARIANTS) def test_fwd_output_contract(backend, variant): - """O is io-dtype at HO heads; final_state is fp32 and empty unless requested.""" + """O is io-dtype at HO heads; final_state is empty unless requested.""" case = make_case(variant, torch.bfloat16, T=128, H=2, HV=4) o, fs = run_fwd(backend, case) assert o.shape == (case.T, case.HO, case.V) and o.dtype == case.dtype assert fs.numel() == 0 o, fs = run_fwd(backend, case, output_final_state=True) assert fs.shape == (case.N, case.HO, case.V, case.K) and fs.dtype == torch.float32 + o_ref, fs_ref = reference(case) + assert_rms_close("o", o, o_ref, FWD_TOL[case.dtype]) + assert_rms_close("final_state", fs, fs_ref, STATE_TOL[case.dtype]) # --------------------------------------------------------------------------- @@ -530,7 +572,19 @@ def test_fwd_output_contract(backend, variant): # --------------------------------------------------------------------------- -def assert_bwd_parity(backend, case, *, scale=None, use_initial_state=False, use_dfs=False, l2norm=False, beta_guard=False, gate_grad_tol=None, seed=SEED + 1): +def assert_bwd_parity( + backend, + case, + *, + scale=None, + use_initial_state=False, + state_dtype=torch.float32, + use_dfs=False, + l2norm=False, + beta_guard=False, + gate_grad_tol=None, + seed=SEED + 1, +): variant, tol = case.variant, BWD_TOL[case.dtype] tensors = {"q": case.q, "k": case.k, "v": case.v, "g": case.gates["g"], "beta": case.gates["beta"]} if variant == "gdn2": @@ -540,7 +594,7 @@ def assert_bwd_parity(backend, case, *, scale=None, use_initial_state=False, use set_seed(seed) state0_op = state0_ref = None if use_initial_state: - state0 = torch.randn(case.N, case.HO, case.V, case.K, device="cuda", dtype=torch.float32) * 0.05 + state0 = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda", dtype=torch.float32) * 0.05).to(state_dtype) state0_op = state0.detach().clone().requires_grad_(True) state0_ref = state0.detach().double().requires_grad_(True) @@ -711,6 +765,320 @@ def test_bwd_with_checkpoints(backend, variant): (o.sum() + fs.sum()).backward() for name, t in (("q", q_t), ("g", g_t)): assert t.grad is not None and torch.isfinite(t.grad).all(), f"bad grad for {name}" + # dumping the checkpoints must not change the result: same run without them + q_ref = to_thd(case.q).detach().clone().requires_grad_(True) + g_ref = to_thd(case.gates["g"]).detach().clone().requires_grad_(True) + ref_args = [q_ref, to_thd(case.k), to_thd(case.v), g_ref, to_thd(case.gates["beta"])] + if variant == "gdn2": + ref_args.append(to_thd(case.gates["w"])) + with waive_unsupported(backend, variant): + o_ref, fs_ref = pinned_op(backend, variant)(*ref_args, case.cu, output_final_state=True) + (o_ref.sum() + fs_ref.sum()).backward() + assert_rms_close("o", o, o_ref, FWD_TOL[case.dtype]) + assert_rms_close("final_state", fs, fs_ref, STATE_TOL[case.dtype]) + for name, t, r in (("q", q_t, q_ref), ("g", g_t, g_ref)): + assert_rms_close(f"d{name}", t.grad.float(), r.grad.float(), BWD_TOL[case.dtype]) + + +# --------------------------------------------------------------------------- +# Dtype surface (gate / beta / state widths, and the caches keyed on them) +# --------------------------------------------------------------------------- + + +def gate_dtype_pair(variant, gate_dtype, io_dtype=torch.bfloat16, **case_kw): + """One case with a 16-bit gate and its EXACT fp32 twin (same values, wider + storage).""" + case = make_case(variant, io_dtype, **case_kw) + g16 = case.gates["g"].to(gate_dtype) + wide = case.clone(gates=dict(case.gates, g=g16.float())) + narrow = case.clone(gates=dict(case.gates, g=g16)) + return narrow, wide + + +def assert_bitwise(name, got, want): + assert got.shape == want.shape, f"{name}: {tuple(got.shape)} vs {tuple(want.shape)}" + assert torch.equal(got.float(), want.float()), f"{name} differs between the 16-bit and fp32 gate arms" + + +@pytest.mark.parametrize("gate_dtype", [torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("T", [128, 1024, SPLIT_T]) +@pytest.mark.parametrize("variant", VARIANTS) +def test_fwd_gate_16bit(backend, variant, T, gate_dtype): + """SPLIT_T also drives the 16-bit gate through the split-K chunk scan.""" + narrow, wide = gate_dtype_pair(variant, gate_dtype, T=T, H=2) + assert narrow.gates["g"].dtype == gate_dtype + o16, fs16 = run_fwd(backend, narrow, output_final_state=True) + o32, fs32 = run_fwd(backend, wide, output_final_state=True) + assert_bitwise("o", o16, o32) + assert_bitwise("final_state", fs16, fs32) + assert_fwd_parity(backend, narrow) + + +@pytest.mark.parametrize("gate_dtype", [torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_fwd_gate_16bit_varlen(backend, variant, gate_dtype): + narrow, wide = gate_dtype_pair(variant, gate_dtype, seq_lens=[96, 32, 160, 1, 511]) + o16, _ = run_fwd(backend, narrow) + o32, _ = run_fwd(backend, wide) + assert_bitwise("o", o16, o32) + assert_fwd_parity(backend, narrow) + + +@pytest.mark.parametrize("gate_dtype", [torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_bwd_gate_16bit(backend, variant, gate_dtype): + """dG leaves in the gate's own dtype, as the forward takes it.""" + narrow, _ = gate_dtype_pair(variant, gate_dtype, T=256, H=2) + assert_bwd_parity(backend, narrow, gate_grad_tol=8e-2) + + +@pytest.mark.parametrize("gate_dtype", [torch.float32, torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_bwd_gate_grad_dtype(backend, variant, gate_dtype): + """The gate gradient comes back at the gate's dtype, carrying the same + values as the exact fp32-gate twin (the gate is widened on load).""" + case = make_case(variant, torch.bfloat16, T=128, H=2, gate_dtype=gate_dtype) + set_seed(SEED + 6) + dO = torch.randn(case.T, case.HO, case.V, device="cuda", dtype=case.dtype) + grads = {} + for arm, g in (("narrow", case.gates["g"]), ("wide", case.gates["g"].float())): + tensors = {"q": case.q, "k": case.k, "v": case.v, "g": g, "beta": case.gates["beta"]} + if variant == "gdn2": + tensors["w"] = case.gates["w"] + leaves = {n: to_thd(t).detach().clone().requires_grad_(True) for n, t in tensors.items()} + with waive_unsupported(backend, variant): + args = [leaves["q"], leaves["k"], leaves["v"], leaves["g"], leaves["beta"]] + if variant == "gdn2": + args.append(leaves["w"]) + o, _ = pinned_op(backend, variant)(*args, case.cu, output_final_state=True) + (grads[arm],) = torch.autograd.grad(o, [leaves["g"]], dO) + assert grads["narrow"].dtype == gate_dtype, f"dG is {grads['narrow'].dtype}, gate is {gate_dtype}" + assert torch.isfinite(grads["narrow"]).all() + assert_rms_close("dG", grads["narrow"].float(), grads["wide"].float(), BWD_TOL[case.dtype]) + + +@pytest.mark.parametrize("gate_dtype", [torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_gate_16bit_safe_gate(backend, variant, gate_dtype): + """Safe-gate takes the gate as raw logits, and its d_a_log / d_dt_bias + reduction reads the raw gate again in the post-pass.""" + case, graw, a_log, dt_bias = safe_gate_case(variant, T=256) + g16 = graw.to(gate_dtype) + kw = dict(safe_gate=True, a_log=a_log, dt_bias=dt_bias, output_final_state=True) + if variant != "gdn": # GDN's scalar safe-gate has no lower bound to clamp to + kw["gate_lower_bound"] = -5.0 + o16, fs16 = run_fwd(backend, case.clone(gates=dict(case.gates, g=g16)), **kw) + o32, fs32 = run_fwd(backend, case.clone(gates=dict(case.gates, g=g16.float())), **kw) + assert_bitwise("o", o16, o32) + assert_bitwise("final_state", fs16, fs32) + + +@pytest.mark.parametrize("gate_dtype", [torch.float32, torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_bwd_meta_dtypes_match_eager(variant, gate_dtype): + """The register_fake kernel must declare the dtypes the op really allocates, + or AOTAutograd traces the wrong gradient dtype.""" + from torch._subclasses.fake_tensor import FakeTensorMode + + case = make_case(variant, torch.bfloat16, T=128, H=2, gate_dtype=gate_dtype) + name = OP_NAMES[variant] + dO = torch.randn(case.T, case.HO, case.V, device="cuda", dtype=case.dtype) + args = [dO, to_thd(case.q), to_thd(case.k), to_thd(case.v), to_thd(case.gates["g"]), to_thd(case.gates["beta"])] + if variant == "gdn2": + args.append(to_thd(case.gates["w"])) + args += [case.cu, float(case.K**-0.5)] + state0 = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda") * 0.05).to(torch.bfloat16) + kw = dict(initial_state=state0, d_final_state=state0.clone()) + bwd = getattr(torch.ops.cudnn, name + "_bwd") + with waive_declined(f"{variant} with a bf16 state"): + eager = bwd(*args, **kw) + with FakeTensorMode(allow_non_fake_inputs=True): + meta = bwd(*args, **kw) + got = [(i, e.dtype, m.dtype) for i, (e, m) in enumerate(zip(eager, meta)) if e.dtype != m.dtype] + assert not got, f"meta/eager dtype mismatch at output indices {got}" + + +@pytest.mark.parametrize("io_dtype", [torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("gate_dtype", [torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_fwd_gate_16bit_io_cross(backend, variant, gate_dtype, io_dtype): + """The gate dtype is independent of the io dtype; all four crossings hold.""" + narrow, wide = gate_dtype_pair(variant, gate_dtype, io_dtype=io_dtype, T=256, H=2) + o16, fs16 = run_fwd(backend, narrow, output_final_state=True) + o32, fs32 = run_fwd(backend, wide, output_final_state=True) + assert_bitwise("o", o16, o32) + assert_bitwise("final_state", fs16, fs32) + + +@pytest.mark.parametrize("beta_dtype", [torch.float32, torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", ["gdn", "kda"]) +def test_fwd_beta_dtype(backend, variant, beta_dtype): + """beta is accepted at fp32 or the io dtype and widened on the scalar load, + so a 16-bit beta and its exact fp32 twin must agree bit for bit.""" + case = make_case(variant, torch.bfloat16 if beta_dtype == torch.float32 else beta_dtype, T=256, H=2) + b16 = case.gates["beta"].to(beta_dtype) + narrow = case.clone(gates=dict(case.gates, beta=b16)) + wide = case.clone(gates=dict(case.gates, beta=b16.float())) + o16, fs16 = run_fwd(backend, narrow, output_final_state=True) + o32, fs32 = run_fwd(backend, wide, output_final_state=True) + assert_bitwise("o", o16, o32) + assert_bitwise("final_state", fs16, fs32) + assert_fwd_parity(backend, narrow) + + +@pytest.mark.parametrize("beta_dtype", [torch.float32, torch.bfloat16], ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", ["gdn", "kda"]) +def test_bwd_beta_grad_dtype(backend, variant, beta_dtype): + """dBeta leaves in beta's own dtype, and carries the same values as the + fp32-beta twin: a 16-bit beta is widened on load, not accumulated narrow.""" + case = make_case(variant, torch.bfloat16, T=128, H=2, beta_dtype=beta_dtype) + set_seed(SEED + 5) + dO = torch.randn(case.T, case.HO, case.V, device="cuda", dtype=case.dtype) + grads = {} + for arm, beta in (("narrow", case.gates["beta"]), ("wide", case.gates["beta"].float())): + leaves = {n: to_thd(t).detach().clone().requires_grad_(True) for n, t in (("q", case.q), ("g", case.gates["g"]), ("beta", beta))} + with waive_unsupported(backend, variant): + o, _ = pinned_op(backend, variant)(leaves["q"], to_thd(case.k), to_thd(case.v), leaves["g"], leaves["beta"], case.cu) + (grads[arm],) = torch.autograd.grad(o, [leaves["beta"]], dO) + assert grads["narrow"].dtype == beta_dtype, f"dBeta is {grads['narrow'].dtype}, beta is {beta_dtype}" + assert torch.isfinite(grads["narrow"]).all() + assert_rms_close("dBeta", grads["narrow"].float(), grads["wide"].float(), BWD_TOL[case.dtype]) + + +@pytest.mark.parametrize("state_dtype", STATE_DTYPES, ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_fwd_state_dtype(backend, variant, state_dtype): + """A bf16 state pool: the kernel widens on load and narrows on store, and + final_state comes back in initial_state's dtype.""" + assert_fwd_parity(backend, make_case(variant, torch.bfloat16, T=256), use_initial_state=True, state_dtype=state_dtype) + + +@pytest.mark.parametrize("state_dtype", STATE_DTYPES, ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_bwd_state_dtype(backend, variant, state_dtype): + """A bf16 state pool drives a bf16 d_final_state into the kernel and a bf16 + d_initial_state out of it, with the reverse-scan accumulator still fp32.""" + assert_bwd_parity(backend, make_case(variant, torch.bfloat16, T=128), use_initial_state=True, state_dtype=state_dtype, use_dfs=True) + + +@pytest.mark.parametrize("state_dtype", STATE_DTYPES, ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_bwd_state_grad_dtype(backend, variant, state_dtype): + """The state gradients ride the state's own dtype end to end, asserted on the + raw op rather than through autograd.""" + case = make_case(variant, torch.bfloat16, T=128, H=2) + state0 = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda") * 0.05).to(state_dtype) + args = [to_thd(case.q), to_thd(case.k), to_thd(case.v), to_thd(case.gates["g"]), to_thd(case.gates["beta"])] + if variant == "gdn2": + args.append(to_thd(case.gates["w"])) + dO = torch.randn(case.T, case.HO, case.V, device="cuda", dtype=case.dtype) + dfs = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda") * 0.1).to(state_dtype) + with waive_unsupported(backend, variant): + o, fs = pinned_op(backend, variant)(*args, case.cu, initial_state=state0, output_final_state=True) + assert fs.dtype == state_dtype, f"final_state is {fs.dtype}" + out = getattr(torch.ops.cudnn, OP_NAMES[variant] + "_bwd")(dO, *args, case.cu, float(case.K**-0.5), initial_state=state0, d_final_state=dfs) + ds0 = out[-3] + assert ds0.dtype == state_dtype, f"d_initial_state is {ds0.dtype}, initial_state is {state_dtype}" + assert torch.isfinite(ds0).all() + with waive_unsupported(backend, variant): + wide = getattr(torch.ops.cudnn, OP_NAMES[variant] + "_bwd")( + dO, *args, case.cu, float(case.K**-0.5), initial_state=state0.float(), d_final_state=dfs.float() + ) + assert_rms_close("d_initial_state", ds0.float(), wide[-3].float(), BWD_TOL[case.dtype]) + assert_rms_close("dQ", out[0].float(), wide[0].float(), BWD_TOL[case.dtype]) + + +@pytest.mark.parametrize("state_dtype", STATE_DTYPES, ids=DTYPE_IDS.get) +@pytest.mark.parametrize("variant", VARIANTS) +def test_bwd_zero_length_sequence_state_dtype(backend, variant, state_dtype): + """An empty sequence takes the scalar pass-through branch of the state-gradient + store.""" + case = make_case(variant, torch.bfloat16, seq_lens=[64, 0, 128]) + assert_bwd_parity(backend, case, use_initial_state=True, state_dtype=state_dtype, use_dfs=True) + + +@pytest.mark.parametrize("variant", VARIANTS) +def test_bwd_state_grad_dtype_must_match_state(backend, variant): + """One state dtype per compiled kernel: a d_final_state that disagrees with + initial_state is rejected at the op, not silently reinterpreted.""" + case = make_case(variant, torch.bfloat16, T=128, H=2) + state0 = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda") * 0.05).to(torch.bfloat16) + args = [to_thd(case.q), to_thd(case.k), to_thd(case.v), to_thd(case.gates["g"]), to_thd(case.gates["beta"])] + if variant == "gdn2": + args.append(to_thd(case.gates["w"])) + dO = torch.randn(case.T, case.HO, case.V, device="cuda", dtype=case.dtype) + bwd = getattr(torch.ops.cudnn, OP_NAMES[variant] + "_bwd") + dfs = torch.randn(case.N, case.HO, case.V, case.K, device="cuda", dtype=torch.float32) * 0.1 + with pytest.raises(TypeError, match="one state dtype per kernel"): + bwd(dO, *args, case.cu, float(case.K**-0.5), initial_state=state0, d_final_state=dfs) + + +@pytest.mark.parametrize("variant", VARIANTS) +def test_bwd_state_grad_cache_separation(backend, variant): + """Two state-gradient dtypes for one shape inside one process.""" + case = make_case(variant, torch.bfloat16, T=256, H=2) + set_seed(SEED + 4) + state = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda") * 0.05).to(torch.bfloat16) + dfs = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda") * 0.1).to(torch.bfloat16) + dO = torch.randn(case.T, case.HO, case.V, device="cuda", dtype=case.dtype) + arms = [] + for narrow in (True, False): + state0 = (state if narrow else state.float()).detach().clone().requires_grad_(True) + leaves = { + n: to_thd(t).detach().clone().requires_grad_(True) + for n, t in (("q", case.q), ("k", case.k), ("v", case.v), ("g", case.gates["g"]), ("beta", case.gates["beta"])) + } + args = [leaves["q"], leaves["k"], leaves["v"], leaves["g"], leaves["beta"]] + if variant == "gdn2": + args.append(to_thd(case.gates["w"]).detach().clone().requires_grad_(True)) + with waive_unsupported(backend, variant): + o, fs = pinned_op(backend, variant)(*args, case.cu, initial_state=state0, output_final_state=True) + grads = torch.autograd.grad([o, fs], [leaves["q"], state0], [dO, (dfs if narrow else dfs.float())]) + arms.append((grads[0], grads[1])) + assert_bitwise("dQ", arms[0][0], arms[1][0]) + assert (arms[0][1].dtype, arms[1][1].dtype) == (torch.bfloat16, torch.float32) + torch.testing.assert_close(arms[0][1].float(), arms[1][1], rtol=1e-2, atol=1e-2) + + +@pytest.mark.parametrize("variant", VARIANTS) +def test_cu_seqlens_int64(backend, variant): + """int64 cu_seqlens (what FLA and FlashInfer hand out) is a live cache-key + element and must produce the identical result.""" + narrow = make_case(variant, torch.bfloat16, seq_lens=[96, 32, 160, 1, 511], cu_dtype=torch.int32) + wide = narrow.clone(cu=narrow.cu.to(torch.int64)) + o32, _ = run_fwd(backend, narrow) + o64, _ = run_fwd(backend, wide) + assert_bitwise("o", o64, o32) + + +@pytest.mark.parametrize("port", ["g", "beta", "initial_state", "cu"]) +@pytest.mark.parametrize("variant", VARIANTS) +def test_dtype_cache_separation(backend, variant, port): + """Two dtypes for the SAME port inside one process, over values that are + numerically identical in both (narrowed first, then widened back).""" + if port == "beta" and variant == "gdn2": + pytest.skip("gdn2 pins beta to the io dtype, so it has no second dtype to collide with") + case = make_case(variant, torch.bfloat16, T=256, H=2) + set_seed(SEED + 3) + state = (torch.randn(case.N, case.HO, case.V, case.K, device="cuda") * 0.05).to(torch.bfloat16) + arms = [] + for narrow in (True, False): + gates, state0 = dict(case.gates), state.float() + if port == "g": + g16 = case.gates["g"].to(torch.bfloat16) + gates["g"] = g16 if narrow else g16.float() + elif port == "beta": + b16 = case.gates["beta"].to(torch.bfloat16) + gates["beta"] = b16 if narrow else b16.float() + elif port == "initial_state": + state0 = state if narrow else state.float() + cu = case.cu.to(torch.int64) if (port == "cu" and narrow) else case.cu.to(torch.int32) + arms.append(run_fwd(backend, case.clone(gates=gates, cu=cu), initial_state=state0, output_final_state=True)) + assert_bitwise("o", arms[0][0], arms[1][0]) + if port == "initial_state": + assert (arms[0][1].dtype, arms[1][1].dtype) == (torch.bfloat16, torch.float32) + else: + assert_bitwise("final_state", arms[0][1], arms[1][1]) # --------------------------------------------------------------------------- @@ -995,8 +1363,9 @@ def test_safe_gate_forward_parity(backend, variant): assert rms_ratio(fs_raw, fs_eff) < 2e-2 +@pytest.mark.parametrize("gate_dtype", [torch.float32, torch.bfloat16, torch.float16], ids=DTYPE_IDS.get) @pytest.mark.parametrize("variant", VARIANTS) -def test_safe_gate_backward(backend, variant): +def test_safe_gate_backward(backend, variant, gate_dtype): """Fused-gate training: dG comes back in raw-logit space and the parameter gradients satisfy their exact identities over dG (d_dt_bias = sum dg_raw; d_a_log = sum dg_raw * (g + dt_bias) per-channel, @@ -1006,7 +1375,7 @@ def test_safe_gate_backward(backend, variant): set_seed(SEED + 9) a_leaf = (torch.randn_like(a_log) * 0.3).requires_grad_(True) dt_leaf = (torch.randn_like(dt_bias) * 0.3).requires_grad_(True) - raw_gates = dict(case.gates, g=graw) + raw_gates = dict(case.gates, g=graw.to(gate_dtype)) kw = dict(safe_gate=True, a_log=a_leaf, dt_bias=dt_leaf, use_qk_l2norm_in_kernel=True) if variant != "gdn": kw["gate_lower_bound"] = lb @@ -1022,6 +1391,7 @@ def test_safe_gate_backward(backend, variant): with waive_unsupported(backend, variant): o, _ = pinned_op(backend, variant)(*args, case.cu, **kw) o.sum().backward() + assert g_leaf.grad.dtype == gate_dtype, f"dG is {g_leaf.grad.dtype}, gate is {gate_dtype}" dg_raw = g_leaf.grad.double() ddt_id = dg_raw.sum(0) if variant == "gdn": @@ -1029,9 +1399,12 @@ def test_safe_gate_backward(backend, variant): da_id = (dg_raw * (F.softplus(y) / torch.sigmoid(y))).sum(0) else: da_id = (dg_raw * (g_leaf.detach().double() + dt_leaf.detach().double()[None])).sum(dim=(0, 2)) + # The identities are evaluated over the returned dG, so they hold to the + # gate dtype's precision. + ident_tol = 1e-4 if gate_dtype == torch.float32 else 5e-2 for name, got, ident in (("d_dt_bias", dt_leaf.grad.double(), ddt_id), ("d_a_log", a_leaf.grad.double(), da_id)): scale = max(ident.abs().max().item(), 1e-6) - assert (got - ident).abs().max().item() / scale < 1e-4, name + assert (got - ident).abs().max().item() / scale < ident_tol, name for name, leaf in (("dq", args[0]), ("dbeta", beta_leaf)): assert leaf.grad is not None and bool(torch.isfinite(leaf.grad).all()), name @@ -1298,12 +1671,20 @@ def test_invalid_qk_head_mismatch_raises(variant): @pytest.mark.parametrize("variant", VARIANTS) def test_invalid_gate_dtype_raises(variant): + """fp64 is rejected everywhere; fp32/bf16/fp16 gates are accepted everywhere.""" case = make_case(variant, torch.bfloat16, T=64) - args = [to_thd(case.q), to_thd(case.k), to_thd(case.v), to_thd(case.gates["g"]).to(torch.bfloat16), to_thd(case.gates["beta"])] - if variant == "gdn2": - args.append(to_thd(case.gates["w"])) - with pytest.raises(TypeError, match="must be"): - op(variant)(*args, case.cu) + + def call(gate_dtype): + args = [to_thd(case.q), to_thd(case.k), to_thd(case.v), to_thd(case.gates["g"]).to(gate_dtype), to_thd(case.gates["beta"])] + if variant == "gdn2": + args.append(to_thd(case.gates["w"])) + return op(variant)(*args, case.cu) + + with pytest.raises((TypeError, KeyError)): + call(torch.float64) + for gate_dtype in (torch.float32, torch.bfloat16, torch.float16): + with waive_declined(f"{variant} with a {gate_dtype} gate"): + assert call(gate_dtype)[0].dtype == case.dtype @pytest.mark.parametrize("variant", VARIANTS) @@ -1625,12 +2006,16 @@ def test_execute_from_a_thread_with_no_cuda_context(backend, variant): args.append(to_thd(case.gates["w"])) seen = {} + set_seed(SEED + 7) + dO = torch.randn(case.T, case.HO, case.V, device="cuda", dtype=case.dtype) + def run_on_cold_thread(): seen["before"] = int(drv.cuCtxGetCurrent()[1]) try: # batch_invariant skips the split-K table launch that would bind a context first o, _ = pinned_op(backend, variant)(*args, case.cu, batch_invariant=True) - torch.autograd.grad([o], leaves, [torch.randn_like(o)]) + seen["o"] = o.detach().clone() + seen["grads"] = torch.autograd.grad([o], leaves, [dO]) except BaseException as exc: # noqa: BLE001 seen["exc"] = exc seen["after"] = int(drv.cuCtxGetCurrent()[1]) @@ -1643,6 +2028,13 @@ def run_on_cold_thread(): raise seen["exc"] assert seen["before"] == 0, "the worker thread was already bound, so this no longer covers the cold path" assert seen["after"] != 0, "execute left the calling thread with no CUDA context" + # the cold thread must not just survive, it must compute what the warm one does + with waive_unsupported(backend, variant): + o_warm, _ = pinned_op(backend, variant)(*args, case.cu, batch_invariant=True) + grads_warm = torch.autograd.grad([o_warm], leaves, [dO]) + assert_bitwise("o", seen["o"], o_warm) + for name, cold, warm in zip(("dQ", "dK"), seen["grads"], grads_warm): + assert_bitwise(name, cold, warm) # --------------------------------------------------------------------------- @@ -1755,6 +2147,7 @@ def build_inputs(c): dO = torch.randn_like(o) grads = torch.autograd.grad([o], grad_inputs, [dO], retain_graph=True) torch.cuda.synchronize() + want = [g.detach().clone() for g in grads] heartbeat[0] = time.monotonic() for _ in range(iters): for g in grads: @@ -1767,8 +2160,9 @@ def build_inputs(c): heartbeat[0] = time.monotonic() assert torch.isfinite(o.float()).all(), "non-finite forward output after stress" names = ["q", "k", "v", "g", "beta"] + (["w"] if case.variant == "gdn2" else []) + (["initial_state"] if use_initial_state else []) - for name, g in zip(names, grads): + for name, g, w in zip(names, grads, want): assert torch.isfinite(g.float()).all(), f"non-finite d{name} after stress" + assert torch.equal(g, w), f"d{name} drifted across stress iterations (same inputs, same dO)" @pytest.mark.gpu_exclusive