Repository navigation
Support torch.empty_like when lowering to Edge, and speed up GroupBasedPartitioner - #24218
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/24218
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (1 Unrelated Failure)As of commit 45a94d4 with merge base d5e8362 ( BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@claude /pr-review |
|
Claude finished @shoumikhin's task in 30m 57s —— View job This PR lowers default-format PR Review: #24218 (click to expand)SummaryThe PR keeps default-format Code Quality
Testing
Backward Compatibility
Performance
RecommendationRequest Changes Two problems in
The other findings can be follow-ups. |
What changes. empty_like with the default format is kept through decomposition. A new ReplaceEmptyLikePass turns it into empty.memory_format after views became copies and no-op views were removed, with the input's layout at that point. That becomes _empty_dim_order, which has a kernel." X = strided_tensor after export after pass why can we not just decompose to |
|
@JacobSzwejbka good question. Once it is decomposed, The ops that take I tried three small models, all with a contiguous
With this change, all three match eager. If I make
This PR has the same limit one step later: |
The Python schemas of dim_order_ops._empty_dim_order and its out variant took int[] size. So a size that comes from a dynamic dim, as in torch.empty(x.shape[0], 3), was fixed to its value at export, and so was that dim in the whole program. Memory planning then sized the program for the export size, and running it at another size failed. A size that comes from tensor data, as in torch.empty(n.item(), 3), failed to lower at all. Take SymInt[] size instead, like aten.empty.memory_format, which this op replaces. The kernels already resize their output to the given size, and their doc comments already say SymInt[]. The kernel codegen treats SymInt like int, so the generated portable code is the same and the ATen mode kernel signature does not change. Tests run a buffer sized from a dynamic dim, and one sized from tensor data, each at two sizes.
reinplace_pass can mark a node to reuse the memory of its input, for example a _clone_dim_order listed in reinplace_extra_ops. When LegalizePortableDimOrderPass inserts a _to_dim_order_copy after such a node, it copies the node's metadata, and with it that mark. The memory planner then puts the copy into the memory it reads from, so the values come out wrong without any error. For example, avg_pool2d of a channels last tensor that a reinplaced clone produced gives wrong values. Drop the memory sharing marks from the metadata of an inserted copy. The test runs that program with the clone reinplaced and compares with eager mode.
The portable copy.out kernel does not check the memory layout (dim
order) of the source. When the sizes match, it reads the source in the
same memory order as the destination. When the source must be broadcast,
it walks the destination as if it were contiguous. So these copies give
wrong values without any error:
buffer = torch.empty(2, 3, 4, 6, memory_format=torch.channels_last)
buffer.copy_(x) # x is a contiguous (2, 3, 4, 6) tensor
buffer.copy_(y) # y is (3, 4, 6), broadcast to every batch
The first also happens when this pass makes the output of avg_pool2d on
a channels last input contiguous, and that output is then copied into a
channels last buffer.
The in-place copy_ kernel writes a mutated buffer or input back, and
runs a copy that reinplace_pass made in place. It checks that both
tensors have the same dim order, so a channels last buffer updated from
a contiguous tensor fails at runtime. That includes shapes with a dim of
size 1, such as (N, C, 1, 1), where the two dim orders describe the same
memory. When the dim orders match but it broadcasts, it also writes the
buffer as if it were contiguous.
LegalizePortableDimOrderPass already inserts dim order copies in front
of portable ops that need a contiguous input. Now it also handles a copy
that is left to the portable kernels. A copy that the kernel already
gets right is left alone: the source is a single value, or it has the
memory order of the destination apart from leading dims of size 1, or it
is broadcast into a destination that is contiguous in memory. For any
other copy into a channels last destination, a source that may have
another shape is first expanded to the shape of the destination. Then,
if the source does not have the dim order of the destination, it is
copied into it.
Sizes count as equal only when they are written the same way, and a
broadcast counts only when it shows in sizes known when lowering.
Tracing can assume a dynamic size is not 1, but at runtime it can be.
Only contiguous and 4-D channels last destinations are handled, because
exir cannot convert a tensor to any other dim order. A copy into a 5-D
channels last tensor is left as it was, and still gives wrong values
when the source has another layout.
Tests compare with eager mode for copies between the two layouts, with
another dtype, from avg_pool2d, with broadcasting, with dynamic and
data-dependent sizes, with reinplaced ops, and through buffer
write-backs. They also check that nothing is inserted for copies the
kernel already gets right.
torch.empty_like(x) is a common way to allocate a scratch buffer, for example in rotary position embeddings. With the default preserve_format it cannot be lowered today. The core ATen decomposition table rewrites it into aten.empty_permuted, which is not in the core ATen opset, so to_edge rejects the program. With the IR check turned off, the program lowers but fails to load, because there is no empty_permuted kernel. Decomposing it right away does not work. Its layout would come from the eager strides of the input, and in the Edge program the input can have another layout: a view becomes a contiguous copy. For example, x.permute(0, 3, 1, 2) of a contiguous tensor has channels last strides in eager, but becomes a contiguous copy. The buffer would then have another layout than its input. The portable add kernel refuses inputs with different layouts, and slice_copy fails on a channels last input because its output is contiguous. So using the buffer together with its input, or filling it through slices as rotary embeddings do, fails at runtime. So keep preserve_format aten.empty_like through decomposition, and let a new ReplaceEmptyLikePass turn it into aten.empty.memory_format in _generate_edge_program, after views became copies and no-ops were removed. It uses the input's layout at that point, by the same rule that TensorSpec uses. The dim order pass then makes it _empty_dim_order, which already has a kernel. The replacement takes only the input's sizes, so with static shapes it has no inputs and partitioners can still merge the ops around it. A layout other than contiguous or 4-D channels last, such as a transposed 2-D input, becomes aten.empty_permuted, as PyTorch's decomposition does. An empty_like with an explicit memory_format does not depend on its input's layout, so it is still decomposed as before. Where to_edge_transform_and_lower skips decomposition, the same pass lowers it with that format. So an empty_like alone does not make it decompose the whole program again for each partitioner, unless the compile config lists it in preserve_ops. The pass only runs when the program has an empty_like that is not listed in preserve_ops. So if a partitioner asks to preserve empty_like, every default-format empty_like is kept, including those its node filter rejects, and those fail to load for lack of a kernel. A program already decomposed with PyTorch's table has aten.empty_permuted instead. Decompose it only when its layout is the identity, which is the same in eager and in Edge. Other layouts keep failing the core ATen check, as they do today, unless a partitioner keeps the op. LegalizePortableDimOrderPass can still change a layout later, in to_executorch. It runs avg_pool2d and a few other ops on a contiguous copy of a channels last input, so their output becomes contiguous, and the buffer keeps its Edge layout. A copy into the buffer is converted to match, but an op that takes both the buffer and that output, such as add, fails at runtime. The same program with an explicit channels last buffer fails the same way.
Lowering a large model with XnnpackPartitioner spent most of its time, and most of its memory while partitioning, inside GroupBasedPartitioner. For every node it kept a set of all nodes downstream and upstream of it, which grows with the square of the graph size. It then tried to merge every pair of partitions. Each try scanned those sets, and each try that passed walked the graph again with validate_partition. Store the same dependency information as bitmasks over node positions, and keep three masks per partition: its nodes, everything downstream of it, and everything upstream of it. Fused on its own, a merged partition has a cycle exactly when a node outside it is downstream of it and also upstream of it. With masks that is a few integer operations, and the masks of a merged partition are the bitwise OR of the two. This is the same question the old code asked, so for the same graph the partitions do not change. As before, a cycle through a third partition is not checked. The masks are built at the start of the merge step, from the graph as it is then, instead of in __init__. So they match the graph being merged, and the extra validate_partition walk is no longer needed. With fewer than two partitions there is nothing to merge, so no masks are built. Only nodes that a partition reaches, or that reach a partition, get masks, because only they can be on a path between two partitions. A mask costs one bit per position up to its last node, so this saves memory on a wide graph where most nodes neither reach nor are reached by a partition. Wide parts below a partition still cost one mask per node. New tests check that a group still merges with a supported node after it, that proposing again after the graph changed checks the changed graph, and that no partition has a cycle on seeded random graphs with random node groups that have no cycle on their own. A memory test checks that this class needs less than 8 MB on top of what its parent class allocates, on a chain of 1000 nodes split by unsupported ones (the old sets alone took about 40 MB there) and on 10000 independent nodes of which two are supported. Measured on CPU, with the same partitions as before: on SmolVLA (22k nodes at the partitioner) partitioning went from 123 min to 31 s, and on pi0.5 (21k nodes) from 78 min to 20 s. Peak memory while partitioning SmolVLA went from about 30 GB to about 12 GB. PyTorch's CapabilityBasedPartitioner.__init__ still builds its own set- based downstream map, which this class never reads. That cost is left for a change in PyTorch.
While it partitions, GroupBasedPartitioner fills four structures: partition_map, nodes_order, partitions_order and partition_users. Nothing reads any of them. partition_map is the costly one. For each partition it keeps every partition downstream of it, which grows with the square of the graph size on a long chain of supported nodes. On a chain of 1000 such nodes, proposing partitions peaked at about 22 MB. After this change it peaks at about 1 MB. Remove all four. The partitions do not change. The memory test gets a chain where every node is supported. It fails before this change.
057a0c8 to
45a94d4
Compare
|
Thanks for the review above (#24218 (comment)). Every point is addressed in the latest push:
The push also adds related fixes as their own commits: a portable copy into a tensor of another layout now gets its source converted first, the dim order copies that |
|
@JacobSzwejbka a follow-up: I pushed an update with one change that affects my answer above. A new commit converts the source of a portable copy to the layout of its destination, because |
|
@pytorchbot cherry-pick --onto release/1.6 -c critical |
Cherry picking #24218The cherry pick PR is at #24247 and it is recommended to link a critical cherry pick PR with an issue. Details for Dev Infra teamRaised by workflow job |
Fixes found while lowering the SmolVLA robot policy to ExecuTorch. Commits 5 and 6 change only the partitioner and do not need commits 1 to 4.
1. Accept symbolic sizes in
_empty_dim_order. The op's schema tookint[] size. Sotorch.empty(x.shape[0], 3)fixed that dim to its export size, and the program failed at any other size.torch.empty(n.item(), 3)failed to lower at all. It now takesSymInt[] size.2. Give inserted dim order copies their own memory. A copy that
LegalizePortableDimOrderPassinserted after a clone listed inreinplace_extra_opsreused the memory it read from, so values came out wrong.3. Convert the source of a portable copy to the layout of its destination. On main, both copies below give wrong values without an error. The portable
copy.outkernel ignores the layout of the source, and treats the destination as contiguous when it broadcasts:The in-place
copy_used for buffer write-backs fails at runtime when the layouts differ. The pass now converts the source to the layout of the destination, and leaves alone the copies the kernel gets right. Only contiguous and 4-D channels last destinations are handled, because exir can convert a tensor only to these two layouts.4. Support
torch.empty_likewhen lowering to Edge. Core ATen decomposition turns it intoaten.empty_permuted, which is not core ATen, soto_edgefails.It cannot be decomposed right away, because in Edge its input can have another layout than in eager:
x.permute(0, 3, 1, 2)of a contiguous tensor is channels last in eager, but a contiguous copy in Edge. So a newReplaceEmptyLikePasslowers it after views have become copies.Limits:
to_edge.xis the output ofavg_pool2don a channels last tensor,to_executorchlater makesxcontiguous, buty = torch.empty_like(x)stays channels last, soy + xfails at runtime.empty_like, every default-formatempty_likeis kept, even those its filter rejects, and those fail to load for lack of a kernel.5. Make
GroupBasedPartitionercycle checks fast on large graphs. It now uses bitmasks instead of per-node sets of all upstream and downstream nodes. WithXnnpackPartitioneron SmolVLA, partitioning went from 123 min to 31 s, and its peak memory from about 30 GB to about 12 GB.6. Remove four structures that
GroupBasedPartitionerfills but never reads.For the same graph, neither partitioner change moves a node to another partition (checked on thousands of random graphs).
What was tested
On Linux x86_64 CPU: 12 of the 18 new tests fail on main, and the other 6 check existing behavior. The exir tests, including exir/backend, and the XNNPACK tests have no new failures.