Skip to content

[XNNPACK] Delegate GEMMs that take parts of one packed weight or bias - #25005

Open
john-rocky wants to merge 3 commits into
pytorch:mainfrom
john-rocky:xnnpack-split-param-gemms
Open

john-rocky wants to merge 3 commits into
pytorch:mainfrom
john-rocky:xnnpack-split-param-gemms

Conversation

@john-rocky

@john-rocky john-rocky commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follows #24352, which leaves a computation shared by several GEMMs on portable. Now GEMMs that take the parts of one split, such as the packed projections of nn.MultiheadAttention, are delegated together, and the split is folded inside their delegate.

get_static_param_deps now also accepts a weight or bias computation in which a multi-output op gives its other outputs to other GEMMs, as long as they are of the same kind as the GEMM being checked, such as linear, and take their part in the same argument position. The config partitioner already merges partitions that share a node other than a constant, so these GEMMs become one partition, and FoldComputedParamsPass folds the multi-output op into one constant per output. GEMMConfig.check_constraints accepts such a GEMM only together with the rest of its group. Every GEMM of the group must pass _check_gemm, which holds the config's checks on a single GEMM, and the merged partition of the group's GEMMs and their deps must have no node with too many dims and must pass validate_partition, the cycle check of fuse_as_graphmodule.

Lowered with XnnpackPartitioner() on macOS arm64, embedding dim 16, 2 heads, batch_first=True, query length 5, memory length 7, default weights, biases drawn with torch.nn.init.normal_, main → this PR:

GEMMs left on portable delegate calls .pte bytes max abs diff vs eager
cross-attention 2 → 0 7 → 6 19,776 → 18,112 3.6e-07 → 2.4e-07
different key and value 3 → 0 4 → 3 18,240 → 16,832 2.4e-07 → 2.4e-07
kdim=12, vdim=10 3 → 0 4 → 3 17,088 → 15,680 4.8e-07 → 4.8e-07
nn.TransformerDecoderLayer, dim_feedforward=32 2 → 0 11 → 13 42,688 → 42,304 4.8e-07 → 4.8e-07
self-attention 0 → 0 6 → 6 17,600 → 17,600 1.9e-06 → 1.9e-06

Timed with the executorch 1.5.1 runtime on one CPU thread of an Apple M4 Max, main → this PR, median time per call. E is the embedding dim.

E=16, query 5, memory 7 E=512, query 1, memory 1,500 E=512, query 64, memory 1,500
cross-attention 15.4 µs → 12.3 µs 623 ms → 2.34 ms 638 ms → 5.48 ms
different key and value 15.3 µs → 12 µs 513 ms → 1.91 ms 526 ms → 5 ms
kdim, vdim 14.8 µs → 12 µs 331 ms → 1.54 ms 344 ms → 4.7 ms
nn.TransformerDecoderLayer 26.6 µs → 23.8 µs 620 ms → 2.47 ms 629 ms → 6.12 ms
self-attention 12 µs → 12 µs 528 µs → 534 µs 821 µs → 824 µs

In the four cases this PR changes, a call is 1.1 to 1.3 times as fast at E=16 and 73 to 269 times as fast at E=512, where on main the key and value projections of the 1,500-row memory run on the portable addmm.

A script to time main and this PR yourself, and the tests that fail on both, are in this comment.

Suggested review order: get_static_param_deps, then GEMMConfig.check_constraints and _check_gemm, which ConvolutionConfig and AddmmConfig override instead of check_constraints, then the error in FoldComputedParamsPass.

Test plan

python -m pytest -v backends/xnnpack/test/passes/test_fold_computed_params.py

18 passed, 26 subtests passed. The new tests lower linears and addmms that take the parts of a packed weight or bias, made with split, with chunk, or with cat followed by chunk. They also lower nn.MultiheadAttention in cross-attention, in cross-attention with dynamic query and memory lengths, with different key and value tensors, with kdim and vdim, and in nn.TransformerDecoderLayer. They check that no GEMM or split is left outside the delegates and that the runtime matches eager. A packed linear bias, and a packed linear weight with its bias, are also covered under static and dynamic quantization. These 14 subtests fail on main. The other new tests check what must not be delegated: a part also used by another op, a GEMM whose output passes through an op left on portable into the GEMM that takes the other part, parts that together are larger than the param, a GEMM of the group whose bias is computed with more dims than XNNPACK supports, and a conv1d that shares a split weight with a conv1d rejected for its dynamic shape. Each of the last four fails when its check is removed. Two more tests guard the group check: one fails if a subclass of GEMMConfig defines check_constraints, since the other GEMMs of a group would skip the checks there, and one delegates a GEMM without the rest of its group and checks the error from FoldComputedParamsPass.

python -m pytest -q backends/xnnpack/test/passes backends/xnnpack/test/ops backends/xnnpack/test/serialization backends/xnnpack/test/quantizer backends/xnnpack/test/test_xnnpack_partitioner.py -o addopts="" --continue-on-collection-errors

Run on macOS arm64 without a source build. The Python sources and tests of this PR and of main each ran on top of the executorch 1.5.1 wheel, which supplies the native runtime and the pybindings:

  • this PR: 69 failed, 524 passed, 1 skipped, 1 error, 213 subtests passed
  • main: 69 failed, 518 passed, 1 skipped, 1 error, 195 subtests passed

In these runs, the same tests fail on main and with this PR.

This PR was authored with Claude Code.

cc @GregoryComer @digantdesai @cbilgin @JakeStevens @nil-is-all

get_static_param_deps now also accepts a weight or bias computation whose
multi-output op, such as the split of nn.MultiheadAttention's packed
in_proj_weight, gives its other outputs to GEMMs of the same op as the same
argument. GEMMConfig.check_constraints accepts such a GEMM only together with
those GEMMs, and only if their merged partition has no node with too many dims
and creates no cycle. FoldComputedParamsPass folds the op inside the delegate
without changes.
@pytorch-bot

pytorch-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25005

Note: Links to docs will display an error until the docs builds have been completed.

❌ 2 New Failures

As of commit a43cbad with merge base 799098d (image):

NEW FAILURES - The following jobs have failed:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 13, 2026
@john-rocky

Copy link
Copy Markdown
Contributor Author

@JakeStevens here is the draft for the packed nn.MultiheadAttention split; the approach is in get_static_param_deps and GEMMConfig.check_constraints.

@JakeStevens

Copy link
Copy Markdown
Contributor

Thanks for picking this up. Folding the split inside the delegate of the GEMMs that use it, and checking those GEMMs as a group, is the right approach, and the tests cover the ways it can go wrong. I'd like one restructure before this comes out of draft, plus two small safeguards.

  1. Restructure the group check. _check_gemms_sharing_deps recurses through check_constraints, guarded by gemms_in_group_check, only so that the other GEMMs of a group also pass the ConvolutionConfig and AddmmConfig overrides. If those overrides become a _check_gemm hook (they're only renamed), check_constraints can collect and check the group in one loop, then run the rank and cycle checks once. That removes the recursion, the mutable set on the config, and _get_gemms_sharing_deps. With it, your 16 tests still pass, removing any one of the three checks still fails its test, and the conv1d, conv2d, addmm, linear, partitioner and passes tests give the same results as this PR.

  2. Keep GEMM configs from overriding check_constraints. The cost of the restructure is that the other GEMMs of a group go only through _check_gemm. A future GEMM config that adds checks in a check_constraints override would skip them for those GEMMs, and lowering would fail again. mypy doesn't run on backends/xnnpack, so typing.final wouldn't be enforced. Instead add a test that fails if any GEMMConfig subclass defines check_constraints.

  3. Fail clearly in FoldComputedParamsPass. If a GEMM is ever delegated without the rest of its group, the split's list output becomes a delegate output, and the pass fails inside create_constant_placeholder with TypeError: cannot create weak reference to 'list' object.

…n up

GEMMConfig.check_constraints now collects the GEMMs that share a weight or
bias computation in one loop, checks each of them with _check_gemm, and runs
the rank and cycle checks on their merged partition once. ConvolutionConfig
and AddmmConfig override _check_gemm instead of check_constraints, with the
same checks, so the other GEMMs of a group get them too. This replaces the
recursion through check_constraints and the set of GEMMs under check that
the config kept. A test fails if a GEMMConfig subclass defines
check_constraints, since the other GEMMs of a group would skip checks added
there.

When a GEMM is delegated without the rest of its group, the multi-output op
that FoldComputedParamsPass folds is also used outside of the folded nodes.
The pass now raises a RuntimeError that names the op and says so, instead of
a TypeError from create_constant_placeholder.

The tests in test_fold_computed_params.py pass. Removing the group, rank or
cycle check fails its test, and the conv1d, conv2d, addmm, linear,
partitioner and passes tests give the same results as before this change.
@john-rocky

Copy link
Copy Markdown
Contributor Author

Thanks, all three are in 464c3cb.

  1. The check_constraints overrides of ConvolutionConfig and AddmmConfig are now _check_gemm overrides; only the name and the super() call in them changed. GEMMConfig.check_constraints collects the group in one loop, checks each GEMM with _check_gemm, and then runs the rank and cycle checks once. The recursion, gemms_in_group_check, _get_gemms_sharing_deps and _check_gemms_sharing_deps are gone.

  2. test_gemm_configs_do_not_override_check_constraints lists the GEMMConfig subclasses that define check_constraints and expects none. With a check_constraints override added to LinearConfig, it fails with ['LinearConfig'] != [].

  3. FoldComputedParamsPass now raises this instead of the TypeError:

    RuntimeError: Cannot fold aten_split_with_sizes_copy_default into a param, as it has more than one output and is used outside of the folded nodes. A GEMM that takes one of its outputs was delegated without the GEMMs that take the others.
    

    test_fp32_gemm_delegated_without_its_group_fails_clearly patches GEMMConfig.check_constraints to call only _check_gemm. So one conv1d of PackedWeightConv1ds is delegated, and the other, rejected for its dynamic shape, is not. Without the new RuntimeError, the test fails on the TypeError.

The three results you listed hold here, on macOS arm64 with each commit's Python sources on top of the executorch 1.5.1 wheel:

  • The 16 tests pass, and so do the 2 new ones.
  • Removing the group, rank or cycle check fails its test and no other in test_fold_computed_params.py.
  • The conv1d, conv2d, addmm, linear, partitioner and passes tests give the same result for every test as with the previous head, 203d0b3: besides the 2 new tests, 215 pass and 5 fail on both. Those 5, three int4 linear tests and two bf16 partitioner tests, fail on main too in this environment.

I updated the description to match the commit. Its list of tests that fail on main and with this PR now also includes tests in which only a subtest fails. The description now also has timings of main and of this PR, with a script to time them yourself.

Could you take another look, and let me know if it can come out of draft?

@john-rocky

Copy link
Copy Markdown
Contributor Author

To time it yourself, save the script below as time_mha.py and run:

python time_mha.py lower main   # with main's executorch
python time_mha.py lower pr     # with this PR's executorch
python time_mha.py time         # with the executorch 1.5.1 wheel
time_mha.py
"""Time nn.MultiheadAttention lowered with XnnpackPartitioner by main and by this PR, on one CPU thread.

    python time_mha.py lower main   # with main's executorch
    python time_mha.py lower pr     # with this PR's executorch
    python time_mha.py time         # loads both sides' programs and times them

The lower steps write ./mha_pte. The time step checks each program against eager (atol and rtol 1e-3), then
alternates main and this PR 10 times. Each turn runs a few warm-up calls and about 0.5 s of timed calls (5 to 200).
The table shows the median call of each side, main -> this PR.
"""

import gc
import math
import os
import statistics
import sys
import time

import torch

SIZES = {  # embedding dim, heads, kdim, vdim, dim_feedforward, query length, memory length
    "E=16, query 5, memory 7": (16, 2, 12, 10, 32, 5, 7),
    "E=512, query 1, memory 1,500": (512, 8, 384, 320, 2048, 1, 1500),
    "E=512, query 64, memory 1,500": (512, 8, 384, 320, 2048, 64, 1500),
}
ROWS = ("cross-attention", "different key and value", "kdim, vdim", "nn.TransformerDecoderLayer", "self-attention")


class Attention(torch.nn.Module):
    def __init__(self, row, E, H, kdim, vdim):
        super().__init__()
        self.row = row
        kw = {"kdim": kdim, "vdim": vdim} if row == "kdim, vdim" else {}
        self.mha = torch.nn.MultiheadAttention(E, H, batch_first=True, **kw)

    def forward(self, x, key, value=None):
        if self.row == "self-attention":
            return self.mha(x, x, x, need_weights=False)[0] + key.sum()
        if self.row == "different key and value":
            value = key * 2
        return self.mha(x, key, key if value is None else value, need_weights=False)[0]


class Decoder(torch.nn.Module):
    def __init__(self, E, H, ff):
        super().__init__()
        self.layer = torch.nn.TransformerDecoderLayer(E, H, ff, dropout=0.0, batch_first=True)

    def forward(self, x, memory):
        return self.layer(x, memory)


def build(row, size):
    E, H, kdim, vdim, ff, q, m = SIZES[size]
    torch.manual_seed(0)
    model = Decoder(E, H, ff) if row == "nn.TransformerDecoderLayer" else Attention(row, E, H, kdim, vdim)
    for name, param in model.named_parameters():
        if name.endswith("bias"):
            torch.nn.init.normal_(param)  # the biases start at zero
    x = torch.randn(1, q, E)
    if row == "kdim, vdim":
        return model.eval(), (x, torch.randn(1, m, kdim), torch.randn(1, m, vdim))
    return model.eval(), (x, torch.randn(1, m, E))


def pte(side, row, size):
    return os.path.join("mha_pte", f"{side}_{ROWS.index(row)}_{list(SIZES).index(size)}.pte")


def lower(side):
    from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
    from executorch.exir import to_edge_transform_and_lower

    os.makedirs("mha_pte", exist_ok=True)
    for row in ROWS:
        for size in SIZES:
            model, inputs = build(row, size)
            edge = to_edge_transform_and_lower(torch.export.export(model, inputs), partitioner=[XnnpackPartitioner()])
            with open(pte(side, row, size), "wb") as f:
                f.write(edge.to_executorch().buffer)


def seconds(program, inputs):
    t0 = time.perf_counter_ns()
    program.forward(inputs)
    return (time.perf_counter_ns() - t0) / 1e9


def fmt(s):
    ms = s * 1e3
    return f"{ms * 1e3:.3g} µs" if ms < 1 else f"{ms:.3g} ms" if ms < 10 else f"{ms:.0f} ms"


def time_both(rounds=10):
    from executorch.extension.pybindings import portable_lib

    missing = [pte(s, r, z) for s in ("main", "pr") for r in ROWS for z in SIZES if not os.path.exists(pte(s, r, z))]
    if missing:
        sys.exit(f"{len(missing)} programs missing, such as {missing[0]}: run the two lower steps first")
    portable_lib._unsafe_reset_threadpool(1)  # before any program loads
    print("| | " + " | ".join(SIZES) + " |\n" + "|---" * (len(SIZES) + 1) + "|", flush=True)
    for row in ROWS:
        cells = []
        for size in SIZES:
            model, inputs = build(row, size)
            with torch.no_grad():
                want = model(*inputs)
            blobs, programs, plan, calls = {}, {}, {}, {"main": [], "pr": []}
            for side in calls:
                with open(pte(side, row, size), "rb") as f:
                    blobs[side] = f.read()
                programs[side] = portable_lib._load_for_executorch_from_buffer(blobs[side])
                if not torch.allclose(programs[side].forward(inputs)[0], want, atol=1e-3, rtol=1e-3):
                    sys.exit(f"{side}, {row}, {size}: the program's output differs from eager")
                for _ in range(2):
                    programs[side].forward(inputs)
                guess = statistics.median(seconds(programs[side], inputs) for _ in range(3))
                n = min(200, max(5, math.ceil(0.5 / guess)))
                plan[side] = (max(1, min(math.ceil(n / 5), math.ceil(0.1 / guess))), n)  # warm-up, timed calls
            gc.collect()
            gc.disable()
            for _ in range(rounds):
                for side in calls:
                    warm, n = plan[side]
                    for _ in range(warm):
                        programs[side].forward(inputs)
                    calls[side] += [seconds(programs[side], inputs) for _ in range(n)]
            gc.enable()
            cells.append(f"{fmt(statistics.median(calls['main']))} → {fmt(statistics.median(calls['pr']))}")
        print(f"| {row} | " + " | ".join(cells) + " |", flush=True)


if __name__ == "__main__":
    if sys.argv[1:2] == ["lower"] and sys.argv[2:] in (["main"], ["pr"]):
        lower(sys.argv[2])
    elif sys.argv[1:] == ["time"]:
        time_both()
    else:
        sys.exit(__doc__)
Tests that fail on both
  • test_mean_dim.py: 32 tests
  • test_io_dim_order.py: 7 tests
  • test_upsample_nearest2d.py: 6 tests
  • test_linear.py: test_linear_qd8_f16_per_channel_int4, test_linear_qd8_f16_per_token_weight_per_channel_group_int4, test_linear_qd8_f32_per_channel_int4
  • test_gelu.py: test_fp32_gelu_approximation_2_tanh, test_fp32_gelu_approximation_3_tanh
  • test_xnnpack_partitioner.py: test_enable_bf16_leaves_ops_xnnpack_cannot_define_in_bf16, test_enable_bf16_runs_an_attention_block
  • test_bmm.py: test_bf16_bmm
  • test_softmax.py: test_bf16_softmax
  • test_xnnpack_quantizer.py: test_gru
  • test_prelu.py: not collected

@JakeStevens
JakeStevens marked this pull request as ready for review November 20, 2026 14:02
@JakeStevens

Copy link
Copy Markdown
Contributor

@claude review effort:max

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Claude finished @JakeStevens's task in 5m 58s —— View job


Nothing blocks this PR coming out of draft: I found only three minor issues, which are a redundant get_deps call per GEMM, a conservative argument-position match, and one low-confidence question about the cycle check.

Detailed review

PR Review: #25005

Summary

GEMMs that take parts of one split or chunked packed weight or bias, such as the nn.MultiheadAttention in-projections, are now accepted as a group, merged into one partition and folded by FoldComputedParamsPass. Three reviewers looked at the change independently, and I re-read the code behind every finding. I found no blockers, just the three minor issues below. Nothing was run, since running tests needed approval here.

One concern came up in review and turned out to be wrong: XnnpackPartitioner(per_op_mode=True) is not broken. generate_per_op_partitions builds on get_matched_nodes_from_configs, which already merges the group's partitions through the DSJ before the overlap check runs (config_partitioner.py:228-234).

Code Quality

  • backends/xnnpack/partition/config/gemm_configs.py:116,128: the position match compares whole args lists, so it also compares their lengths. In linear(x, w0, b) and linear(y, w1) with w0, w1 = W.split(...), both GEMMs take the part as the weight. But [F, T, F] != [F, T], so both are rejected and run on portable. This is safe, just more conservative than the docstring ("as the same argument of GEMMs like user"). Comparing only the index of the part (user.args.index(node) against the index in gemm.args) would accept this case. Fix this →
  • gemm_configs.py:199-213 (low confidence): the cycle check only covers the GEMM group and its deps, not the final merged partition. get_matched_nodes_from_configs can also union the group with other config partitions that share a non-constant node with it. Two possible cases are a choose_qparams shared by dynamically quantized linears, or a dep that another config also claims. validate_partition never sees those nodes. If the later grouping step then has to break that larger set apart, the split ends up in a delegate without the rest of its group. Lowering would then fail with the new RuntimeError, where before this PR those GEMMs fell back to portable. Nobody built a concrete model that triggers this. Could you confirm whether such a merge can happen, for example by lowering a self-attention block with [XnnpackDynamicallyQuantizedPartitioner(), XnnpackPartitioner()]?

Performance

  • gemm_configs.py:184: check_constraints calls self.get_deps(gemm, ep) right after _check_gemm, which already called it (:225). This happens for every GEMM, including the usual case with no group. With get_partition (:232), that makes three get_deps calls per GEMM where there used to be two. For AddmmConfig and MMConfig, each call runs get_source_partitions over the whole graph (:667). Each call also adds to COMPUTED_PARAM_TAG and logs why again. Graphs with many addmm or mm nodes, such as a decomposed LLM, pay roughly 1.5x the old whole-graph scans, twice over (once in the do-not-decompose filter, once in partitioning). Having _check_gemm return the deps, or reusing them, would remove the extra call. Fix this →

Recommendation

Approve

None of these block it. The redundant get_deps call is cheap to fix. Please answer the cycle-check question before merging.

@executorch-triage executorch-triage Bot added the community: contribution PRs coming from community (excluding hardware partners) label Nov 20, 2026
@nil-is-all nil-is-all added module: xnnpack Issues related to xnnpack delegation and the code under backends/xnnpack/ release notes: xnnpack Changes to the XNNPack backend delegate labels Nov 23, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. community: contribution PRs coming from community (excluding hardware partners) module: xnnpack Issues related to xnnpack delegation and the code under backends/xnnpack/ release notes: xnnpack Changes to the XNNPack backend delegate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants