Skip to content

A depthwise convolution is a stencil on the vector unit, not a matmul - #333

Merged
student-Jungmin merged 11 commits into
pytorchsim-triton-backendfrom
depthwise-conv
Oct 10, 2026
Merged

student-Jungmin merged 11 commits into
pytorchsim-triton-backendfrom
depthwise-conv

Conversation

@student-Jungmin

Copy link
Copy Markdown
Collaborator

Branches from ci-ptb-token (#332) so the gate runs on the compiler's image; the diff shrinks to one commit when #332 lands.

Why

test_mobilenet took 59 minutes on the 256x256 config and died at the runners' 70-minute limit on 32x32 and 8x8 (#332's runs). Of those 59 minutes, 291 s were the image pull, 38 s the 44 kernel compiles, and 3154 s Spike -- almost all of it five depthwise 3x3 convolutions at 180-560 s each (the same kernel launched twice is simulated twice).

A depthwise conv (GROUPS = C, one channel a group) went through Inductor's conv2d Triton template with the npu tile table: BLOCK_M=64, BLOCK_N=16, BLOCK_K=16, one program per 64 outputs per group, one 64x16x16 tl.dot per tap. The accelerator model's systolic push (vcix-accelerator/examples/tpu/functional.hpp, systolic_input_push) computes lanes x K products for every pushed row whatever N is valid, so the 32-channel 112x112 layer (3.6M useful multiply-adds) emulated 14.8G of them: 142 s locally, 482 s in CI. The 144-channel 56x56 layer: 16.6G, 160 s / 562 s.

For reference, origin/develop decomposes exactly this case (mlir_decomposition.py, _group_conv_cin1_cout1: pad, then per-tap gather x weight, summed) and runs all of MobileNetV2 functional in 175 s on 128x128 with no launch over 7.3 s.

What

aten.convolution's npu decomposition (inductor_patches._decompose_convolution_for_npu, where the Conv1d -> Conv2d registration already lived) takes a depthwise 2-D conv as a stencil: the input padded with constant_pad_nd, each tap a strided slice of it times that tap's weight, the taps summed, the bias last. Inductor fuses the taps into one pointwise kernel together with the batch norm and hardtanh after it, so a depthwise layer is one vector kernel over its outputs and the systolic array is left to the pointwise convolutions. Transposed convs, output_padding and non-npu inputs still decline; everything else keeps the template.

Verified (256x256 functional config, torch 2.14.0, compiler a901c55)

before after
test_mobilenet wall 997 s 181 s
Spike total / launches 933 s / 74 95 s / 67
slowest launch 160 s (depthwise 144 groups) 10 s (fused BN + hardtanh + stencil)

test_mobilenet passes; test_group_conv (depthwise, 240 groups, stride 2), test_conv2d (14 checks), test_cnn, test_pool pass; depthwise probes against the CPU with kernel 5 / stride 2 / dilation 2 / bias / batch 2 agree to 3e-6. test_conv_view_input fails before and after (tts.load ... elem_mask is an i1, compiler side, not in the allowlist).

The allowlist notes name a related defect in the old path: a grouped conv with a bias got bias[c % (OUT_C // GROUPS)]. The stencil adds the bias per channel itself; a depthwise conv with a bias is one of the probes above.

…s the test stack

PyTorchSim-Triton-Backend publishes an image per commit (images.yml:
ghcr.io/psal-postech/pytorchsim-triton-backend:<sha>), built on the
vcix-accelerator environment image -- Ubuntu 22.04 with python3.11, the
RISC-V toolchain, pk, Spike, gem5 -- with LLVM, Triton and the torchsim
backend, the model, the compiler, its dialect and extension, doctor and
smoke passed. This repository's CI ignored it: Dockerfile.ptb cloned the
compiler at the pin and ran toolchain.sh llvm triton vcixenv vcix dialect
ext, building all of that again from source, on top of a base image that
itself installed python3.11 and torch on a bare Ubuntu. A moved pin cost
an hour of toolchain build before the first test could run, and the clone
needed a token for the private repository, which is what stopped #331's
first gated run.

Dockerfile.base is now FROM the compiler's image at the pin, adding only
`python`, boost, PyTorch 2.14 / torchvision 0.29 (CPU) and the packages
the tests import, and the environment the compiler route reads
(TORCHSIM_COMPILE_DIR, the Triton source tree on PYTHONPATH, the
extension, gem5). Its tag hashes the compiler pin as well, so a moved pin
rebuilds it; nothing of the compiler is built here. Dockerfile.ptb and
ptb_base_pin.sh go, as do the "Check PTB access" job and every use of a
token: the compiler's package grants this repository read access, and the
default Actions token pulls it. The app image removes the compiler's
PyTorchSim checkout before copying the tree under test to the same path,
so the compiler's trace producer reads this tree's TOGSim headers. The
base job moves to the big self-hosted runner, where a ~10 GB image fits.
pytorchsim_triton_backend.yml gates PRs into pytorchsim-triton-backend as
well, and watches Dockerfile.base in place of Dockerfile.ptb.
A missing image and a denied one print the same one-line error; docker's
own message (manifest unknown vs denied) tells them apart, so it is shown.
The compiler's image is pushed by buildx in OCI format, and the big
runner's docker CLI answers docker manifest inspect with "parsing manifest
blob" on it -- which read as "not in the registry" although the image was
there and readable. The propagation wait already uses imagetools inspect;
both existence checks do now, the base image's included, since
build-push-action pushes OCI too and the check would have rebuilt a base
that existed.
torch.hub.load asks on stdin whether ultralytics/yolov5 may be downloaded
the first time a machine sees it; a CI container has no stdin and the
test died with EOFError before compiling anything (the box this was
written on had already answered once). trust_repo=True is the answer.
… tail on failure

It was sent to /dev/null, so a failing run_cycle.sh left "exit code 1"
and nothing else in the job log.
The compiler's failure report names the reason as the failing tool's last
output line. For an MLIR diagnostic that line is the caret under the source,
so Inductor reported "command failed with exit code 1: ^" and nothing else
(the cycle-validation job's gemm 256 in CI). The stderr block the report
prints below is where the diagnostic is; its lines that look like one
(error:, *Error, Assertion, a refusal) now follow the reason line, at most
two of them.
PyTorchSim-Triton-Backend compiles with Triton 3.8 unmodified, whose frontend
refuses any block tensor over TRITON_MAX_TENSOR_NUMEL (1 << 20 elements)
before MLIR exists. The mm tile candidates were bounded by the scratchpad
alone, and on the 256x256 tpuv6e machine half the scratchpad holds blocks of
4M and 8M elements: test_gpt2's addmm (BLOCK_N=4096 x BLOCK_K=1024) and
test_mistral's mm (8388608 elements) failed in CI with "numel exceeds triton
maximum tensor numel". They passed on the development machine only because
its Triton checkout carries a local edit raising the limit to 1 << 26
(2026-10-08, for the v6e rig).

The limit is read from the Triton the route compiles with (triton._utils),
so a toolchain that raised it is followed. Three places honour it: the mm
tile candidates drop any tile whose A, B or C block exceeds it;
fixed_config_for caps a reduction block so that the product of all pinned
blocks fits (a bf16 reduction of 8192 on 256 lanes is 2M elements); and the
compile retry loop treats the refusal as a tile too big, so a kernel that
still exceeds it tries the next smaller tile instead of failing. Persistent
reductions are unaffected: the persistence check already admits only blocks
of 512 or less.

Verified under the stock limit (a Triton overlay with 1 << 20 in a toolchain
prefix overlay): test_gpt2 and test_mistral fail without this commit the way
CI did and pass with it (gpt2 55 s, mistral 93 s); test_gpt2's addmm now
picks BLOCK_N=4096 x BLOCK_K=256. With the local 1 << 26 the candidates are
unchanged.
Every push leaves another torchsim-test:<sha> image (and every moved pin
another torchsim_base tag) on each self-hosted runner that pulled or built
it, and nothing removed them. In run 37981364816 a small runner reached 87 MB
of free disk and test_transformer failed before the test started: the pull
died with exit 125 ("writing blob: adding layer ... processing tar file").
The run before it lost test_transformer on the same config the same way.

Each test job, the cycle-validation job and the three image-build jobs now
remove this repository's images other than the one they are about to use
(the test image for a test job, the base image for a build), prune dangling
layers and print the free space. Images of other repositories on the runner
are left alone; an image in use by another container is refused by rmi and
kept.
…ost path returns every out tensor

test_yolov5 failed on every config in the gate with "Object of type 'Tensor'
is not an instance of 'sequence'" from an eager max_pool2d: YOLOv5's SPPF
wraps its pooling in warnings.catch_warnings(), dynamo breaks the graph
there, and the pooling runs eagerly on a tensor the compiled graph produced.
Dynamo's frame hook then met the Python kernel registered for
aten::max_pool2d_with_indices.out and, since it is not a torch frame, traced
it as user code (TORCH_LOGS=trace_source shows the wrapper's lines as frame
1/0). Inside a traced frame torch.compiler.is_compiling() is a constant True,
so the compile-in-flight guard chose the host path and dynamo compiled THAT:
copies to the CPU, the op on the CPU, copies back. A CPU fallback for every
eager op reached from a compiled model, and for this two-output op a single
Tensor returned where the dispatcher expects both outputs, which is the
error. The same guard was green on the development machine because the
sweep that validated it predates the guard's commit.

The kernel is now torch.compiler.disable'd: dynamo leaves it alone, it runs
eagerly, the guard evaluates the real flag (True only inside a compile
session, which is the constant-folding case it was written for), and the
op compiles through dummy_graph as before. The host path writes and returns
every out tensor the schema names (out and indices for max_pool2d, max and
max_values for max.dim) instead of the first.

Verified with the frontend's torch 2.14.0 and the compiler at a901c55:
test_yolov5 on the 256x256 and 32x32 configs, test_swinv2 (the constant
folded during compile that motivated the guard), test_mlp, test_eager,
test_eager_to_compile_recursion and test_expert_mask pass; a module with the
SPPF pattern compiles its pooling as an npu kernel.
…e loses every unused image

Removing this repository's older images was not enough: in run 37994502339
node n01 still had 14 GB free afterwards (210 of 223 GB used by images of
other repositories and leftovers of pulls that had already failed for lack
of space), test_convnextv2's pull died at 3 MB free, and test_diffusion on
the same node ended after 42 minutes with no log at all.

When fewer than 40 GB are free after the repository's own cleanup, the job
now also prunes every stopped container and every unused image on the
runner, whatever repository they belong to; an image in use by a running
container is kept. The step prints the free space and the largest images
left so the next log says what occupies a node.
…t a matmul

MobileNet's test took 59 minutes in CI on the 256x256 config and died at the
runner's 70-minute limit on 32x32 and 8x8; 90 percent of it was Spike, and
nearly all of that was five depthwise 3x3 convolutions (GROUPS = C, one
channel a group). They went through Inductor's conv2d template with the npu
tile table (BLOCK_M=64, BLOCK_N=16, BLOCK_K=16, one program per 64 outputs
per group), one 64x16x16 dot per tap. The accelerator model's systolic push
(vcix-accelerator examples/tpu/functional.hpp, systolic_input_push) computes
lanes x K products for every pushed row whatever N is valid, so a layer with
3.6M useful multiply-adds emulated 14.8G of them: 142 s locally and 482 s in
CI for the 32-channel 112x112 layer, 160 s / 562 s for the 144-channel 56x56
one. origin/develop decomposed exactly this case (mlir_decomposition.py,
_group_conv_cin1_cout1) and runs all of MobileNetV2 in 175 s.

aten.convolution's npu decomposition now takes a depthwise 2-D conv as a
stencil: the input padded with constant_pad_nd, each tap a strided slice of
it times that tap's weight, the taps summed, the bias last. Inductor fuses
the taps into one pointwise kernel together with the batch norm and hardtanh
that follow, so a depthwise layer is one vector kernel over its outputs and
the systolic array is left to the pointwise convolutions. The Conv1d ->
Conv2d decomposition that lived here keeps its place; transposed convs,
output_padding and non-npu inputs still decline.

Verified on the 256x256 functional config: test_group_conv (depthwise, 240
groups, stride 2) and test_conv2d (14 checks) pass; test_mobilenet passes in
181 s instead of 997 s, its Spike time 95 s over 67 launches instead of 933 s
over 74, the slowest launch 10 s instead of 160 s.
@student-Jungmin
student-Jungmin merged commit fd956b9 into pytorchsim-triton-backend Oct 10, 2026
4 checks passed
@student-Jungmin
student-Jungmin deleted the depthwise-conv branch October 12, 2026 04:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant