|
15 | 15 | _IS_ROCM_PYTORCH = getattr(torch.version, "hip", None) is not None |
16 | 16 |
|
17 | 17 | SUPPORTED_ROW_DTYPES = (torch.bfloat16, torch.float16, torch.float32) |
| 18 | +SUPPORTED_ROW_WEIGHTING_DTYPES = (torch.bfloat16, torch.float16) |
18 | 19 |
|
19 | 20 | _MAX_BLOCK_HIDDEN = 512 |
20 | 21 | # The forward adds one row at a time, so only a single [BLOCK_H] FP32 accumulator is live. |
@@ -142,6 +143,84 @@ def _weighted_restore_backward_kernel( |
142 | 143 | mask=slot_mask, |
143 | 144 | ) |
144 | 145 |
|
| 146 | + @triton.jit |
| 147 | + def _row_weighting_forward_kernel( |
| 148 | + rows_ptr, |
| 149 | + weights_ptr, |
| 150 | + out_ptr, |
| 151 | + hidden, |
| 152 | + rows_stride, |
| 153 | + weights_stride, |
| 154 | + out_stride, |
| 155 | + BLOCK_H: tl.constexpr, |
| 156 | + ): |
| 157 | + row = tl.program_id(0).to(tl.int64) |
| 158 | + hidden_offsets = tl.program_id(1) * BLOCK_H + tl.arange(0, BLOCK_H) |
| 159 | + hidden_mask = hidden_offsets < hidden |
| 160 | + |
| 161 | + values = tl.load(rows_ptr + row * rows_stride + hidden_offsets, mask=hidden_mask, other=0.0).to(tl.float32) |
| 162 | + weight = tl.load(weights_ptr + row * weights_stride).to(tl.float32) |
| 163 | + tl.store( |
| 164 | + out_ptr + row * out_stride + hidden_offsets, |
| 165 | + (values * weight).to(out_ptr.dtype.element_ty), |
| 166 | + mask=hidden_mask, |
| 167 | + ) |
| 168 | + |
| 169 | + @triton.jit |
| 170 | + def _row_weighting_backward_partial_kernel( |
| 171 | + grad_out_ptr, |
| 172 | + rows_ptr, |
| 173 | + weights_ptr, |
| 174 | + grad_rows_ptr, |
| 175 | + partials_ptr, |
| 176 | + hidden, |
| 177 | + grad_out_stride, |
| 178 | + rows_stride, |
| 179 | + weights_stride, |
| 180 | + grad_rows_stride, |
| 181 | + num_hidden_blocks: tl.constexpr, |
| 182 | + BLOCK_H: tl.constexpr, |
| 183 | + ): |
| 184 | + row = tl.program_id(0).to(tl.int64) |
| 185 | + hidden_block = tl.program_id(1) |
| 186 | + hidden_offsets = hidden_block * BLOCK_H + tl.arange(0, BLOCK_H) |
| 187 | + hidden_mask = hidden_offsets < hidden |
| 188 | + |
| 189 | + upstream = tl.load( |
| 190 | + grad_out_ptr + row * grad_out_stride + hidden_offsets, |
| 191 | + mask=hidden_mask, |
| 192 | + other=0.0, |
| 193 | + ).to(tl.float32) |
| 194 | + values = tl.load( |
| 195 | + rows_ptr + row * rows_stride + hidden_offsets, |
| 196 | + mask=hidden_mask, |
| 197 | + other=0.0, |
| 198 | + ).to(tl.float32) |
| 199 | + weight = tl.load(weights_ptr + row * weights_stride).to(tl.float32) |
| 200 | + |
| 201 | + tl.store( |
| 202 | + grad_rows_ptr + row * grad_rows_stride + hidden_offsets, |
| 203 | + (upstream * weight).to(grad_rows_ptr.dtype.element_ty), |
| 204 | + mask=hidden_mask, |
| 205 | + ) |
| 206 | + partial = tl.sum(upstream * values, axis=0) |
| 207 | + tl.store(partials_ptr + row * num_hidden_blocks + hidden_block, partial) |
| 208 | + |
| 209 | + @triton.jit |
| 210 | + def _row_weighting_backward_reduce_kernel( |
| 211 | + partials_ptr, |
| 212 | + grad_weights_ptr, |
| 213 | + grad_weights_stride, |
| 214 | + NUM_HIDDEN_BLOCKS: tl.constexpr, |
| 215 | + BLOCK_B: tl.constexpr, |
| 216 | + ): |
| 217 | + row = tl.program_id(0).to(tl.int64) |
| 218 | + offsets = tl.arange(0, BLOCK_B) |
| 219 | + mask = offsets < NUM_HIDDEN_BLOCKS |
| 220 | + partials = tl.load(partials_ptr + row * NUM_HIDDEN_BLOCKS + offsets, mask=mask, other=0.0) |
| 221 | + grad_weight = tl.sum(partials, axis=0) |
| 222 | + tl.store(grad_weights_ptr + row * grad_weights_stride, grad_weight) |
| 223 | + |
145 | 224 |
|
146 | 225 | def is_available() -> bool: |
147 | 226 | """Whether this build can run the fused weighted restore at all.""" |
@@ -174,6 +253,16 @@ def _block_hidden(hidden: int, slots: int) -> int: |
174 | 253 | return min(_MAX_BLOCK_HIDDEN, budget, max(16, triton.next_power_of_2(hidden))) |
175 | 254 |
|
176 | 255 |
|
| 256 | +def _row_weighting_block_hidden(hidden: int) -> int: |
| 257 | + """Choose a power-of-two hidden tile for row-local products.""" |
| 258 | + return min(_MAX_BLOCK_HIDDEN, max(16, triton.next_power_of_2(hidden))) |
| 259 | + |
| 260 | + |
| 261 | +def _row_weighting_reduce_block(num_hidden_blocks: int) -> int: |
| 262 | + """Round the per-row partial count up to a power of two for ``tl.arange``.""" |
| 263 | + return max(1, triton.next_power_of_2(num_hidden_blocks)) |
| 264 | + |
| 265 | + |
177 | 266 | def _padded_top_k(top_k: int) -> int: |
178 | 267 | """Round top-k up to a power of two, which ``tl.arange`` requires.""" |
179 | 268 | return max(2, triton.next_power_of_2(top_k)) |
@@ -256,6 +345,114 @@ def backward(ctx, grad_output): |
256 | 345 | return grad_rows, grad_scores, None, None |
257 | 346 |
|
258 | 347 |
|
| 348 | +def assert_row_weighting_supported(rows: torch.Tensor, weights: torch.Tensor) -> None: |
| 349 | + """Reject unsupported per-row weighting configurations before dispatch.""" |
| 350 | + if not _TRITON_AVAILABLE: |
| 351 | + raise RuntimeError('row_weighting_impl="fused" needs Triton, which is not installed in this environment. ' |
| 352 | + 'Install Triton, or set row_weighting_impl="eager".') |
| 353 | + if _IS_ROCM_PYTORCH: |
| 354 | + raise RuntimeError('row_weighting_impl="fused" is not yet supported on ROCm. Set ' |
| 355 | + 'row_weighting_impl="eager" to run here.') |
| 356 | + if rows.device.type != "cuda": |
| 357 | + raise RuntimeError('row_weighting_impl="fused" runs CUDA kernels but rows are on device ' |
| 358 | + f'"{rows.device.type}". Set row_weighting_impl="eager" to run here.') |
| 359 | + if weights.device != rows.device: |
| 360 | + raise RuntimeError('row_weighting_impl="fused" requires rows and weights on the same CUDA device, got ' |
| 361 | + f"rows on {rows.device} and weights on {weights.device}.") |
| 362 | + if rows.dim() != 2: |
| 363 | + raise RuntimeError('row_weighting_impl="fused" requires rows with shape [N, H], got ' |
| 364 | + f"{tuple(rows.shape)}. Set row_weighting_impl=\"eager\" for unsupported shapes.") |
| 365 | + expected_weight_shape = (rows.shape[0], 1) |
| 366 | + if tuple(weights.shape) != expected_weight_shape: |
| 367 | + raise RuntimeError('row_weighting_impl="fused" requires weights with shape [N, 1] matching rows, got ' |
| 368 | + f"{tuple(weights.shape)} for rows {tuple(rows.shape)}.") |
| 369 | + if rows.dtype not in SUPPORTED_ROW_WEIGHTING_DTYPES: |
| 370 | + raise RuntimeError('row_weighting_impl="fused" supports bfloat16 and float16 rows, got ' |
| 371 | + f"{rows.dtype}. Set row_weighting_impl=\"eager\", or use a supported dtype.") |
| 372 | + if weights.dtype != torch.float32: |
| 373 | + raise RuntimeError('row_weighting_impl="fused" requires float32 weights, got ' |
| 374 | + f"{weights.dtype}. Set row_weighting_impl=\"eager\" for unsupported weights.") |
| 375 | + if not rows.is_contiguous(): |
| 376 | + raise RuntimeError('row_weighting_impl="fused" requires contiguous rows. Set row_weighting_impl="eager" ' |
| 377 | + "for non-contiguous row layouts.") |
| 378 | + if not weights.is_contiguous(): |
| 379 | + raise RuntimeError('row_weighting_impl="fused" requires contiguous weights. Set row_weighting_impl="eager" ' |
| 380 | + "for non-contiguous weight layouts.") |
| 381 | + |
| 382 | + |
| 383 | +class _FusedRowWeighting(torch.autograd.Function): |
| 384 | + """Apply one FP32 routing weight per row, with the eager rounding point.""" |
| 385 | + |
| 386 | + @staticmethod |
| 387 | + def forward(ctx, rows, weights): |
| 388 | + output = torch.empty_like(rows) |
| 389 | + ctx.save_for_backward(rows, weights) |
| 390 | + |
| 391 | + n_rows, hidden = rows.shape |
| 392 | + if n_rows == 0 or hidden == 0: |
| 393 | + return output |
| 394 | + |
| 395 | + block_hidden = _row_weighting_block_hidden(hidden) |
| 396 | + grid = (n_rows, triton.cdiv(hidden, block_hidden)) |
| 397 | + _row_weighting_forward_kernel[grid]( |
| 398 | + rows, |
| 399 | + weights, |
| 400 | + output, |
| 401 | + hidden, |
| 402 | + rows.stride(0), |
| 403 | + weights.stride(0), |
| 404 | + output.stride(0), |
| 405 | + BLOCK_H=block_hidden, |
| 406 | + ) |
| 407 | + return output |
| 408 | + |
| 409 | + @staticmethod |
| 410 | + def backward(ctx, grad_output): |
| 411 | + rows, weights = ctx.saved_tensors |
| 412 | + grad_output = grad_output.contiguous() |
| 413 | + grad_rows = torch.empty_like(rows) |
| 414 | + grad_weights = torch.empty_like(weights) |
| 415 | + |
| 416 | + n_rows, hidden = rows.shape |
| 417 | + if n_rows == 0: |
| 418 | + return grad_rows, grad_weights |
| 419 | + if hidden == 0: |
| 420 | + grad_weights.zero_() |
| 421 | + return grad_rows, grad_weights |
| 422 | + |
| 423 | + block_hidden = _row_weighting_block_hidden(hidden) |
| 424 | + num_hidden_blocks = triton.cdiv(hidden, block_hidden) |
| 425 | + partials = torch.empty((n_rows, num_hidden_blocks), dtype=torch.float32, device=rows.device) |
| 426 | + _row_weighting_backward_partial_kernel[(n_rows, num_hidden_blocks)]( |
| 427 | + grad_output, |
| 428 | + rows, |
| 429 | + weights, |
| 430 | + grad_rows, |
| 431 | + partials, |
| 432 | + hidden, |
| 433 | + grad_output.stride(0), |
| 434 | + rows.stride(0), |
| 435 | + weights.stride(0), |
| 436 | + grad_rows.stride(0), |
| 437 | + num_hidden_blocks=num_hidden_blocks, |
| 438 | + BLOCK_H=block_hidden, |
| 439 | + ) |
| 440 | + _row_weighting_backward_reduce_kernel[(n_rows, )]( |
| 441 | + partials, |
| 442 | + grad_weights, |
| 443 | + grad_weights.stride(0), |
| 444 | + NUM_HIDDEN_BLOCKS=num_hidden_blocks, |
| 445 | + BLOCK_B=_row_weighting_reduce_block(num_hidden_blocks), |
| 446 | + ) |
| 447 | + return grad_rows, grad_weights |
| 448 | + |
| 449 | + |
| 450 | +def fused_row_weighting(rows: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: |
| 451 | + """Apply ``weights`` to ``rows`` as ``(rows.float() * weights).to(rows.dtype)``.""" |
| 452 | + assert_row_weighting_supported(rows, weights) |
| 453 | + return _FusedRowWeighting.apply(rows, weights) |
| 454 | + |
| 455 | + |
259 | 456 | def fused_weighted_restore( |
260 | 457 | combined_rows: torch.Tensor, |
261 | 458 | top_scores: torch.Tensor, |
|
0 commit comments