Skip to content

Commit aaa31ad

Browse files
authored
[Vulkan] Fuse SwiGLU elementwise operations (pytorch#22979)
### Summary SwiGLU currently runs a sigmoid and two multiplies as separate Vulkan dispatches. Fuse `gate * sigmoid(gate) * up` into one binary kernel. For Qwen3-0.6B, this removes 56 dispatches per token (737 → 681). Models need to be re-exported to use the fusion. The matcher handles either multiply operand order and skips shared sigmoid/SiLU intermediates. The fused op reuses the existing binary-op broadcasting, packing, and dynamic-resize logic for FP16/FP32 buffers and 3D textures. FP16 inputs are evaluated in FP32 with one output conversion, so results can differ slightly from the unfused intermediate rounding. On an Apple M1 Pro with MoltenVK, Qwen3-0.6B W4 (group size 32, FP16 storage, context limit 1024): | Prompt tokens | Median decode ms/token, before → after | Median paired decode TPS gain | Median prefill ms, before → after | | --- | --- | --- | --- | | 41 | 20.47 → 19.52 | +4.1% | 106.5 → 106.0 | | 768 | 21.87 → 20.59 | +6.5% | 662.5 → 656.5 | Four alternating pairs per prompt, full warmup, and 64 measured decode tokens per run using the same unprofiled Release runner. All eight pairs favored fusion, with identical generated text within each prompt. Prefill showed no regression in these runs. Both benchmark arms include the W4 specialization from pytorch#22973 and the merged view removal from pytorch#22898; this PR contains only SwiGLU fusion. Both runners used the same 255-token prefill chunk cap to respect the export's shape bound. Adreno performance has not been measured. ### Test plan All 21 tests in `backends/vulkan/test/test_vulkan_passes.py` passed. The five new SwiGLU tests cover operand order, broadcasting, dynamic projection ordering, shared intermediates, and mixed precision; they were rerun after test cleanup. All 56 cases selected by `vulkan_compute_api_test --gtest_filter='*VulkanSwiGLUTest*'` passed on MoltenVK. Each exercises row counts 1 → 7 → 63 → 1, covering FP16/FP32, buffers/textures, packed layouts, odd widths, broadcasting, and the 3072-wide LLM case. Results are checked against an independent float reference and the unfused GPU path with half-precision rounding bounds. Full model runs also exercised prefill chunks up to 255 followed by decode. The new shaders and C++ dispatch code built in Release. Python/C++ lint and formatting checks passed. GPU traces confirmed that the only dispatch-count changes were 28 fewer sigmoid kernels, 56 fewer multiply kernels, and 28 new SwiGLU kernels. Authored with assistance from OpenAI Codex. cc @SS-JIA @manuelcandales @digantdesai @cbilgin
1 parent 9cced90 commit aaa31ad

12 files changed

Lines changed: 358 additions & 0 deletions

‎backends/vulkan/custom_ops_lib.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1131,6 +1131,18 @@ def sdpa_impl(
11311131
lib.impl(name, sdpa_impl, "CompositeExplicitAutograd")
11321132
sdpa_op = getattr(getattr(torch.ops, namespace), name)
11331133

1134+
################
1135+
## swiglu ##
1136+
################
1137+
1138+
1139+
def swiglu_impl(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor:
1140+
return (gate * torch.sigmoid(gate)) * up
1141+
1142+
1143+
lib.define("swiglu(Tensor gate, Tensor up) -> Tensor")
1144+
lib.impl("swiglu", swiglu_impl, "CompositeExplicitAutograd")
1145+
11341146
################
11351147
## rms_norm ##
11361148
################

‎backends/vulkan/op_registry.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,16 @@ def register_binaryop_cpp_ops():
272272
)
273273

274274

275+
@update_features(exir_ops.edge.et_vk.swiglu.default)
276+
def register_swiglu():
277+
return OpFeatures(
278+
inputs_storage=utils.ANY_STORAGE,
279+
inputs_dtypes=utils.FP_T,
280+
supports_resize=True,
281+
supports_highdim=True,
282+
)
283+
284+
275285
@update_features(
276286
[
277287
exir_ops.edge.aten.eq.Tensor,

‎backends/vulkan/patterns/BUCK‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ fbcode_target(_kind = runtime.python_library,
2121
"weight_packing_utils.py",
2222
"sdpa.py",
2323
"select_as_symint.py",
24+
"swiglu.py",
2425
],
2526
visibility = [
2627
"//executorch/backends/...",

‎backends/vulkan/patterns/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828

2929
import executorch.backends.vulkan.patterns.select_as_symint # noqa
3030

31+
import executorch.backends.vulkan.patterns.swiglu # noqa
32+
3133
import torch
3234

3335
from executorch.backends.vulkan.patterns.pattern_registry import (

‎backends/vulkan/patterns/swiglu.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Copyright (c) Meta Platforms, Inc. and affiliates.
2+
# All rights reserved.
3+
#
4+
# This source code is licensed under the BSD-style license found in the
5+
# LICENSE file in the root directory of this source tree.
6+
7+
from typing import Optional
8+
9+
import torch
10+
from executorch.exir import ExportedProgram
11+
from executorch.exir.dialects._ops import ops as exir_ops
12+
13+
from .pattern_registry import (
14+
PatternMatch,
15+
register_pattern_detector,
16+
register_pattern_replacement,
17+
)
18+
19+
20+
@register_pattern_detector("swiglu")
21+
def find_swiglu_pattern(node: torch.fx.Node) -> Optional[PatternMatch]:
22+
if node.target != exir_ops.edge.aten.mul.Tensor:
23+
return None
24+
25+
for silu, up in (node.args, node.args[::-1]):
26+
if (
27+
not isinstance(silu, torch.fx.Node)
28+
or not isinstance(up, torch.fx.Node)
29+
or silu.target != exir_ops.edge.aten.mul.Tensor
30+
or len(silu.users) != 1
31+
):
32+
continue
33+
for gate, sigmoid in (silu.args, silu.args[::-1]):
34+
if (
35+
not isinstance(gate, torch.fx.Node)
36+
or not isinstance(sigmoid, torch.fx.Node)
37+
or sigmoid.target != exir_ops.edge.aten.sigmoid.default
38+
or sigmoid.args != (gate,)
39+
or len(sigmoid.users) != 1
40+
):
41+
continue
42+
values = [n.meta.get("val") for n in (gate, up, sigmoid, silu, node)]
43+
if not all(isinstance(v, torch.Tensor) for v in values):
44+
continue
45+
if not all(v.dtype == values[0].dtype for v in values):
46+
continue
47+
if values[0].dtype not in (torch.float16, torch.float32):
48+
continue
49+
return PatternMatch(
50+
[gate, up], [node], [sigmoid, silu, node], anchor_node=node
51+
)
52+
return None
53+
54+
55+
@register_pattern_replacement("swiglu")
56+
def replace_swiglu_pattern(
57+
ep: ExportedProgram, graph_module: torch.fx.GraphModule, match: PatternMatch
58+
):
59+
# The up projection can occur after sigmoid/mul, so insert at the final mul.
60+
with graph_module.graph.inserting_before(match.anchor_node):
61+
fused = graph_module.graph.call_function(
62+
exir_ops.edge.et_vk.swiglu.default, tuple(match.input_nodes)
63+
)
64+
fused.meta = match.anchor_node.meta.copy()
65+
match.anchor_node.replace_all_uses_with(fused)

‎backends/vulkan/runtime/graph/ops/glsl/binary_op_buffer.glsl‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,11 @@ ${layout_declare_spec_const(C, "int", "other_layout", "CONTIG_LAYOUT_INT")}
6262
${layout_declare_spec_const(C, "int", "in_broadcast_packed_dim", "0")}
6363
${layout_declare_spec_const(C, "int", "other_broadcast_packed_dim", "0")}
6464

65+
$if OPERATOR == "swiglu(X, Y)":
66+
float swiglu(float gate, float up) {
67+
return (gate * (1.0 / (1.0 + exp(-gate)))) * up;
68+
}
69+
6570
void main() {
6671
const uint out_bufi = linear_idx_from_gid();
6772
if (out_of_bounds(out_bufi, outp)) {

‎backends/vulkan/runtime/graph/ops/glsl/binary_op_buffer.yaml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ binary_op_buffer:
2222
OPERATOR: X - A * Y
2323
- NAME: binary_mul_buffer
2424
OPERATOR: X * Y
25+
- NAME: binary_swiglu_buffer
26+
OPERATOR: swiglu(X, Y)
27+
generate_variant_forall:
28+
DTYPE:
29+
- VALUE: half
30+
- VALUE: float
2531
- NAME: binary_div_buffer
2632
OPERATOR: X / Y
2733
- NAME: binary_pow_buffer

‎backends/vulkan/runtime/graph/ops/glsl/binary_op_texture.glsl‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,11 @@ ${layout_declare_spec_const(C, "int", "other_broadcast_packed_dim", "0")}
6262
$if MASK_PADDING:
6363
#define MASK_PADDING
6464

65+
$if OPERATOR == "swiglu(X, Y)":
66+
vec4 swiglu(vec4 gate, vec4 up) {
67+
return (gate * (1.0 / (1.0 + exp(-gate)))) * up;
68+
}
69+
6570
void main() {
6671
const ivec3 out_pos = ivec3(gl_GlobalInvocationID);
6772

‎backends/vulkan/runtime/graph/ops/glsl/binary_op_texture.yaml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ binary_op_texture:
2222
OPERATOR: X - A * Y
2323
- NAME: binary_mul_texture3d
2424
OPERATOR: X * Y
25+
- NAME: binary_swiglu_texture3d
26+
OPERATOR: swiglu(X, Y)
27+
generate_variant_forall:
28+
DTYPE:
29+
- VALUE: half
30+
- VALUE: float
2531
- NAME: binary_div_texture3d
2632
OPERATOR: X / Y
2733
MASK_PADDING: 1

‎backends/vulkan/runtime/graph/ops/impl/BinaryOp.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ DEFINE_BINARY_OP_WITH_ALPHA_FN(sub);
134134
DEFINE_BINARY_OP_WITH_ALPHA_FN(floor_divide);
135135

136136
DEFINE_BINARY_OP_FN(mul);
137+
DEFINE_BINARY_OP_FN(swiglu);
137138
DEFINE_BINARY_OP_FN(div);
138139
DEFINE_BINARY_OP_FN(pow);
139140
DEFINE_BINARY_OP_FN(minimum);
@@ -149,6 +150,7 @@ REGISTER_OPERATORS {
149150
VK_REGISTER_OP(aten.add.Tensor, add);
150151
VK_REGISTER_OP(aten.sub.Tensor, sub);
151152
VK_REGISTER_OP(aten.mul.Tensor, mul);
153+
VK_REGISTER_OP(et_vk.swiglu.default, swiglu);
152154
VK_REGISTER_OP(aten.div.Tensor, div);
153155
VK_REGISTER_OP(aten.div.Tensor_mode, floor_divide);
154156
VK_REGISTER_OP(aten.pow.Tensor_Tensor, pow);

0 commit comments

Comments
 (0)