Entry point called by bench.py. Must match reference.fused_mlp_ref signature. SwiGLU MLP: hidden = activation(x @ w_gate.T) * (x @ w_up.T) out = hidden @ w_down.T Args: x: [batch, hidden_size] or [batch, seq_len, hidden_size] w_gate: [intermediate_size, hid
(
x: torch.Tensor,
w_gate: torch.Tensor,
w_up: torch.Tensor,
w_down: torch.Tensor,
activation: str = "silu",
)
| 100 | |
| 101 | |
| 102 | def kernel_fn( |
| 103 | x: torch.Tensor, |
| 104 | w_gate: torch.Tensor, |
| 105 | w_up: torch.Tensor, |
| 106 | w_down: torch.Tensor, |
| 107 | activation: str = "silu", |
| 108 | ) -> torch.Tensor: |
| 109 | """ |
| 110 | Entry point called by bench.py. Must match reference.fused_mlp_ref signature. |
| 111 | |
| 112 | SwiGLU MLP: |
| 113 | hidden = activation(x @ w_gate.T) * (x @ w_up.T) |
| 114 | out = hidden @ w_down.T |
| 115 | |
| 116 | Args: |
| 117 | x: [batch, hidden_size] or [batch, seq_len, hidden_size] |
| 118 | w_gate: [intermediate_size, hidden_size] |
| 119 | w_up: [intermediate_size, hidden_size] |
| 120 | w_down: [hidden_size, intermediate_size] |
| 121 | activation: "silu" or "gelu" |
| 122 | """ |
| 123 | assert x.is_cuda |
| 124 | |
| 125 | # Handle multi-dim input |
| 126 | orig_shape = x.shape |
| 127 | if x.ndim > 2: |
| 128 | x = x.view(-1, x.shape[-1]) |
| 129 | |
| 130 | M, K = x.shape |
| 131 | N, K2 = w_gate.shape |
| 132 | assert K == K2, f"Hidden dim mismatch: x has {K}, w_gate has {K2}" |
| 133 | assert w_up.shape == (N, K), f"w_up shape mismatch" |
| 134 | |
| 135 | hidden = torch.empty((M, N), device=x.device, dtype=x.dtype) |
| 136 | |
| 137 | BLOCK_SIZE_M = 64 |
| 138 | BLOCK_SIZE_N = 64 |
| 139 | BLOCK_SIZE_K = 32 |
| 140 | |
| 141 | grid = (triton.cdiv(M, BLOCK_SIZE_M), triton.cdiv(N, BLOCK_SIZE_N)) |
| 142 | |
| 143 | # W_gate and W_up are [N, K]. We access them as transposed: X[M,K] @ W^T[K,N] |
| 144 | # So stride_wgk corresponds to stride along the K dimension (stride(1) of [N,K]) |
| 145 | # and stride_wgn corresponds to stride along N dimension (stride(0) of [N,K]) |
| 146 | fused_gate_up_kernel[grid]( |
| 147 | x, |
| 148 | w_gate, |
| 149 | w_up, |
| 150 | hidden, |
| 151 | M, N, K, |
| 152 | x.stride(0), x.stride(1), |
| 153 | w_gate.stride(1), w_gate.stride(0), # transposed: K-stride, N-stride |
| 154 | w_up.stride(1), w_up.stride(0), # transposed: K-stride, N-stride |
| 155 | hidden.stride(0), hidden.stride(1), |
| 156 | USE_SILU=(activation == "silu"), |
| 157 | BLOCK_SIZE_M=BLOCK_SIZE_M, |
| 158 | BLOCK_SIZE_N=BLOCK_SIZE_N, |
| 159 | BLOCK_SIZE_K=BLOCK_SIZE_K, |
nothing calls this directly
no outgoing calls
no test coverage detected