Repository navigation
[XNNPACK] Delegate GEMMs that take parts of one packed weight or bias - #25005
john-rocky wants to merge 3 commits into
Conversation
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.
🔗 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 FailuresAs of commit a43cbad with merge base 799098d ( NEW FAILURES - The following jobs have failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@JakeStevens here is the draft for the packed |
|
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.
|
…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.
|
Thanks, all three are in 464c3cb.
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:
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? |
|
To time it yourself, save the script below as 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
|
|
@claude review effort:max |
|
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 Detailed reviewPR Review: #25005SummaryGEMMs that take parts of one split or chunked packed weight or bias, such as the One concern came up in review and turned out to be wrong: Code Quality
Performance
RecommendationApprove None of these block it. The redundant |
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_depsnow 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 aslinear, 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, andFoldComputedParamsPassfolds the multi-output op into one constant per output.GEMMConfig.check_constraintsaccepts 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 passvalidate_partition, the cycle check offuse_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 withtorch.nn.init.normal_, main → this PR:.ptebyteskdim=12, vdim=10nn.TransformerDecoderLayer,dim_feedforward=32Timed 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.
kdim,vdimnn.TransformerDecoderLayerIn 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, thenGEMMConfig.check_constraintsand_check_gemm, whichConvolutionConfigandAddmmConfigoverride instead ofcheck_constraints, then the error inFoldComputedParamsPass.Test plan
python -m pytest -v backends/xnnpack/test/passes/test_fold_computed_params.py18 passed, 26 subtests passed. The new tests lower linears and addmms that take the parts of a packed weight or bias, made with
split, withchunk, or withcatfollowed bychunk. They also lowernn.MultiheadAttentionin cross-attention, in cross-attention with dynamic query and memory lengths, with different key and value tensors, withkdimandvdim, and innn.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 ofGEMMConfigdefinescheck_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 fromFoldComputedParamsPass.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-errorsRun 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:
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