LeetKernels
ProblemsStart solving
Problems

84. SwiGLU MLP Block medium

Implement the SwiGLU MLP block — the feedforward network used in LLaMA, Mistral, Gemma, and most modern large language models. Given an input matrix x of shape [M, d_model] and three weight matrices W_gate, W_up (each [d_model, d_ffn]), and W_down ([d_ffn, d_model]), compute: output = (SiLU(x × W_gate) ⊙ (x × W_up)) × W_down, where SiLU(z) = z × sigmoid(z) and ⊙ denotes element-wise multiplication. All tensors are float32.

x [M, d_model] x · W_gate gate projection x · W_up up projection [M, d_ffn] [M, d_ffn] SiLU ⊙ · W_down [M, d_ffn] output [M, d_model] z · sigmoid(z)

Implementation Requirements

  • Implement the solve function with the signature unchanged.
  • Do not use external libraries beyond the framework provided.
  • Write the result into output in-place.

Example

Input: M = 2, d_model = 2, d_ffn = 4

x (float32, 2×2): x=[1.00.0​0.01.0​] Wgate​ and Wup​ (both 2×4): Wgate​=Wup​=[1.00.0​0.01.0​0.00.0​0.00.0​] Wdown​ (4×2): Wdown​=​1.00.00.00.0​0.01.00.00.0​​

Intermediate steps: gate=x⋅Wgate​=[1.00.0​0.01.0​0.00.0​0.00.0​] up=x⋅Wup​=[1.00.0​0.01.0​0.00.0​0.00.0​] SiLU(1.0)=1.0×σ(1.0)≈0.7311 hidden=SiLU(gate)⊙up=[0.73110.0​0.00.7311​0.00.0​0.00.0​]

Output: output=hidden⋅Wdown​≈[0.73110.0​0.00.7311​]

Constraints

  • 1 ≤ M ≤ 65,536
  • 1 ≤ d_model ≤ 8,192
  • 1 ≤ d_ffn ≤ 32,768
  • All tensors are float32 on the GPU.
  • Input values are in the range [-10, 10].
  • Performance is measured with M = 512, d_model = 4,096, d_ffn = 14,336

Starter code (CUDA)

#include <cuda_runtime.h>

// x, W_gate, W_up, W_down, output are device pointers
extern "C" void solve(const float* x, const float* W_gate, const float* W_up, const float* W_down,
                      float* output, int M, int d_model, int d_ffn) {}

Solve it on your GPU

Previous: Linear RecurrenceNext: LoRA Linear

From LeetGPU, CC BY-NC-ND 4.0.