LeetKernels
ProblemsStart solving
Problems

81. INT4 Weight-Only Quantized MatMul medium

Implement a weight-only INT4 quantized matrix multiplication (W4A16), a core kernel used in modern LLM inference. Given a float16 activation matrix x of shape M × K and a weight matrix stored in packed INT4 format, compute the output matrix y = x × WT of shape M × N, where W is the dequantized float16 weight matrix of shape N × K.

Packing format: Each byte of w_q stores two INT4 weights. The high nibble (bits 7–4) holds weight w[n, 2i] and the low nibble (bits 3–0) holds w[n, 2i+1]. INT4 values are stored unsigned in the range [0, 15] with an offset of 8, so the signed weight is nibble − 8, giving values in [−8, 7].

Dequantization: Weights are dequantized group-wise. Each contiguous block of group_size weights along the K dimension shares one float16 scale:

W[n, k] = (w_q_nibble[n, k] - 8) * scales[n, k // group_size]

Implementation Requirements

  • Use only native features (external libraries are not permitted)
  • The solve function signature must remain unchanged
  • The final result must be stored in y

Example

Input (M = 2, N = 4, K = 4, group_size = 2):

Activations x (float16, 2×4): [1.00.0​0.01.0​1.00.0​0.01.0​] Packed weights w_q (uint8, 4×2) with signed INT4 values in brackets: ​0x990xAA0x770x88​0x990xAA0x770x88​​⇒Wint4​=​12−10​12−10​12−10​12−10​​ Scales (float16, 4×2, all entries 0.5): ​0.50.50.50.5​0.50.50.50.5​​⇒Wdequant​=​0.51.0−0.50.0​0.51.0−0.50.0​0.51.0−0.50.0​0.51.0−0.50.0​​ Output y=x×WT (float16, 2×4): [1.01.0​2.02.0​−1.0−1.0​0.00.0​]

Constraints

  • 1 ≤ M, N ≤ 8,192
  • 1 ≤ K ≤ 8,192
  • K is divisible by 2 and by group_size
  • group_size ∈ {2, 4, 8, 16, 32, 64, 128}
  • All tensors are stored in row-major order
  • Input dtype: x and scales are float16; w_q is uint8
  • Output dtype: y is float16
  • Performance is measured with M = 4,096, N = 4,096, K = 4,096, group_size = 128

Starter code (CUDA)

#include <cuda_fp16.h>
#include <cuda_runtime.h>
#include <stdint.h>

// x, w_q, scales, y are device pointers
extern "C" void solve(const __half* x, const uint8_t* w_q, const __half* scales, __half* y, int M,
                      int N, int K, int group_size) {}

Solve it on your GPU

Previous: Grouped Query AttentionNext: Linear Recurrence

From LeetGPU, CC BY-NC-ND 4.0.