-
Notifications
You must be signed in to change notification settings - Fork 63
[WS2][kernels] Deterministic Qwen3 SwiGLU forward (CUDA SM90 + Triton) #258
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bitborne
wants to merge
2
commits into
RL-Align:main
Choose a base branch
from
bitborne:codex/qwen3-swiglu-forward-sm90
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| #!/usr/bin/env python | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # Copyright (c) 2026 RL-Kernel Contributors | ||
| """Benchmark Qwen3 TP-local SwiGLU forward backends on Hopper.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| from collections.abc import Callable | ||
|
|
||
| import torch | ||
| import torch.nn.functional as F | ||
|
|
||
| from rl_engine.kernels.ops.cuda.activation.swiglu import SwiGLUSM90Op | ||
| from rl_engine.kernels.ops.triton.activation.swiglu import TritonSwiGLUOp | ||
|
|
||
|
|
||
| def _bench(fn: Callable[[], torch.Tensor], warmup: int, iterations: int) -> float: | ||
| for _ in range(warmup): | ||
| fn() | ||
| torch.cuda.synchronize() | ||
|
|
||
| start = torch.cuda.Event(enable_timing=True) | ||
| end = torch.cuda.Event(enable_timing=True) | ||
| start.record() | ||
| for _ in range(iterations): | ||
| fn() | ||
| end.record() | ||
| end.synchronize() | ||
| return start.elapsed_time(end) / iterations | ||
|
|
||
|
|
||
| def _parse_args() -> argparse.Namespace: | ||
| parser = argparse.ArgumentParser(description=__doc__) | ||
| parser.add_argument("--rows", type=int, default=4096, help="M_local token rows") | ||
| parser.add_argument( | ||
| "--width", type=int, default=6144, help="Qwen3-8B TP=2 local intermediate width" | ||
| ) | ||
| parser.add_argument("--warmup", type=int, default=20) | ||
| parser.add_argument("--iterations", type=int, default=100) | ||
| return parser.parse_args() | ||
|
|
||
|
|
||
| def main() -> None: | ||
| args = _parse_args() | ||
| if not torch.cuda.is_available(): | ||
| raise RuntimeError("benchmark_swiglu.py requires CUDA") | ||
| major, minor = torch.cuda.get_device_capability() | ||
| if major != 9: | ||
| raise RuntimeError(f"benchmark_swiglu.py requires Hopper SM90, got sm_{major}{minor}") | ||
|
|
||
| generator = torch.Generator(device="cuda").manual_seed(239) | ||
| shape = (args.rows, args.width) | ||
| gate = torch.randn(shape, device="cuda", dtype=torch.bfloat16, generator=generator) | ||
| up = torch.randn(shape, device="cuda", dtype=torch.bfloat16, generator=generator) | ||
| cuda_op = SwiGLUSM90Op() | ||
| triton_op = TritonSwiGLUOp() | ||
|
|
||
| timings = { | ||
| "PyTorch": _bench( | ||
| lambda: F.silu(gate.float()).mul(up.float()).bfloat16(), | ||
| args.warmup, | ||
| args.iterations, | ||
| ), | ||
| "CUDA SM90": _bench(lambda: cuda_op(gate, up), args.warmup, args.iterations), | ||
| "Triton": _bench(lambda: triton_op(gate, up), args.warmup, args.iterations), | ||
| } | ||
|
|
||
| print(f"device={torch.cuda.get_device_name()} shape={shape} dtype=bf16") | ||
| print("backend latency_ms") | ||
| for name, latency in timings.items(): | ||
| print(f"{name:<14} {latency:>10.4f}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // Copyright (c) 2026 RL-Kernel Contributors | ||
|
|
||
| #include <torch/extension.h> | ||
|
|
||
| #include <ATen/cuda/CUDAContext.h> | ||
| #include <c10/cuda/CUDAException.h> | ||
| #include <c10/cuda/CUDAGuard.h> | ||
| #include <cuda_bf16.h> | ||
| #include <cuda_runtime.h> | ||
|
|
||
| #include <algorithm> | ||
| #include <cstdint> | ||
|
|
||
| namespace { | ||
|
|
||
| constexpr int kThreads = 256; | ||
| constexpr int64_t kMaxBlocks = 65535; | ||
|
|
||
| __device__ __forceinline__ float swiglu_fp32(float gate, float up) { | ||
| const float sigmoid_gate = 1.0f / (1.0f + expf(-gate)); | ||
| return (gate * sigmoid_gate) * up; | ||
| } | ||
|
|
||
| __global__ void swiglu_forward_kernel(const __nv_bfloat16 *__restrict__ gate, | ||
| const __nv_bfloat16 *__restrict__ up, | ||
| __nv_bfloat16 *__restrict__ output, | ||
| int64_t numel) { | ||
| const int64_t stride = static_cast<int64_t>(blockDim.x) * gridDim.x * 2; | ||
| for (int64_t index = | ||
| (static_cast<int64_t>(blockIdx.x) * blockDim.x + threadIdx.x) * 2; | ||
| index < numel; index += stride) { | ||
| if (index + 1 < numel) { | ||
| const auto gate2 = | ||
| reinterpret_cast<const __nv_bfloat162 *>(gate)[index / 2]; | ||
| const auto up2 = reinterpret_cast<const __nv_bfloat162 *>(up)[index / 2]; | ||
| reinterpret_cast<__nv_bfloat162 *>(output)[index / 2] = | ||
| __floats2bfloat162_rn( | ||
| swiglu_fp32(__low2float(gate2), __low2float(up2)), | ||
| swiglu_fp32(__high2float(gate2), __high2float(up2))); | ||
| } else { | ||
| output[index] = __float2bfloat16_rn(swiglu_fp32( | ||
| __bfloat162float(gate[index]), __bfloat162float(up[index]))); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| void check_bf16_tensor(const torch::Tensor &tensor, const char *name) { | ||
| TORCH_CHECK(tensor.is_cuda(), name, " must be a CUDA tensor"); | ||
| TORCH_CHECK(tensor.is_contiguous(), name, " must be contiguous"); | ||
| TORCH_CHECK(tensor.scalar_type() == torch::kBFloat16, name, | ||
| " must have dtype torch.bfloat16"); | ||
| TORCH_CHECK(reinterpret_cast<uintptr_t>(tensor.data_ptr()) % | ||
| alignof(__nv_bfloat162) == | ||
| 0, | ||
| name, " must be 4-byte aligned for bfloat162 access"); | ||
| } | ||
|
|
||
| void check_sm90(const torch::Tensor &tensor) { | ||
| c10::cuda::CUDAGuard device_guard(tensor.device()); | ||
| const auto *properties = at::cuda::getCurrentDeviceProperties(); | ||
| TORCH_CHECK(properties->major == 9, | ||
| "SwiGLU SM90 kernel requires Hopper compute capability 9.x, got " | ||
| "sm_", | ||
| properties->major, properties->minor); | ||
| } | ||
|
|
||
| int launch_blocks(int64_t numel) { | ||
| const int64_t work_items = (numel + 1) / 2; | ||
| return static_cast<int>( | ||
| std::min<int64_t>((work_items + kThreads - 1) / kThreads, kMaxBlocks)); | ||
| } | ||
|
|
||
| } // namespace | ||
|
|
||
| torch::Tensor swiglu_forward_sm90(torch::Tensor gate, torch::Tensor up) { | ||
| check_bf16_tensor(gate, "gate"); | ||
| check_bf16_tensor(up, "up"); | ||
| TORCH_CHECK(gate.sizes() == up.sizes(), | ||
| "gate and up must have the same shape"); | ||
| TORCH_CHECK(gate.device() == up.device(), | ||
| "gate and up must be on the same device"); | ||
| check_sm90(gate); | ||
|
|
||
| auto output = torch::empty_like(gate); | ||
| if (gate.numel() == 0) { | ||
| return output; | ||
| } | ||
|
|
||
| c10::cuda::CUDAGuard device_guard(gate.device()); | ||
| cudaStream_t stream = at::cuda::getCurrentCUDAStream(); | ||
| swiglu_forward_kernel<<<launch_blocks(gate.numel()), kThreads, 0, stream>>>( | ||
| reinterpret_cast<const __nv_bfloat16 *>(gate.data_ptr()), | ||
| reinterpret_cast<const __nv_bfloat16 *>(up.data_ptr()), | ||
| reinterpret_cast<__nv_bfloat16 *>(output.data_ptr()), gate.numel()); | ||
| C10_CUDA_KERNEL_LAUNCH_CHECK(); | ||
| return output; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Remove literal quote characters from the export value.
This expression exports
''for the empty default and'1'when the value is1.envs.env_flagrejects both values, so setup.py raisesValueErrorand blocks the GPU CI build.Proposed fix
📝 Committable suggestion
🧰 Tools
🪛 Shellcheck (0.11.0)
[info] 141-159: Expressions don't expand in single quotes, use double quotes for that.
(SC2016)
🤖 Prompt for AI Agents
Source: Linters/SAST tools