jkim96 commited on
Commit
9ca5706
·
verified ·
1 Parent(s): 0cb768d

Add DASH-Q remote-code inference (Triton decode kernel)

Browse files
Files changed (3) hide show
  1. README.md +3 -4
  2. dashq_kernel.py +126 -38
  3. modeling_dashq.py +7 -9
README.md CHANGED
@@ -32,10 +32,9 @@ inputs = tokenizer(text, return_tensors="pt").to(model.device)
32
  print(tokenizer.decode(model.generate(**inputs, max_new_tokens=256)[0]))
33
  ```
34
 
35
- `trust_remote_code=True` is required: the checkpoint ships the quantized-layer
36
- implementation (`modeling_dashq.py`) and a Triton weight-only GEMV decode kernel
37
- (`dashq_kernel.py`). Without Triton or on CPU the model falls back to a PyTorch
38
- dequantize-and-matmul path.
39
 
40
  ### Requirements
41
 
 
32
  print(tokenizer.decode(model.generate(**inputs, max_new_tokens=256)[0]))
33
  ```
34
 
35
+ `trust_remote_code=True` is required: the checkpoint ships its quantized-layer
36
+ implementation (`modeling_dashq.py`) and Triton kernels (`dashq_kernel.py`).
37
+ Without Triton, or on CPU, it falls back to dequantize-and-matmul in PyTorch.
 
38
 
39
  ### Requirements
40
 
dashq_kernel.py CHANGED
@@ -1,18 +1,16 @@
1
- """Triton weight-only GEMV backend for DASH-Q packed checkpoints.
2
 
3
- Group-wise asymmetric integer weights (the format DASH-Q emits) are stored
4
- K-major so that a decode-time GEMV reads each packed word exactly once with
5
- fully coalesced loads:
6
 
7
- W_q : (K // elements_per_word, N) int32 (packed along K, N contiguous)
8
- s,z : (K // group_size, N) (one group per program)
9
 
10
- Supported bit widths: 2, 3, 4, 8 (and 1). 3-bit uses two bit-planes -- a
11
- 2-bit plane plus a 1-bit plane -- which is exactly 3 bits per weight and is
12
- not covered by existing kernel libraries.
13
 
14
- Batched inputs (prefill) fall back to an unpack-and-matmul path that uses the
15
- same K-major buffers, so the original torch buffers can be released.
16
  """
17
  from __future__ import annotations
18
 
@@ -26,11 +24,13 @@ try:
26
  import triton.language as tl
27
 
28
  TRITON_AVAILABLE = True
29
- except Exception: # pragma: no cover - triton is an optional dependency
30
  TRITON_AVAILABLE = False
31
 
32
  SUPPORTED_NBITS = (1, 2, 3, 4, 8)
33
 
 
 
34
 
35
  if TRITON_AVAILABLE:
36
 
@@ -46,7 +46,7 @@ if TRITON_AVAILABLE:
46
  offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
47
  offs_n = tl.max_contiguous(tl.multiple_of(offs_n, BLOCK_N), BLOCK_N)
48
 
49
- # one scale/zero group per program (2 * BLOCK_K == GS)
50
  k_m = (pid_k * BLOCK_K) // GS
51
  scales = tl.load(s_ptr + k_m * N + offs_n).to(tl.float32)
52
  zeros = tl.load(z_ptr + k_m * N + offs_n).to(tl.float32)
@@ -76,12 +76,69 @@ if TRITON_AVAILABLE:
76
  b = (q.to(tl.float32) - zeros[None, :]) * scales[None, :]
77
  acc += tl.sum(a[:, None] * b, axis=0)
78
  offs_k += BLOCK_K
79
-
80
  tl.atomic_add(y_ptr + offs_n, acc, sem="relaxed")
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  def _pack_kmajor(q_kn: torch.Tensor, bits: int) -> torch.Tensor:
84
- """(K, N) uint8 codes -> (K // eps, N) int32, value k in word k // eps."""
85
  K, N = q_kn.shape
86
  eps = 32 // bits
87
  v = q_kn.to(torch.int32).reshape(K // eps, eps, N)
@@ -100,7 +157,7 @@ def _unpack_kmajor(words: torch.Tensor, bits: int, K: int) -> torch.Tensor:
100
 
101
 
102
  class TritonQuantLinear(nn.Module):
103
- """Decode-optimized replacement for a DASH-Q PackedQuantizedLinear."""
104
 
105
  def __init__(
106
  self,
@@ -118,7 +175,7 @@ class TritonQuantLinear(nn.Module):
118
  if not TRITON_AVAILABLE:
119
  raise RuntimeError("Triton is not available.")
120
  if nbits not in SUPPORTED_NBITS:
121
- raise ValueError(f"Unsupported nbits for the Triton backend: {nbits}")
122
 
123
  out_features, in_features = W_int.shape
124
  if in_features % group_size != 0:
@@ -153,8 +210,7 @@ class TritonQuantLinear(nn.Module):
153
  else:
154
  self.bias = None
155
 
156
- # accumulator is seeded with the bias, so the kernel never adds it
157
- # (each K-split program contributes once via atomic_add)
158
  acc_init = torch.zeros(out_features, dtype=torch.float32, device=self.W_q.device)
159
  if bias is not None:
160
  acc_init.copy_(self.bias.float())
@@ -166,7 +222,7 @@ class TritonQuantLinear(nn.Module):
166
  )
167
 
168
  def dequantize_weight(self, dtype: torch.dtype) -> torch.Tensor:
169
- """Returns W^T as (in_features, out_features), matching the K-major layout."""
170
  if self.nbits == 3:
171
  q = (_unpack_kmajor(self.W_q, 2, self.in_features).to(torch.int32) << 1) | (
172
  _unpack_kmajor(self.W_lo, 1, self.in_features).to(torch.int32)
@@ -177,37 +233,69 @@ class TritonQuantLinear(nn.Module):
177
  z = self.zero.repeat_interleave(self.group_size, dim=0).to(dtype)
178
  return (q.to(dtype) - z) * s
179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  def forward(self, x: torch.Tensor) -> torch.Tensor:
181
  shape = x.shape
182
  tokens = x.numel() // shape[-1]
183
  if tokens == 1 and x.is_cuda:
184
  self._acc.copy_(self._acc_init)
185
  _dashq_gemv_kernel[self._grid](
186
- x.reshape(-1),
187
- self.W_q,
188
- self.W_lo,
189
- self.scale,
190
- self.zero,
191
- self._acc,
192
- self.out_features,
193
- self.in_features,
194
- self.nbits,
195
- self.eps,
196
- self.group_size,
197
- self.block_n,
198
- self.block_k,
199
  num_warps=self.num_warps,
200
  )
201
  return self._acc.to(x.dtype).reshape(*shape[:-1], self.out_features)
202
 
203
- w_t = self.dequantize_weight(x.dtype)
204
- out = x.reshape(tokens, -1) @ w_t
 
 
 
205
  if self.bias is not None:
206
- out = out + self.bias.to(x.dtype)
207
- return out.reshape(*shape[:-1], self.out_features)
208
 
209
  def extra_repr(self) -> str:
210
  return (
211
  f"in_features={self.in_features}, out_features={self.out_features}, "
212
- f"nbits={self.nbits}, group_size={self.group_size}, backend=triton"
213
  )
 
1
+ """Triton kernels for group-wise asymmetric integer weights.
2
 
3
+ Weights are stored K-major: W_q has shape (K // elements_per_word, N) with
4
+ values packed along K, and scale/zero have shape (K // group_size, N).
 
5
 
6
+ Three kernels are selected by the number of input rows M:
 
7
 
8
+ M == 1 GEMV
9
+ 2 <= M <= 32 fused dequantize-GEMM with split-K
10
+ M > 32 fused dequantize-GEMM, accumulator kept in registers
11
 
12
+ Supported bit widths are 1, 2, 3, 4 and 8. 3-bit is stored as a 2-bit plane
13
+ plus a 1-bit plane, so it occupies exactly 3 bits per weight.
14
  """
15
  from __future__ import annotations
16
 
 
24
  import triton.language as tl
25
 
26
  TRITON_AVAILABLE = True
27
+ except Exception: # triton is optional
28
  TRITON_AVAILABLE = False
29
 
30
  SUPPORTED_NBITS = (1, 2, 3, 4, 8)
31
 
32
+ _GEMM_CONFIG_CACHE = {}
33
+
34
 
35
  if TRITON_AVAILABLE:
36
 
 
46
  offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
47
  offs_n = tl.max_contiguous(tl.multiple_of(offs_n, BLOCK_N), BLOCK_N)
48
 
49
+ # 2 * BLOCK_K == GS, so a program covers exactly one scale group.
50
  k_m = (pid_k * BLOCK_K) // GS
51
  scales = tl.load(s_ptr + k_m * N + offs_n).to(tl.float32)
52
  zeros = tl.load(z_ptr + k_m * N + offs_n).to(tl.float32)
 
76
  b = (q.to(tl.float32) - zeros[None, :]) * scales[None, :]
77
  acc += tl.sum(a[:, None] * b, axis=0)
78
  offs_k += BLOCK_K
 
79
  tl.atomic_add(y_ptr + offs_n, acc, sem="relaxed")
80
 
81
+ @triton.jit
82
+ def _dashq_gemm_kernel(
83
+ x_ptr, w_ptr, lo_ptr, s_ptr, z_ptr, y_ptr,
84
+ M, N, K,
85
+ NBITS: tl.constexpr, EPS: tl.constexpr, GS: tl.constexpr,
86
+ BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
87
+ SPLIT_K: tl.constexpr, OUT_DTYPE: tl.constexpr,
88
+ ):
89
+ """y[M, N] = x[M, K] @ dequantize(w)[K, N]
90
+
91
+ BLOCK_K divides the group size, so a K-tile lies inside one group and the
92
+ scale/zero load is a single (1, BLOCK_N) vector.
93
+ """
94
+ pid_m = tl.program_id(0)
95
+ pid_n = tl.program_id(1)
96
+ pid_k = tl.program_id(2)
97
+
98
+ offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
99
+ offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
100
+ mask_m = offs_m < M
101
+ mask_n = offs_n < N
102
+
103
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
104
+
105
+ for t in range(pid_k, tl.cdiv(K, BLOCK_K), SPLIT_K):
106
+ k0 = t * BLOCK_K
107
+ offs_k = k0 + tl.arange(0, BLOCK_K)
108
+ mask_k = offs_k < K
109
+
110
+ x = tl.load(x_ptr + offs_m[:, None] * K + offs_k[None, :],
111
+ mask=mask_m[:, None] & mask_k[None, :], other=0.0)
112
+
113
+ if NBITS == 3:
114
+ hw = tl.load(w_ptr + (offs_k // 16)[:, None] * N + offs_n[None, :],
115
+ mask=mask_k[:, None] & mask_n[None, :], other=0)
116
+ lw = tl.load(lo_ptr + (offs_k // 32)[:, None] * N + offs_n[None, :],
117
+ mask=mask_k[:, None] & mask_n[None, :], other=0)
118
+ q = (((hw >> (((offs_k % 16) * 2)[:, None])) & 3) << 1) | (
119
+ (lw >> ((offs_k % 32)[:, None])) & 1)
120
+ else:
121
+ wv = tl.load(w_ptr + (offs_k // EPS)[:, None] * N + offs_n[None, :],
122
+ mask=mask_k[:, None] & mask_n[None, :], other=0)
123
+ q = (wv >> (((offs_k % EPS) * NBITS)[:, None])) & ((1 << NBITS) - 1)
124
+
125
+ g = k0 // GS
126
+ s = tl.load(s_ptr + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
127
+ z = tl.load(z_ptr + g * N + offs_n, mask=mask_n, other=0.0).to(tl.float32)
128
+ w = (q.to(tl.float32) - z[None, :]) * s[None, :]
129
+
130
+ acc += tl.dot(x, w.to(x.dtype), out_dtype=tl.float32)
131
+
132
+ out = acc.to(OUT_DTYPE)
133
+ y_ptrs = y_ptr + offs_m[:, None] * N + offs_n[None, :]
134
+ if SPLIT_K == 1:
135
+ tl.store(y_ptrs, out, mask=mask_m[:, None] & mask_n[None, :])
136
+ else:
137
+ tl.atomic_add(y_ptrs, out, mask=mask_m[:, None] & mask_n[None, :], sem="relaxed")
138
+
139
 
140
  def _pack_kmajor(q_kn: torch.Tensor, bits: int) -> torch.Tensor:
141
+ """(K, N) codes -> (K // eps, N) int32, value k in word k // eps."""
142
  K, N = q_kn.shape
143
  eps = 32 // bits
144
  v = q_kn.to(torch.int32).reshape(K // eps, eps, N)
 
157
 
158
 
159
  class TritonQuantLinear(nn.Module):
160
+ """Linear layer over group-wise asymmetric integer weights."""
161
 
162
  def __init__(
163
  self,
 
175
  if not TRITON_AVAILABLE:
176
  raise RuntimeError("Triton is not available.")
177
  if nbits not in SUPPORTED_NBITS:
178
+ raise ValueError(f"Unsupported nbits: {nbits}")
179
 
180
  out_features, in_features = W_int.shape
181
  if in_features % group_size != 0:
 
210
  else:
211
  self.bias = None
212
 
213
+ # The GEMV accumulates with atomics, so it starts from the bias.
 
214
  acc_init = torch.zeros(out_features, dtype=torch.float32, device=self.W_q.device)
215
  if bias is not None:
216
  acc_init.copy_(self.bias.float())
 
222
  )
223
 
224
  def dequantize_weight(self, dtype: torch.dtype) -> torch.Tensor:
225
+ """Returns W^T with shape (in_features, out_features)."""
226
  if self.nbits == 3:
227
  q = (_unpack_kmajor(self.W_q, 2, self.in_features).to(torch.int32) << 1) | (
228
  _unpack_kmajor(self.W_lo, 1, self.in_features).to(torch.int32)
 
233
  z = self.zero.repeat_interleave(self.group_size, dim=0).to(dtype)
234
  return (q.to(dtype) - z) * s
235
 
236
+ # (BLOCK_M, BLOCK_N, SPLIT_K, num_warps, num_stages), largest tile first;
237
+ # the first entry that fits in shared memory is cached per shape.
238
+ _SMALL_M_CONFIGS = ((16, 64, 8, 4, 2), (16, 64, 4, 4, 1))
239
+ _LARGE_M_CONFIGS = ((128, 128, 1, 8, 4), (128, 128, 1, 8, 3),
240
+ (128, 64, 1, 4, 3), (64, 64, 1, 4, 2))
241
+
242
+ def _gemm(self, x2d: torch.Tensor) -> torch.Tensor:
243
+ M = x2d.shape[0]
244
+ N, K, gs = self.out_features, self.in_features, self.group_size
245
+ block_k = min(gs, 32)
246
+ configs = self._SMALL_M_CONFIGS if M <= 32 else self._LARGE_M_CONFIGS
247
+ cache_key = (M <= 32, N, K, gs, self.nbits)
248
+ if cache_key in _GEMM_CONFIG_CACHE:
249
+ configs = (_GEMM_CONFIG_CACHE[cache_key],)
250
+
251
+ tl_dtype = tl.float16 if self.out_dtype == torch.float16 else tl.bfloat16
252
+ last_err = None
253
+ for cfg in configs:
254
+ block_m, block_n, split_k, warps, stages = cfg
255
+ split_k = min(split_k, max(1, K // block_k))
256
+ alloc = torch.empty if split_k == 1 else torch.zeros
257
+ y = alloc(M, N, dtype=self.out_dtype, device=x2d.device)
258
+ grid = (triton.cdiv(M, block_m), triton.cdiv(N, block_n), split_k)
259
+ try:
260
+ _dashq_gemm_kernel[grid](
261
+ x2d, self.W_q, self.W_lo, self.scale, self.zero, y,
262
+ M, N, K,
263
+ self.nbits, self.eps, gs,
264
+ block_m, block_n, block_k, split_k, tl_dtype,
265
+ num_warps=warps, num_stages=stages,
266
+ )
267
+ except triton.runtime.errors.OutOfResources as exc:
268
+ last_err = exc
269
+ continue
270
+ _GEMM_CONFIG_CACHE[cache_key] = cfg
271
+ return y
272
+ raise last_err
273
+
274
  def forward(self, x: torch.Tensor) -> torch.Tensor:
275
  shape = x.shape
276
  tokens = x.numel() // shape[-1]
277
  if tokens == 1 and x.is_cuda:
278
  self._acc.copy_(self._acc_init)
279
  _dashq_gemv_kernel[self._grid](
280
+ x.reshape(-1), self.W_q, self.W_lo, self.scale, self.zero, self._acc,
281
+ self.out_features, self.in_features,
282
+ self.nbits, self.eps, self.group_size,
283
+ self.block_n, self.block_k,
 
 
 
 
 
 
 
 
 
284
  num_warps=self.num_warps,
285
  )
286
  return self._acc.to(x.dtype).reshape(*shape[:-1], self.out_features)
287
 
288
+ x2d = x.reshape(tokens, -1)
289
+ if x.is_cuda and TRITON_AVAILABLE:
290
+ out = self._gemm(x2d)
291
+ else:
292
+ out = x2d @ self.dequantize_weight(x.dtype)
293
  if self.bias is not None:
294
+ out = out + self.bias.to(out.dtype)
295
+ return out.to(x.dtype).reshape(*shape[:-1], self.out_features)
296
 
297
  def extra_repr(self) -> str:
298
  return (
299
  f"in_features={self.in_features}, out_features={self.out_features}, "
300
+ f"nbits={self.nbits}, group_size={self.group_size}"
301
  )
modeling_dashq.py CHANGED
@@ -1,13 +1,11 @@
1
- """Self-contained DASH-Q inference code for this checkpoint.
2
 
3
  Generated by export_hf_repo.py -- do not edit by hand.
4
 
5
- Weights are stored as group-wise asymmetric integers packed into int32 words.
6
- The layout of every quantized layer is described by `dashq_config.json` in this
7
- repository. At load time each quantized module is converted to the K-major
8
- layout used by the DASH-Q Triton decode kernel (`dashq_kernel.py`); when Triton
9
- is unavailable (e.g. CPU) the modules fall back to an unpack-and-matmul path in
10
- pure PyTorch.
11
  """
12
  from __future__ import annotations
13
 
@@ -38,7 +36,7 @@ def _unpack_int_values(packed: torch.Tensor, nbits: int, numel: int) -> torch.Te
38
 
39
 
40
  class DashQPackedLinear(nn.Module):
41
- """Holds the checkpoint buffers; converted to the Triton kernel after load."""
42
 
43
  def __init__(self, in_features: int, out_features: int, nbits: int, group_size: int,
44
  bias: bool, dtype: torch.dtype, quant_in_features: Optional[int] = None) -> None:
@@ -203,7 +201,7 @@ class DashQQwen3_5MoeForConditionalGeneration(Qwen3_5MoeForConditionalGeneration
203
  return model
204
 
205
  def build_dashq_kernels(self, verbose: bool = True) -> "DashQQwen3_5MoeForConditionalGeneration":
206
- """Convert packed buffers to the Triton decode kernel (no-op off CUDA)."""
207
  total = built = 0
208
  for module in self.modules():
209
  if isinstance(module, DashQPackedLinear):
 
1
+ """Inference code for this DASH-Q checkpoint.
2
 
3
  Generated by export_hf_repo.py -- do not edit by hand.
4
 
5
+ Weights are group-wise asymmetric integers packed into int32 words; the layout of
6
+ each quantized layer is described by `dashq_config.json`. At load time the layers
7
+ are converted to the format used by the Triton kernels in `dashq_kernel.py`, with
8
+ a PyTorch dequantize-and-matmul fallback when Triton is unavailable.
 
 
9
  """
10
  from __future__ import annotations
11
 
 
36
 
37
 
38
  class DashQPackedLinear(nn.Module):
39
+ """Checkpoint buffers for one quantized layer."""
40
 
41
  def __init__(self, in_features: int, out_features: int, nbits: int, group_size: int,
42
  bias: bool, dtype: torch.dtype, quant_in_features: Optional[int] = None) -> None:
 
201
  return model
202
 
203
  def build_dashq_kernels(self, verbose: bool = True) -> "DashQQwen3_5MoeForConditionalGeneration":
204
+ """Move the packed buffers to the Triton kernel layout (no-op off CUDA)."""
205
  total = built = 0
206
  for module in self.modules():
207
  if isinstance(module, DashQPackedLinear):