Skip to content

Keep ops above 6 dims out of XNNPACK and fix quantized ops it leaves out - #24380

Merged
shoumikhin merged 23 commits into
pytorch:mainfrom
shoumikhin:xnnpack-high-rank-permute
Nov 2, 2026
Merged

shoumikhin merged 23 commits into
pytorch:mainfrom
shoumikhin:xnnpack-high-rank-permute

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

What is wrong today

XNNPACK supports tensors with at most 6 dimensions, but the XNNPACK partitioner, which decides which ops run on XNNPACK, does not check this. A permute or another op on a 7-D or 8-D tensor then lowers fine but fails to load:

Failed to define tensor 0 with code: xnn_status_unsupported_parameter

Some vision models hit this in a "patchify" step that cuts an image into patches:

y = x.reshape(2, 6, 8, 2, 16, 8, 2, 16).permute(0, 2, 5, 3, 6, 1, 4, 7)
y = y.reshape(2, 64, -1) * 2

With the 3-D convolution kernel from #24385, a statically quantized Conv3d is worse: it fails to load or, without a fused ReLU, returns one wrong value repeated everywhere, with no error. XNNPACK has no 3-D convolution, so the partitioner leaves the conv out, but only after marking the quantize and dequantize nodes around it as folded into it. Those nodes then land in delegates that skip them, so nothing writes the outputs. A statically quantized Conv2d or Linear whose output is not quantized hits the same bug, even without #24385.

What this change does

The partitioner now leaves out any op with an input or output above 6 dimensions, and it checks every node that a partition takes. A float linear on such an input still keeps its 2-D matrix multiply on XNNPACK.

Quantize and dequantize nodes are now marked as folded only once the op they belong to is really partitioned, so a rejected op keeps them as separate ops.

force_non_static_weights_for_f32_linear no longer changes how a quantized linear is partitioned. With it, a quantized linear decomposed into a matrix multiply (for example with to_backend) used to lose its quantize and dequantize nodes: a static one failed to lower or load, and a dynamic one ran as a float matrix multiply. Now it is partitioned as without the flag.

The XNNPACK quantizer now leaves 3-D convolutions in float. The model file gets larger, but there are no extra quantize and dequantize steps and no quantization error. They run on the CPU kernels, which support 3-D convolution once #24385 lands. Without it, such a model fails with "Expect input tensor to be 3-D or 4-D".

Still not covered: a linear on such an input, quantized with torchao's affine ops. Those ops have no portable kernels, so the model now fails in to_executorch() instead of at load. And a linear on such an input quantized with the XNNPACK quantizer runs outside XNNPACK, because its quantized input has too many dims.

Testing

  • test_permute.py checks which ops are delegated for 6-D and 7-D permutes, and for a linear on an 8-D input: float (also with a ReLU), static and dynamic quantization, each in both partitioner modes.
  • New tests cover a statically quantized Conv2d and Linear with a float output, a statically and a dynamically quantized linear lowered through to_backend with force_non_static_weights_for_f32_linear, and 3-D convolutions that the quantizer leaves unquantized.
  • The per-channel transposed conv test now also runs the convs that XNNPACK rejects. Before this change they returned all zeros.
  • Each new test fails without the part of the change it covers.
  • On macOS arm64, the patchify example and other 7-D and 8-D cases load and match eager PyTorch. A Conv3d model quantized with the XNNPACK quantizer matches eager PyTorch with Support 3-D convolution in the portable convolution kernel #24385, and fails without it.

XNNPACK supports tensors with at most 6 dimensions. The XNNPACK
partitioner did not check this, so it could delegate an op whose input
or output has more dimensions. Lowering then succeeds, but loading the
program fails with:

    Failed to define tensor 0 with code: xnn_status_unsupported_parameter

Some vision models hit this in a "patchify" step, which reshapes an
image into 8 dimensions, permutes it, and reshapes it into a sequence
of patches:

    y = x.reshape(2, 6, 8, 2, 16, 8, 2, 16).permute(0, 2, 5, 3, 6, 1, 4, 7)
    y = y.reshape(2, 64, -1) * 2

This change checks the number of dimensions in the XNNPACK partitioner:

- The common constraint check that op configs run. An op with an input
  or output above XNN_MAX_TENSOR_DIMS is not delegated, and an op such
  as linear is not kept whole for XNNPACK, so it gets decomposed.
- The source partition check for a decomposed linear. Its matrix
  multiply pulls the reshapes around it into its partition, even when
  their own constraint check rejects them. If any of them touches a
  tensor above the limit, the matrix multiply is not delegated either.
  The check runs before the linear's quantize and dequantize nodes are
  marked to be folded into the matrix multiply, so a rejected linear
  leaves them as separate ops.

In the example above, the reshapes and the permute then run outside
XNNPACK, and the multiply is still delegated.

Still not covered: a linear on such an input, quantized with torchao's
affine quantize and dequantize ops. Those ops are kept whole for
XNNPACK and have no portable kernels, so such a model now fails when it
is converted to an ExecuTorch program, instead of when it is loaded.

The quantized test needs the quantized kernels, so the test target now
preloads them.

Tested with new permute tests that lower a linear on an 8-D input
followed by an 8-D permute, in float and with static quantization. They
check that no delegate holds a tensor with more than 6 dims, and compare
the program output with the reference. The tests fail without the
change, and they also fail when the common check or the matrix multiply
check is removed.
@shoumikhin shoumikhin added the release notes: xnnpack Changes to the XNNPack backend delegate label Oct 31, 2026
Copilot AI balanced review requested due to automatic review settings October 31, 2026 08:21
@pytorch-bot

pytorch-bot Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit a86580f with merge base aed328d (image):
💚 Looks good so far! There are no failures yet. 💚

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 Oct 31, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

shoumikhin added a commit to shoumikhin/executorch that referenced this pull request Oct 31, 2026
The check that keeps ops with more than 6 dimensions out of the XNNPACK
delegate is not CUDA work, so it moves to pytorch#24380. This returns
backends/xnnpack to what main has.
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 20m 37s —— View job


PR Review: #24380

No blockers. The main problems are that the new AddmmConfig rank check looks at nodes the partition doesn't always take, so a 2-D matmul can be rejected for no reason, and that the new tests don't pin the 6-D limit.

Detailed review

Summary

The PR makes the XNNPACK partitioner leave out every op with an input or output above 6 dims. It also leaves out every decomposed linear whose source partition contains such an op. I found no blockers, only the minor issues below. These findings come from reading the code; I didn't run the tests.

Testing

  • backends/xnnpack/test/ops/test_permute.py:94-127: the tests check neither the limit nor the expected partitioning.

    • No boundary test. The new tests use 8-D tensors and the rest of the file uses 4-D. I found no 6-D tensor anywhere under backends/xnnpack/test. So changing > to >= at xnnpack_config.py:163, which would drop every 6-D op from XNNPACK, would still pass. The 5-D and 7-D cases in the description were only run by hand. Using the existing Permute module, add a 6-D permute that must stay delegated and a 7-D one that must not.
    • Weak assertion. assertGreater(len(lowered_modules), 0) (line 114) and the per-node rank check pass no matter what ends up delegated. Nothing checks the outcome the description claims: the mul delegated, the views and the permute outside. The other tests in this file check this with check_count({"torch.ops.higher_order.executorch_call_delegate": ...}), check and check_not.
    • Dynamic quantization is untested. It is the usual XNNPACK linear recipe. On that path, _get_act_deps (gemm_configs.py:258-300) adds choose_qparams/getitem deps, and the dynamic q/dq on the 8-D activation is then left outside the delegate.

    Fix this →

Performance

  • backends/xnnpack/partition/config/gemm_configs.py:565-566: the check covers nodes the partition doesn't always take.

    • Problem: The check runs over all of src_partition.nodes. With force_non_static_weights_for_f32_linear=True, the partition returned is set(deps) & set(src_partition.nodes) (lines 582-586). For FP32, deps contains no source-partition node: see the bias deps (240-246), weight deps (485-491, 610-616) and activation deps (262-263). The partition would therefore be just the 2-D addmm/mm, yet it is rejected because of >6-D views it would never contain. The matmul then falls back to portable, and the comment on line 565 is wrong in this mode.
    • Trigger: XnnpackPartitioner(force_non_static_weights_for_f32_linear=True) on LinearPermute8d.
    • Fix: Check the nodes actually returned. XNNPartitionerConfig.get_partition (xnnpack_config.py:71) is the only caller of get_node_and_deps, so do it there: return [] when any returned node fails _check_tensor_ranks. get_matched_nodes_from_configs already skips empty partitions (config_partitioner.py:229). This enforces "no delegated tensor above 6-D" for every config, not just the anchor plus this one special case that reaches into the base class's private helper.
    • Keep the anchor check in check_common_constraints, because filter_fn (config_partitioner.py:180-186) relies on it to decompose aten.linear.

    Fix this →

  • Default greedy mode, FP32 only (low confidence). An FP32 linear on a >6-D input loses its 2-D matmul to portable only because the flatten/unflatten views around it are above 6-D. This is because ret_deps is the union with src_partition.nodes (line 585). Leaving just those views out of ret_deps, instead of rejecting the partition, could keep the matmul on XNNPACK. Quantized precisions still have to reject, because their activation dq is itself above 6-D. I did not check that ConvertToLinearPass accepts a linear source partition without its views.

  • Follow-up, not a blocker. A >6-D permute that keeps runs of adjacent input dims together is a ≤6-D permute once those dims are merged. For example, permute(0, 1, 3, 5, 2, 4, 6, 7) on an 8-D tensor becomes permute(0, 2, 4, 1, 3, 5) after merging dims 0–1 and 6–7. Each such permute now splits the delegate and runs as a portable permute_copy. A pass that collapses view → permute → view chains to the minimal rank would keep them on XNNPACK. The patchify permutation in the description can't be reduced this way.

Recommendation

Approve

Nothing blocks. Fixing which nodes gemm_configs.py:566 checks, and adding the 6-D and 7-D boundary tests, are cheap changes worth making before merge.

The XNNPACK partitioner marks the quantize and dequantize nodes around a
quantized conv or linear as implicit, which means folded into that op.
The delegate then does not emit them as separate ops. The marks were set
while the partitioner was still checking the op, so they stayed even
when it then rejected the op.

The quantize and dequantize pairs around a rejected op then went into
delegates of their own, and those delegates skipped the marked nodes.
One delegate had no output, and the next one read a value that nothing
wrote. The program returned zeros instead of failing. For example:

- A statically quantized Conv3d or ConvTranspose3d. XNNPACK has no 3-D
  convolution, so the partitioner rejects it, and the output was all
  zeros.
- A quantized Conv2d or Linear whose output is not quantized, for
  example with a quantization config without an output activation.

Now GEMMConfig marks the nodes in get_partition, once a partition is
taken. A rejected op leaves them as separate ops, and their delegates
convert the values as they should.

Tested with a new conv test: a Conv2d with a quantized input and weight
and a float output. Without this change its output does not match the
reference.
The dims check for a decomposed linear looked at every node of its
source partition. The nodes the partition takes can differ from that.
With force_non_static_weights_for_f32_linear the partition keeps only
the deps inside the source partition, so a 2-D matrix multiply was
rejected because of 8-D views it would never hold.

Now XNNPartitionerConfig.get_partition checks every node it returns,
and returns an empty partition if any of them has more than 6 dims.
This covers every config, not only linear. The check of the op itself
stays in check_common_constraints, because the partitioner uses it to
decide which aten ops to keep from being decomposed.

In its default mode, a decomposed float linear now also keeps its 2-D
matrix multiply on XNNPACK. Its source partition leaves out only the
views above the limit, instead of the whole partition being rejected.
A quantized linear on such an input still runs outside XNNPACK, because
its quantized activation has more than 6 dims.

Tested with stronger permute tests that check which ops are delegated.
A 6-D permute is delegated and a 7-D one is not. A float linear on an
8-D input keeps its matrix multiply in XNNPACK, with and without
force_non_static_weights_for_f32_linear, while its views and the 8-D
permute stay outside. Its static and dynamic quantized variants keep the
matrix multiply outside. Each of these breaks at least one test:
removing the get_partition check, keeping the views in the default mode,
putting back the old source partition check, or lowering the limit to
5 dims.
XNNPACK has no 3-D convolution, so the XNNPACK partitioner never
delegates Conv3d or ConvTranspose3d. The XNNPACK quantizer still
quantized them for static quantization. That only added quantize and
dequantize steps around a float convolution that runs on the CPU
kernels anyway.

Now the conv and conv + relu annotators skip convolutions whose weight
has more than 4 dims, the same way the conv annotator already skips the
convolutions that XNNPACK cannot run with dynamic quantization. The
partitioner tells the convolution dims apart by the weight rank too.

Tested with a new conv test that quantizes a Conv3d with a relu followed
by a ConvTranspose3d. It finds quantize and dequantize ops in the graph
without this change, and none with it.
Copilot AI balanced review requested due to automatic review settings October 31, 2026 18:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

The generic XNNPACK op configs, such as add or permute, mark the
quantize and dequantize nodes around a quantized op as implicit, which
means folded into the op, in get_node_and_deps. get_partition can still
reject the partition after that with its dims check. That cannot happen
for these ops today, because their quantize and dequantize nodes have
the same shapes as the op, which check_common_constraints already
checked. But any later check in get_partition would bring back the wrong
outputs that a rejected quantized conv or linear used to give.

Now these configs mark the nodes in get_partition, once the partition is
taken, as the conv and linear configs do. The marked nodes are the same
as before.

Checked by forcing get_partition to reject the partition of a quantized
add: the program matches the reference with this change, and is wrong
without it.
The comment said the weight rank is the only reliable way to tell the
dims of a convolution. That is true in the partitioner, which sees the
generic convolution op, but the quantizer annotators only match the
conv1d, conv2d and conv3d ops and their transposed forms. The comment
now only says why these convolutions are skipped.
Copilot AI balanced review requested due to automatic review settings October 31, 2026 20:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

A float linear on an input with more than 6 dims is decomposed into
views around a 2-D matrix multiply, and the matrix multiply is still
delegated. But a ReLU or Hardtanh after the linear has the same high
rank as its output. The matrix multiply took it as a fused activation,
and the dims check then rejected the whole partition, so the matrix
multiply ran outside XNNPACK.

Now a float matrix multiply fuses an activation only when the
activation fits in XNNPACK. Otherwise the activation runs outside on
its own, and the matrix multiply stays delegated.

Tested by adding a ReLU case to the float linear permute test, in both
partitioner modes. Without this change the matrix multiply is not
delegated in the default mode.
The conv and linear configs and the generic op configs each marked the
quantize and dequantize nodes of a taken partition as implicit, in two
copies of the same loop. Now XNNPartitionerConfig.get_partition does it
for every config, right after its dims check. It marks the q/dq nodes
of the partition except the partitioned node itself, so a standalone
quantize or dequantize partition stays a separate op. No config returns
other q/dq nodes today, so the marked nodes are the same as before.

With one copy, the order of the check and the marking is covered by the
existing tests: marking before the check breaks the static quantized
permute test, and no marking breaks the quantized conv tests.
… test

The test for 3-D convolutions only checked that no quantize or
dequantize ops appear, so it would also pass if the quantizer quantized
nothing at all. It now runs the same model in 2-D too and checks that
that one is quantized. The name now says what it checks.
Copilot AI balanced review requested due to automatic review settings October 31, 2026 22:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

XNNPartitionerConfig.get_partition can now return an empty partition
when a node has more dims than XNNPACK supports, and it marks the
quantize and dequantize nodes of a taken partition as implicit. The
docstring now says so, so that the author of a new config knows that
the q/dq nodes it returns are folded into its op. The comment above the
marking loop now only gives the reason for it.
Copilot AI balanced review requested due to automatic review settings November 1, 2026 00:09
@shoumikhin shoumikhin changed the title Keep ops with more than 6 dimensions out of the XNNPACK delegate Keep ops above 6 dims out of XNNPACK and fix quantized ops it leaves out Nov 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI balanced review requested due to automatic review settings November 1, 2026 09:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 25m 26s —— View job


PR Review: #24380

No blockers. Two of the new tests are weaker or more brittle than the tests around them, and the new dims check may stop delegating reshapes of constants above 6 dims (low confidence).

Detailed review

Summary

The PR keeps every node with an input or output above 6 dims out of XNNPACK partitions. It also marks q/dq nodes as folded only once their partition is taken, limits force_non_static_weights_for_f32_linear to float linears, and makes the XNNPACK quantizer leave 3-D convs in float. I found no blockers, only the minor issues below. These findings come from reading the code; I didn't run the tests.

Testing

  • backends/xnnpack/test/ops/test_conv2d.py:876-893: the rejected transposed-conv cases compare a quantized output with no quantization tolerance.

    • Problem: The module ends in quantize_per_tensor → dequantize_per_tensor at scale 0.12345, so every output is a multiple of 0.12345.
      • The reference runs ATen's conv_transpose2d, and the program runs the portable convolution kernel. If their fp32 sums for one element fall on opposite sides of a rounding midpoint, that element is off by 0.12345, against atol=1e-3.
      • The accepted case in the same loop goes through _test, which passes qtol=2 (line 279). These cases use the default qtol=0.
      • The weights and inputs come from unseeded torch.randint (lines 806-811, 860-862), so every run draws new values.
      • I haven't measured how often this happens (low confidence). Passing qtol=1 removes the risk.
    • Weaker than the new float-output tests: those tests (line 413, test_linear.py:865) assert a delegate count; this case does not. It would keep passing if the per-tensor q/dq stopped being delegated, and that delegation is the path that returned zeros.

    Fix this →

  • backends/xnnpack/test/ops/test_conv2d.py:359-377: test_qs8_quantizer_skips_conv3d counts only the weights' dequantize_per_channel.

    • Problem: The test doesn't check the activations, so it doesn't pin the description's claim that 3-D convs get no extra quantize and dequantize steps. It also stops at .export(), so it only tests annotation.
    • Fix: The quantizer's annotation tests live in backends/xnnpack/test/quantizer/test_xnnpack_quantizer.py. There, test_conv1d and test_conv2d (lines 45-94) call _test_quantizer with a node_occurrence that counts all four q/dq ops. A test_conv3d in that file with every count at 0 would cover both weights and activations.

    Fix this →

Performance

  • backends/xnnpack/partition/config/xnnpack_config.py:178-190: a reshape of a constant above 6 dims may no longer be delegated (low confidence).

    • Problem: _check_tensor_ranks rejects a node if any of its inputs has more than 6 dims. It does this even when that input is a constant and the node's output has 6 dims or fewer.
      • Before this PR: ViewCopyConfig (generic_node_configs.py:546) took such a view. ConstPropPass (backends/xnnpack/_passes/__init__.py:85) then folded it into a constant of 6 dims or fewer during preprocess, so XNNPACK never saw the larger tensor.
      • Now: the view runs on the portable kernel on every call, and its result enters the delegate as a runtime input.
    • Trigger: register_buffer("pe", torch.randn(1, 2, 2, 2, 2, 2, 4)) with forward(x): return x + self.pe.reshape(16, 8). I haven't run this, and the pattern is uncommon.

    Fix this →

Recommendation

Approve

Nothing blocks merging. Passing qtol in the rejected transposed-conv cases is a one-line change worth making first, because otherwise those cases may fail at random in CI.

The rejected cases of the per-channel transposed conv test ran the
program, but did not check that XNNPACK still runs the quantize and
dequantize nodes around the conv. They now count those two delegates,
like the float-output tests do.

They also allow one quantization step of difference, like the accepted
case. The XNNPACK quantize ignores quant_min, so a value that should
clamp to -127 comes out as -128. With the test's own random inputs,
this happened in 6 to 14 percent of runs per case. The per-test seed in
conftest.py hid it in CI, but a runner without that seed would see it.
The test counted only the weight dequantize nodes, so it would still
pass if the quantizer skipped the weights of a 3-D conv but kept
quantizing its input and output. It now counts all four quantize and
dequantize ops: in 2-D, four for the activations and three dequantize
nodes for the weights, and in 3-D, none.
Copilot AI balanced review requested due to automatic review settings November 1, 2026 12:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

@claude

claude Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Claude finished @shoumikhin's task in 26m 8s —— View job


PR Review: #24380

I found no issues in this round and recommend approving. This is based on reading the code only; I couldn't run the tests in this job.

Detailed review

Summary

The PR keeps every node with an input or output above 6 dims out of XNNPACK partitions. It also marks quantize and dequantize nodes as folded only once their op's partition is taken, applies force_non_static_weights_for_f32_linear only to float linears, and makes the XNNPACK quantizer leave 3-D convs in float. I found no issues. These conclusions come from reading the code, because Python and the tests can't run in this job.

Recommendation

Approve

Nothing blocks merging.

@shoumikhin
shoumikhin merged commit 1549787 into pytorch:main Nov 2, 2026
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@pytorchbot cherry-pick --onto release/1.6 -c critical

@pytorchbot

Copy link
Copy Markdown
Collaborator

Cherry picking #24380

The cherry pick PR is at #24445 and it is recommended to link a critical cherry pick PR with an issue.

Details for Dev Infra team Raised by workflow job

shoumikhin added a commit to shoumikhin/executorch that referenced this pull request Nov 2, 2026
The check that keeps ops with more than 6 dimensions out of the XNNPACK
delegate is not CUDA work, so it moves to pytorch#24380. This returns
backends/xnnpack to what main has.
shoumikhin added a commit that referenced this pull request Nov 2, 2026
## What is wrong today

A model with `torch.nn.Conv3d` lowers without an error but fails at run
time on CPU, for example with XNNPACK:

```
Check failed (in.dim() == 3 || in.dim() == 4): Expect input tensor to be 3-D or 4-D, but got, 5.
```

XNNPACK does not take 3-D or bfloat16 convolutions, so they run on the
portable convolution kernel, which only supported 1-D and 2-D. This
blocks vision encoders with a `Conv3d` patch embedding, such as Qwen2-VL
and Qwen2.5-VL. It is the failure in #11704.

## What this change does

The portable convolution kernel now runs 3-D convolutions, regular and
transposed. 1-D and 2-D convolutions run as 3-D ones with extra dims of
size 1 and add up their terms in the same order as before, so their
results stay the same (except that, with fused multiply-add, a result of
-0 can now be +0, as in PyTorch). The input and output may now have
different dim orders, because `torch.export` gives a `Conv3d` with a
channels-last input a contiguous output. The backend test suite no
longer skips 3-D convolutions.

It also fixes older bugs in the argument checks, which affect 1-D and
2-D too:

- A bias of the wrong length was read past its end (missing
parentheses), and a Bool bias crashed the kernel.
- `groups = 0` divided by zero, and a huge `groups` could overflow in
the bias check.
- A huge padding or dilation, or an output size too large for the 32-bit
tensor sizes, let a call that should fail run. Stride, padding and
dilation must now fit in 32 bits.
- Like PyTorch, the checks now reject a kernel dim of 0, a regular
convolution's kernel larger than the padded input, and an empty spatial
dim unless the batch or channel dim is empty too.

## Testing

- New tests cover grouped regular and transposed 3-D convolutions with
contiguous, channels-last and mixed layouts, and the checks above. All
but one fail without this change; that one checks that an empty batch or
channel dim still works.
- The portable kernel tests pass with AddressSanitizer and
UndefinedBehaviorSanitizer on Linux Arm64.
- The Cortex-M `conv3d` test, now with several channels, a 2x3x3 kernel,
stride and padding, no longer expects a failure and passes in CI on the
Arm simulator.
- A `Conv3d` patch embedding lowered with XNNPACK, and random
convolutions on the portable kernel, match eager PyTorch in float32 and
bfloat16.
- Speed against main on Arm64 and x86-64: regular 1-D and 2-D
convolutions are 1.5 to 13 times faster with GCC and with Clang at
`-Os`, and 18 percent faster to 11 percent slower with Clang at `-O2`
and `-O3`. Transposed ones are 5 percent faster to 17 percent slower.
- Code size for a Cortex-M55 (Arm GNU toolchain 15.2):
`op_convolution.o` grows from 32,484 to 33,263 bytes at `-Os` and from
48,477 to 61,457 at `-O3`. `kernel_ops_util.o`, which holds the argument
checks, grows from 15,746 to 17,743 bytes at `-Os` and from 25,932 to
28,979 at `-O3`.

## Notes

- Depends on #24380. Without it, a static int8 `Conv3d` lowered with
XNNPACK returns wrong values with no error, or fails to load, and the
backend test suite's static int8 XNNPACK `Conv3d` cases fail. Please
merge #24380 first or together with this change.
- An earlier version of 3-D support was reverted, see #19977.
shoumikhin added a commit that referenced this pull request Nov 2, 2026
… input shapes, masked copies as where, tensor checks dropped before compiling, float64, _reshape_copy, scatter_reduce and varlen_attn, follow-ups (#24326)

## What is wrong today

With `enable_cuda_graph_for_method` set, the CUDA backend runs a method
a few times normally, captures a CUDA graph on the fourth call, and
replays that graph after it. Some calls go wrong:

- **A call that cannot be captured fails.** A mask index, such as
`x[mask]` or `x[mask] = v`, reads a count back to the host, and a
capture cannot record that. The capture call returned an error. An
output that is first strided at the capture call failed the same way. A
`.item()` on a device tensor, such as a `torch.cond` predicate computed
on the GPU, ended the process.
- **A replay can return a wrong result with no error.** Replay checked
only each input's byte count. An input that changes from `(2, 3, 4, 4)`
to `(2, 4, 3, 4)` keeps its byte count, so it replayed the captured
shape and returned the wrong output.

## What this change does

- Replay compares each input's shape with the captured one and refuses a
different shape with `InvalidArgument`. The error names the dim and both
sizes. A captured graph only works for the input shapes of the capture
call, and the code comment on the graph phases now says so.
- When a capture fails, the backend runs the same call again without a
graph and returns its result. Graphs stay off for that method, as
before. The retry is safe because a capture records kernels without
running them, and it happens only if the new graph never started
running. The `.item()` shims now refuse to read inside a capture, as the
mask index does, so a capture that reads a device value is retried too
instead of ending the process.
- A method whose program keeps a constant in host memory, such as a
`torch.cond` flag updated on every call, now runs without a graph. Host
code runs only during the capture, so a graph would keep the branch of
the capture call, and a retry after a failed capture would take the
other one. The log names the constant found in host memory, or says the
constants could not be listed.
- An expected capture failure, such as the mask index refusing to run
inside a capture, is logged at Info instead of Error, since the call
then succeeds. A real failure of the call without a graph is still
logged at Error. AOTInductor's generated code still prints its own line
for the refused call.
- The allocations a captured graph makes are recorded only after its
first launch succeeds. Before, a failed first launch left addresses that
were never allocated, and a later cleanup passed them to `cudaFree`. A
failed capture now cleans up with `CudaGraphState::release()` instead of
a copy of it.
- These CUDA graph changes do not change the exported program, so older
programs get them too. A program that uses the new shims described below
(scatter, scatter_reduce, float64 or float16) needs a runtime that has
them.

Smaller commits:

- The CUDA random shims seed from `std::random_device` instead of the
clock, so two processes started in the same second no longer draw the
same numbers. If `std::random_device` throws, or the copy of the seed to
the GPU fails, the shim logs an error and frees what it allocated, and
the next call tries again.
- The wheel's shared library check now lists the mask index and
`index_put` shims.
- With PyTorch 2.14, a program that writes a one-element buffer, such as
a counter, kept returning its first update, because Inductor folded the
update into a constant. The AOTI backends (CUDA and Metal) now turn off
Inductor's joint-graph constant folding, for the whole program, when a
program writes a buffer. On a small Gemma 4 decoder that writes its KV
cache, folding changes two nodes per graph; with it off, export and
decode times stayed within run-to-run noise and the generated tokens
were identical.
- Unit tests for `aoti_torch_get_size`.
- Comments on the index shims and on `set_output_data_ptr` that
described accumulation, the sort count limit and the output index
wrongly are corrected.
- The mask index tests move to a new `test_index_shims.py`, since they
need the Python runtime. They add a 2-D mask, and `index_put` with
repeated indices in deterministic mode (half and bfloat16 accumulation,
last write wins, an int32 index).
- `test_output_shape_changes_at_capture` ends with a call that only a
live graph rejects, so it fails if graphs are off. The KV cache
recapture test checks that dropping the graph also clears the captured
input shapes.

## Follow-ups to #24314

- Delete `test_align_corners_compiles_with_dynamic_sizes`. It could not
fail: it passed with no resize rewrite at all and with the min and max
in the align_corners ratio replaced by a plain `if`, because
`torch.compile` compiles again for an output size of 1. With torch 2.14
and `CI` set it also failed for an unrelated reason, and it is the one
failing test of the CUDA unit test job on main.
`test_bicubic_antialias_resize` already runs an exported program at an
output height of 1, where a plain `if` breaks.
- The comment on that min and max now gives the real reason: an exported
program keeps the branch it was traced with, so a plain `if` divides by
zero at an output size of 1.
- A backend that keeps its data in the `.pte`, such as Metal, now
refuses a `data_name` compile spec built by hand too, before compiling
anything. Before, only `generate_data_name_compile_spec` refused it, and
a hand-built spec was ignored with no name check.
- The CUDA docs warn that Windows and macOS usually treat data names
that differ only in case as the same file.

## Copies through a boolean mask no longer read the mask count back to
the host

`out[mask] = src[mask]` ran as a mask index and a mask `index_put`. Each
of them read the mask's count back to the host and waited for the GPU,
on every call. Transformers' SmolVLM vision embeddings do this for their
position ids.

When the values are the same mask's picks from a tensor shaped like the
destination, every element goes back to where it came from. So a new
pass in the CUDA backend writes the copy as `torch.where(mask, src,
out)`, which gives the same result, bit for bit. It does so inside
`torch.cond` branches and other subgraphs too. It rewrites only when
`where` would lay out its result like the destination, since `where`
takes its layout from its inputs, the mask first, while `index_put`
keeps the destination's layout. It also drops the index and the checks
on its size when nothing else reads them and each check tests only the
index's count and holds for any mask. A user check on the count, such as
`torch._check(x[mask].shape[0] >= 1)`, keeps the index. The pass
compares the two masks with a work list, so masks with long histories do
not hit Python's recursion limit. On an A100, five calls of the SmolVLM
position id code went from 10 count reads and 10 stream waits to none.

## Tensor checks no longer stop the CUDA export

The argument checks in `torch.distributions` export as
`aten._assert_async.msg`. The CUDA backend compiled each one into a
device assert inside a Triton kernel. While compiling, AOTInductor runs
every kernel once to pick its launch settings, on made-up buffers:
random floats, and zeros for integers and bools. So a check that reads a
bool from an earlier kernel saw false and failed, even though it holds
for every real input. The export then stopped with "device-side assert
triggered". A Gaussian policy head, `MultivariateNormal(mean,
scale_tril=...)` with 14 actions, hits this.

A new pass in the CUDA backend now removes these checks before
compiling, so the CUDA delegate no longer runs them. The rest of
ExecuTorch already removes the same checks before a program is saved. A
failed device assert could not come back as an error anyway: it breaks
the CUDA context for the rest of the process. Checks on sizes
(`_assert_scalar`) stay, since they run on the host.

## float64 weights load in the CUDA backend

A program with a float64 weight lowered and saved, then failed to load
with `Malformed CUDA FQN weight metadata`. This happened with a float64
buffer, and with float64 math that constant propagation folds into one
constant, such as a sinusoidal time embedding. The export wrote the
weight correctly, but the runtime had no float64 dtype: the weight cache
refused it, and the runtime's tensor type and dtype shims had none
either.

- The runtime's tensor type now has `Double`, with its 8 byte size. The
same type wraps a method's inputs and outputs, so a float64 input or
output works too.
- The shims export `aoti_torch_dtype_float64`, which compiled code calls
to name the dtype of a float64 constant.
- The weight cache accepts `Double`, and uses 8 bytes when it checks
that a weight fits its storage.
- The shims that still refused float64 accept it: a float64 `.item()`
(`aoti_torch_item_float64`, which did not exist, so the first execute
ended the process), the single-element read those entry points share,
`index_put` with accumulate, and the sort shim. A float16 `.item()` had
the same problem with `aoti_torch_item_float16` and works now too.
- A float read with `.item()` reached Triton kernels truncated to an
integer, in float32 too, so a scale of 1.5 computed as 1 with no error.
AOTInductor declares every symbolic argument of a kernel's launcher
`int64_t`. A compile-time patch in the CUDA backend now declares it with
the float type the kernel takes, the change that the open
pytorch/pytorch#201882 makes in PyTorch.

## `aten._reshape_copy` lowers to the CUDA backend

Torch-TensorRT turns `aten.view` into `aten._reshape_copy`. A view that
TensorRT leaves to PyTorch reaches the CUDA backend in that form, and
the export failed with `missing fallback kernels: aten::_reshape_copy`,
since Inductor has no lowering for it and torch registers no
decomposition. The CUDA backend now decomposes it the way ATen computes
it: a contiguous copy, viewed to the new shape.

## `varlen_attn` lowers to the CUDA backend

`torch.nn.attention.varlen.varlen_attn` runs attention over several
sequences packed into one tensor. Lowering it failed with `missing
fallback kernels: torch_attn::_varlen_attn`, since it calls Flash or
cuDNN attention, which this backend does not ship. The CUDA backend now
decomposes it into ops Inductor lowers: attention over all the packed
tokens, with a mask that keeps each query in its own sequence. The
output is contiguous, like the op's output for a query in the usual
(tokens, heads, dim) order, so reshaping it before the output projection
works.

The decomposition matches the op for causal masks, sliding windows,
grouped-query attention, and query and key sequences of different
lengths. For a query sequence longer than `max_k + 1`, Flash attention 2
(PyTorch's default) and Flash attention 3 give different results for
some windows, because version 2 changes the window based on `max_k`. So
a window other than `(left, 0)` lowers only when `max_q <= max_k + 1` is
known at export time, as in self-attention, and raises a clear error
otherwise. `seqused_k` and `block_table` (paged KV) raise a clear error
too. It computes the weights with a softmax, which subtracts each row's
largest score first, so the weights still add up to one when scores are
large. Tokens before the first sequence or past the last one, such as
the padding of a fixed-size buffer, do not change any sequence's output,
even when they hold NaN. Unlike in Flash attention, a NaN or inf in one
sequence's values does reach the other sequences. It holds a float32
score per head for every pair of packed tokens and runs much slower than
Flash attention, so it suits packs of a few thousand tokens, such as a
few camera images.

## `scatter_reduce` with amax, amin, prod and mean lowers to the CUDA
backend

Lowering `x.scatter_reduce(dim, index, src, "amax")` failed with
`missing fallback kernels: aoti_torch_cuda_scatter_reduce_two_out`, and
so did "amin", "prod" and "mean". Inductor writes a scatter itself only
when it can add atomically, and leaves the other reductions to an ATen
kernel that this backend did not ship. A sum into int64 or bool, a sum
into bfloat16 on GPUs older than sm_90, and deterministic mode use the
same kernel.

- A new shim next to the index shims implements it the way ATen does:
`include_self`, elements the index does not name, the count and integer
rounding of the mean, NaN in amax and amin, and bool for sum only. Half
and bfloat16 sums add in float, as ATen does in deterministic mode. A
product rounds to the tensor's dtype at every step and a mean rounds its
sum before dividing, as ATen does, so half overflows and integers wrap
where ATen's do. A mean also counts its terms in the tensor's dtype, as
ATen does, so 128 int8 ones average to 1.
- It sorts the writes by the element they land on and reduces each
element's values in index order, so the result is deterministic. It also
works inside a CUDA graph. The sort is now one helper that `index_put`
uses too.
- It is slower than ATen's atomic kernel: 1.5 to 3.2 times on an A100 at
512 output rows, 4096 source rows and 1024 columns, and up to 7 times
when many values land on few elements. A decomposition into ops Inductor
lowers natively was measured first. It has to compare every output
element with every source element, and it was 8 to 89 times slower than
ATen's kernel.
- `aoti_cuda_shims.lib` and the wheel's shared library check list the
new shim. The import library now also lists the shims the DLL exported
but it left out, such as `aoti_torch_dtype_float16` and the
`aoti_torch_item_` getters, so a float16 model lowered for Windows
links.

## CUDA programs load without torch on machines with no libgomp

On Linux, Inductor adds OpenMP (`-fopenmp`, `-lgomp`) to every link.
Unless the compiler passes `--as-needed` to the linker, as Ubuntu's GCC
does by default, the compiled library lists `libgomp.so.1` as a
dependency even when it calls no OpenMP function. PyTorch ships a
libgomp, so this went unnoticed while torch was imported. A process
without torch failed to load the program with `libgomp.so.1: cannot open
shared object file` on any machine with no system libgomp, such as a
minimal container.

The CUDA backend now links with `-Wl,--as-needed`, so the linker keeps
only the libraries the program uses. A program that does call OpenMP
keeps libgomp. PyTorch already does the same for MPS builds on macOS,
and pytorch/pytorch#202902 adds it to Inductor for Linux. The torch-free
tests in `test_pybindings_cuda_dlpack.py` now run without a system
libgomp, and the ones that check which libraries got loaded also check
for libgomp. On an A100, a small MLP and CNN exported with this change
load without torch and match eager where the loader cannot find libgomp.

This patch, and the one that lets Triton templates run on GPUs with few
SMs, now stay in place while any thread lowers. Before, when two threads
lowered at once, the first one to finish removed the patch from the
other, and the rest of that compile ran without it.

## A failed CUDA load no longer leaves its library in the temporary
directory

To load a method, the CUDA backend writes the program's compiled library
to a temporary file, such as `/tmp/executorch_cuda_<pid>_0.so`. Only
`destroy()` removed that file, and `destroy()` never runs when the load
fails, so every load that failed after writing the file left it behind.
A scope guard now removes the file unless the load succeeds.
`test_missing_weights_blob.py` now checks that a load that fails for a
missing weights blob leaves nothing in the temporary directory. Without
the fix, that check fails.

The XNNPACK high-rank permute fix moved to #24380.

## The Triton SDPA leaves keys past the end out of the softmax

With `triton_kernel_mode` on (the default), the CUDA backend runs
`scaled_dot_product_attention` as its Triton kernel, `triton::sdpa`. For
power-of-two head sizes, its main kernel reads keys in tiles of 32, 64
or 128. When the number of keys is not a multiple of the tile, the last
tile reaches past the last key. The kernel loaded those positions as
zeros but never removed them from the softmax, so without an attention
mask or a causal mask each one got a score of 0 and took part of the
attention weight. Calls that pass `kv_len` with neither a mask nor
`is_causal`, such as the DFlash draft model's global attention layers,
had the same problem. On an A100, with the query at 0 and the values at
1, where the right output is 1, one key gave 0.031, 33 keys gave 0.516
and 80 keys gave 0.625. With random inputs and one key, the output was
off by 3.4 when the largest value was 3.67. All of these now match eager
PyTorch.

The kernel now gives every position past the last key, or past `kv_len`,
a score of minus infinity, as the other attention kernels in `sdpa.py`
already do. The first version of the kernel did this, and a later
rewrite dropped it. Checking every tile cost up to 8% where no tile
reaches past the end, so only calls that need the check pay for it. A
mask or a causal bound already drops those keys, so calls with one skip
it. The launcher also passes the largest tile size that divides the
number of keys, and tiles that divide it skip the check at compile time.
So calls with a mask or a causal bound, and tiles that divide a key
count known at export time, compile to the same code as before. Without
a mask or a causal bound, a `kv_len` or a symbolic key count checks
every tile. `test_triton_sdpa.py` drops its note that called this a
kernel limitation, runs its basic test with a single key, and runs every
tile without a mask over 80 and 96 keys and over a `kv_len` of 80. These
fail without the fix.

## `scatter` with a tensor source lowers to the CUDA backend

Lowering `x.scatter(dim, index, src)` failed with a `missing fallback
kernels` error that names `aoti_torch_cuda_scatter_src_out` when `src`
is bfloat16, int64 or bool. Inductor writes a scatter from a tensor
itself only in a dtype it can add atomically, so it leaves int64, bool
and, on GPUs older than sm_90, bfloat16 to an ATen kernel, and every
dtype in deterministic mode. A mixture-of-experts layer that writes its
expert outputs back with `torch.zeros_like(h).scatter(1, index, src)` in
bfloat16 hit this on an A100.

A new shim next to the `scatter_reduce` one implements it with the same
checks, the same sorting of the writes by the element they land on, and
the same kernel. The kernel gets a new mode in which only the last write
to each element stores its value. So when values land on the same
element, the last one in index order wins, as ATen does in deterministic
mode; ATen's default CUDA kernel keeps any one of them. As in that
default kernel, an index out of range, negative ones included, triggers
a device-side assert. In deterministic mode, ATen's scatter counts a
negative index from the end instead. The shim takes float, double, half,
bfloat16, the integer dtypes and bool. Like ATen, both scatter shims now
take an int32 index as well as an int64 one. Mostly because of the sort,
the shim is about 10 to 15 times slower than ATen's default kernel for a
mixture-of-experts style bfloat16 scatter of 4 to 34 million values on
an A100. The Windows import library `aoti_cuda_shims.lib` and the
wheel's shared library check now list the new shim. On an A100 with
PyTorch 2.14 and 2.15, scatters in float32, float16, bfloat16, int64 and
bool lower, run and match eager PyTorch exactly. So does a small
mixture-of-experts layer built the same way.
`test_scatter_with_tensor_source` fails without the fix, and its int32
index case fails when the shims take only int64.

## Review order

Start with the CUDA graph changes: `cuda_backend.cpp` and
`cuda_delegate_handle.h` in `backends/cuda/runtime`, the mask and
`.item()` shims in `runtime/shims/index.cu` and `memory.cpp`, and their
tests in `test_output_stride_rearrange.py`. Then the lowering side: the
passes in `backends/cuda/passes`, the decompositions and compile-time
patches in `backends/cuda/cuda_backend.py`, and the folding switch in
`backends/aoti/aoti_backend.py`. Then the scatter and scatter_reduce
shims in `index.cu` with `test_index_shims.py`. The remaining commits
are small follow-ups that stand on their own.

## Testing

On an A100, with the CUDA backend built from this branch:

- `test_index_shims.py`, `test_output_stride_rearrange.py`,
`test_cuda_export.py`, `test_antialiased_resize.py`,
`test_merge_ptes.py` and `test_cuda_weight_metadata.py` pass.
- With the backend built from main, the new CUDA graph tests fail.
- The replay error names the dim, for example "input 0 has size 4 in dim
1, captured with 3".
- `test_cuda_kv_cache` passes, and fails when `release()` keeps the
captured input shapes.
- With the min and max replaced by a plain `if`,
`test_bicubic_antialias_resize` fails.
- With the new data name refusal removed, or moved back behind the
compile, the data name test fails.
- A `torch.cond` on a host-memory flag matches eager on every call; with
a graph it returned the captured branch.
- A random program run from two processes started together drew the same
numbers in 2 of 3 tries before the seed change, and different ones in 3
of 3 after.
- Mask index programs exported from this branch match eager PyTorch on
every call, both on a runtime built from main with CUDA graphs off and
on this branch's runtime with CUDA graphs on.
- The shared shim unit tests pass in a standalone googletest build.
- `test_replace_masked_copy_with_where.py` passes, and fails when the
pass does nothing, is not registered, or skips its accumulate,
same-mask, boolean mask, shared picks or count check. It writes into a
destination filled with 7, so it fails if `where` loses the values the
mask does not pick. A contiguous destination with a channels_last
source, or with a channels_last mask, keeps its `index_put`; before, the
rewrite failed to lower when a later `view(-1)` needed the destination's
layout. It also fails when the pass walks only the top-level graph,
since a masked copy in a `torch.cond` branch then keeps its index, and
when it takes two draws of a random mask for the same mask. Two masks
computed with over a thousand ops each raised RecursionError before. A
check that reads the index's count but tests another size keeps the
index; before, the pass removed it.
- A masked copy lowered through the CUDA partitioner matches eager for
masks that pick some, none and all positions. The test records the graph
the pass returns, and fails when the pass is not registered or leaves
the index in place.
- A module that adds one to a device buffer on every call and reads a
mask's count returns the call number on every call, so the capture call
that runs again without a graph updates the buffer once. With the retry
made to run the call twice, the capture call returns one too many. With
PyTorch 2.14 it returned one on every call even without a graph, because
Inductor folded the written buffer into a fill; it passes now with 2.14
and with 2.15 and 2.16 nightlies.
- On the tiny Gemma 4 decoder from the Gemma 4 31B example's tests,
which writes a KV cache, with PyTorch 2.14 on an A100: with the folding
off, export took 193 s against 190.5 s with it on, a decode call took
945 µs against 1019 µs (medians of three exports and three runs on a
busy machine), and the 41 generated tokens were the same.
- The mask tests check that the runtime log reports one failed capture,
so they fail when CUDA graphs are off or a failed capture is tried
again. `test_host_read_runs_without_a_graph` also runs a module that
scales by a `.item()` read; without the capture check in the item shims,
the process aborts.
- With the debug check on the phase before the retry turned into a
release check, the mask tests pass.
- `test_distribution_argument_check` passes with PyTorch 2.14 and fails
with "device-side assert triggered" without the new pass. It also checks
that the backend lists the pass, since without the pass the export fails
only when autotuning happens to trip the assert. It writes the
`MultivariateNormal` check as `torch._assert_async`, since PyTorch 2.14
cannot export the distribution itself. It also checks that the pass
drops the check and the math that only fed it. A Gaussian policy head
with hidden sizes 16, 64 and 256 exports, runs, and matches eager
PyTorch.
- A float64 buffer and a folded float64 constant load and match eager
PyTorch. Before, both failed to load. `test_float64_weight_loads` fails
without the fix.
- `test_reshape_copy` in `test_cuda_export.py` fails without the fix.
The one in `test_index_shims.py` runs `_reshape_copy` on a transposed, a
sliced and a contiguous input and matches eager PyTorch.
- `test_varlen_attn` in `test_cuda_export.py` fails without the fix. It
lowers a program that flattens the output, compares the decomposition
with the op on CUDA only (on ROCm, varlen_attn runs AOTriton, which
lines an explicit window up with the start of each sequence, while the
decomposition follows Flash attention on CUDA, which lines it up with
the end), including a window in self-attention and NaN values outside
the key sequences, and checks that a window the Flash attention versions
disagree on raises. It also fails when the output is left
non-contiguous, when the window check is removed or refuses every such
window, and when the values outside the key sequences are not zeroed.
Both `test_varlen_attn` tests include queries and keys filled with 1024,
where every key gets the same weight; computing the weights as
`exp(scores - logsumexp)` fails them, since at that size float32 rounds
the log-sum-exp to a whole number and the weights no longer add up to
one. The `test_varlen_attn` in `test_index_shims.py` lowers and runs
programs that call `varlen_attn` with no window, a causal mask and the
windows (8, 0) and (4, 2), flatten each output, and take `cu_seq_q` and
`cu_seq_k` only at run time. They match eager PyTorch.
- `test_missing_weights_blob.py`, `test_cuda_weight_reuse.py` and
`test_device_placement.py` pass.
- `test_scatter_reduce` now runs the sum too, which for int64 goes to
the new shim. The test that a missing scatter kernel fails at export now
tries to lower a scatter of a scalar in deterministic mode. The backend
still lacks that kernel, so the test still checks the scatter fallback
now that the scatter_reduce and scatter shims exist. It fails when the
check stops watching that fallback.
`test_scatter_mean_counts_in_its_dtype` fails with the old count and
when a count that wraps to zero is not turned into one.
`test_float64_and_float16_values` (a sort and `.item()` in each dtype)
and the float64 masked accumulate fail with the old shims, and all pass
now. The `.item()` scale is 1.5, so that test also fails without the
patch that passes a float to Triton kernels as a float.
- `test_scatter_reduce` and `test_sort_shim.py` pass.
`test_scatter_reduce` fails without the fix, and also when the shim
ignores `include_self`, rounds the integer mean toward zero, or lets a
NaN lose in amax and amin. `test_scatter_strides` scatters along the
middle dim of a 3-D tensor, given as a negative dim, from a strided
source and from transposed operands, and fails when the shims walk only
the last two dims. `test_scatter_reduce_edge_cases` covers a bool sum,
int32 and half products that wrap and overflow, and an empty index.
`test_scatter_reduce_sum_adds_in_float` sums 1000 half and bfloat16
values in deterministic mode, and fails when the sum rounds to the dtype
at every step. `test_scatter_reduce_replays_in_a_graph` captures a
`scatter_reduce` program in a CUDA graph and matches eager on every
replay.
- The weight cache, runtime tensor and shim unit tests pass in a
standalone googletest build. Without the fix, the weight cache test of a
float64 entry fails.

- `test_small_gpu_override_survives_a_thread_that_leaves_first` overlaps
two threads inside the small-GPU patch, and fails with the old save and
restore.

- With the seed copy made to fail once, the random shim logs it, fails
that call, and seeds on the next one; before, it went on with an
unseeded state.

Not tested: a failed first graph launch (it cannot be triggered from a
test), a `std::random_device` that throws, Windows, macOS
case-insensitive file systems, the buffer folding change on Metal, and
the ROCm build. No test covers the seed change, since a test cannot make
two processes start in the same second.








### Checked on real robot policies

On the release/1.6 stack with this change, on A100 and H100:
- SmolVLA on the CUDA backend: one device-to-host copy per action chunk
(only the action download), matching eager within the usual tolerance.
- A Gaussian policy whose `torch.distributions` check used to stop the
CUDA export: exports and runs, 0.76 ms per chunk.
- A float64 weight that used to fail at load with "Malformed CUDA FQN
weight metadata": loads and runs, max difference 0.
- Four processes started together: four different random draws, against
two out of four before.
JacobSzwejbka pushed a commit that referenced this pull request Nov 3, 2026
Merge after #24445. It does not depend on it to build, but #24445 brings
the XNNPACK fix for statically quantized 3-D convolutions, and without
it the backend test suite would report those cases as failing once this
pick removes the 3-D skip.

## What is wrong today

A model with `torch.nn.Conv3d` lowers without an error but fails at run
time on CPU, for example with XNNPACK:

```
Check failed (in.dim() == 3 || in.dim() == 4): Expect input tensor to be 3-D or 4-D, but got, 5.
```

XNNPACK does not take 3-D or bfloat16 convolutions, so they run on the
portable convolution kernel, which only supported 1-D and 2-D. This
blocks vision encoders with a `Conv3d` patch embedding, such as Qwen2-VL
and Qwen2.5-VL. It is the failure in #11704.

## What this change does

The portable convolution kernel now runs 3-D convolutions, regular and
transposed. 1-D and 2-D convolutions run as 3-D ones with extra dims of
size 1 and add up their terms in the same order as before, so their
results stay the same (except that, with fused multiply-add, a result of
-0 can now be +0, as in PyTorch). The input and output may now have
different dim orders, because `torch.export` gives a `Conv3d` with a
channels-last input a contiguous output. The backend test suite no
longer skips 3-D convolutions.

It also fixes older bugs in the argument checks, which affect 1-D and
2-D too:

- A bias of the wrong length was read past its end (missing
parentheses), and a Bool bias crashed the kernel.
- `groups = 0` divided by zero, and a huge `groups` could overflow in
the bias check.
- A huge padding or dilation, or an output size too large for the 32-bit
tensor sizes, let a call that should fail run. Stride, padding and
dilation must now fit in 32 bits.
- Like PyTorch, the checks now reject a kernel dim of 0, a regular
convolution's kernel larger than the padded input, and an empty spatial
dim unless the batch or channel dim is empty too.

## Testing

- New tests cover grouped regular and transposed 3-D convolutions with
contiguous, channels-last and mixed layouts, and the checks above. All
but one fail without this change; that one checks that an empty batch or
channel dim still works.
- The portable kernel tests pass with AddressSanitizer and
UndefinedBehaviorSanitizer on Linux Arm64.
- The Cortex-M `conv3d` test, now with several channels, a 2x3x3 kernel,
stride and padding, no longer expects a failure and passes in CI on the
Arm simulator.
- A `Conv3d` patch embedding lowered with XNNPACK, and random
convolutions on the portable kernel, match eager PyTorch in float32 and
bfloat16.
- Speed against main on Arm64 and x86-64: regular 1-D and 2-D
convolutions are 1.5 to 13 times faster with GCC and with Clang at
`-Os`, and 18 percent faster to 11 percent slower with Clang at `-O2`
and `-O3`. Transposed ones are 5 percent faster to 17 percent slower.
- Code size for a Cortex-M55 (Arm GNU toolchain 15.2):
`op_convolution.o` grows from 32,484 to 33,263 bytes at `-Os` and from
48,477 to 61,457 at `-O3`. `kernel_ops_util.o`, which holds the argument
checks, grows from 15,746 to 17,743 bytes at `-Os` and from 25,932 to
28,979 at `-O3`.

## Notes

- Depends on #24380. Without it, a static int8 `Conv3d` lowered with
XNNPACK returns wrong values with no error, or fails to load, and the
backend test suite's static int8 XNNPACK `Conv3d` cases fail. Please
merge #24380 first or together with this change.
- An earlier version of 3-D support was reverted, see #19977.

Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>
shoumikhin added a commit to shoumikhin/lerobot that referenced this pull request Nov 3, 2026
…d drive a robot with the bundle

The export tests compared bundles with their PyTorch policies, mostly
with the PyTorch test backend. Nothing exported the main policies with
every backend that ExecuTorch runs, checked where their programs run, or
ran `lerobot-rollout --bundle.path` on a bundle that a real compiler
wrote.

`tests/export/test_export_backends.py` exports tiny ACT, Diffusion
Policy, pi0, pi0.5, SmolVLA and GR00T checkpoints with
`executorch_xnnpack`, `executorch_cuda` and `executorch_tensorrt`. The
export itself only writes a bundle that reproduces the PyTorch policy's
test case within the bundle's tolerance. Then, for each bundle:

- Each program runs where its backend runs it. XNNPACK bundles hold only
  `XnnpackBackend` delegates. CUDA bundles hold only `CudaBackend`
  delegates, and TensorRT bundles `TensorRTBackend` and possibly
  `CudaBackend` ones, with no operator left on the CPU.
- `lerobot-rollout --bundle.path` drives a recording robot for at least
  12 actions, which takes several chunks, in a process that never loads
  PyTorch.

The recording robot can now show a bundle's test case: with
`--robot.frames=<test case file>` it has a camera for each image of the
test case, so a bundle of a policy with cameras can drive it.

Each backend takes its skip mark from `tests/export/backends.py`, so a
row that a released ExecuTorch or Torch-TensorRT cannot run yet skips
and says which fix it needs.

Two kinds of row fail on every wheel released so far, so they skip up to
the version with the bug and run again on a newer one:

- GR00T with XNNPACK: ExecuTorch 1.6.0's XNNPACK cannot load GR00T's
  vision program, which permutes an 8-D tensor (pytorch/executorch#24380).
- pi0 and pi0.5 with TensorRT: TensorRT 11.4.0.106 cannot build an engine
  for the tiny policies' concatenations. The full-size policies build.

Tested: see the following commit, which runs these tests in CI.
JacobSzwejbka pushed a commit that referenced this pull request Nov 3, 2026
… input shapes, masked copies as where, tensor checks dropped before compiling, float64, _reshape_copy, scatter_reduce and varlen_attn, follow-ups (#24512)

## What is wrong today

With `enable_cuda_graph_for_method` set, the CUDA backend runs a method
a few times normally, captures a CUDA graph on the fourth call, and
replays that graph after it. Some calls go wrong:

- **A call that cannot be captured fails.** A mask index, such as
`x[mask]` or `x[mask] = v`, reads a count back to the host, and a
capture cannot record that. The capture call returned an error. An
output that is first strided at the capture call failed the same way. A
`.item()` on a device tensor, such as a `torch.cond` predicate computed
on the GPU, ended the process.
- **A replay can return a wrong result with no error.** Replay checked
only each input's byte count. An input that changes from `(2, 3, 4, 4)`
to `(2, 4, 3, 4)` keeps its byte count, so it replayed the captured
shape and returned the wrong output.

## What this change does

- Replay compares each input's shape with the captured one and refuses a
different shape with `InvalidArgument`. The error names the dim and both
sizes. A captured graph only works for the input shapes of the capture
call, and the code comment on the graph phases now says so.
- When a capture fails, the backend runs the same call again without a
graph and returns its result. Graphs stay off for that method, as
before. The retry is safe because a capture records kernels without
running them, and it happens only if the new graph never started
running. The `.item()` shims now refuse to read inside a capture, as the
mask index does, so a capture that reads a device value is retried too
instead of ending the process.
- A method whose program keeps a constant in host memory, such as a
`torch.cond` flag updated on every call, now runs without a graph. Host
code runs only during the capture, so a graph would keep the branch of
the capture call, and a retry after a failed capture would take the
other one. The log names the constant found in host memory, or says the
constants could not be listed.
- An expected capture failure, such as the mask index refusing to run
inside a capture, is logged at Info instead of Error, since the call
then succeeds. A real failure of the call without a graph is still
logged at Error. AOTInductor's generated code still prints its own line
for the refused call.
- The allocations a captured graph makes are recorded only after its
first launch succeeds. Before, a failed first launch left addresses that
were never allocated, and a later cleanup passed them to `cudaFree`. A
failed capture now cleans up with `CudaGraphState::release()` instead of
a copy of it.
- These CUDA graph changes do not change the exported program, so older
programs get them too. A program that uses the new shims described below
(scatter, scatter_reduce, float64 or float16) needs a runtime that has
them.

Smaller commits:

- The CUDA random shims seed from `std::random_device` instead of the
clock, so two processes started in the same second no longer draw the
same numbers. If `std::random_device` throws, or the copy of the seed to
the GPU fails, the shim logs an error and frees what it allocated, and
the next call tries again.
- The wheel's shared library check now lists the mask index and
`index_put` shims.
- With PyTorch 2.14, a program that writes a one-element buffer, such as
a counter, kept returning its first update, because Inductor folded the
update into a constant. The AOTI backends (CUDA and Metal) now turn off
Inductor's joint-graph constant folding, for the whole program, when a
program writes a buffer. On a small Gemma 4 decoder that writes its KV
cache, folding changes two nodes per graph; with it off, export and
decode times stayed within run-to-run noise and the generated tokens
were identical.
- Unit tests for `aoti_torch_get_size`.
- Comments on the index shims and on `set_output_data_ptr` that
described accumulation, the sort count limit and the output index
wrongly are corrected.
- The mask index tests move to a new `test_index_shims.py`, since they
need the Python runtime. They add a 2-D mask, and `index_put` with
repeated indices in deterministic mode (half and bfloat16 accumulation,
last write wins, an int32 index).
- `test_output_shape_changes_at_capture` ends with a call that only a
live graph rejects, so it fails if graphs are off. The KV cache
recapture test checks that dropping the graph also clears the captured
input shapes.

## Follow-ups to #24314

- Delete `test_align_corners_compiles_with_dynamic_sizes`. It could not
fail: it passed with no resize rewrite at all and with the min and max
in the align_corners ratio replaced by a plain `if`, because
`torch.compile` compiles again for an output size of 1. With torch 2.14
and `CI` set it also failed for an unrelated reason, and it is the one
failing test of the CUDA unit test job on main.
`test_bicubic_antialias_resize` already runs an exported program at an
output height of 1, where a plain `if` breaks.
- The comment on that min and max now gives the real reason: an exported
program keeps the branch it was traced with, so a plain `if` divides by
zero at an output size of 1.
- A backend that keeps its data in the `.pte`, such as Metal, now
refuses a `data_name` compile spec built by hand too, before compiling
anything. Before, only `generate_data_name_compile_spec` refused it, and
a hand-built spec was ignored with no name check.
- The CUDA docs warn that Windows and macOS usually treat data names
that differ only in case as the same file.

## Copies through a boolean mask no longer read the mask count back to
the host

`out[mask] = src[mask]` ran as a mask index and a mask `index_put`. Each
of them read the mask's count back to the host and waited for the GPU,
on every call. Transformers' SmolVLM vision embeddings do this for their
position ids.

When the values are the same mask's picks from a tensor shaped like the
destination, every element goes back to where it came from. So a new
pass in the CUDA backend writes the copy as `torch.where(mask, src,
out)`, which gives the same result, bit for bit. It does so inside
`torch.cond` branches and other subgraphs too. It rewrites only when
`where` would lay out its result like the destination, since `where`
takes its layout from its inputs, the mask first, while `index_put`
keeps the destination's layout. It also drops the index and the checks
on its size when nothing else reads them and each check tests only the
index's count and holds for any mask. A user check on the count, such as
`torch._check(x[mask].shape[0] >= 1)`, keeps the index. The pass
compares the two masks with a work list, so masks with long histories do
not hit Python's recursion limit. On an A100, five calls of the SmolVLM
position id code went from 10 count reads and 10 stream waits to none.

## Tensor checks no longer stop the CUDA export

The argument checks in `torch.distributions` export as
`aten._assert_async.msg`. The CUDA backend compiled each one into a
device assert inside a Triton kernel. While compiling, AOTInductor runs
every kernel once to pick its launch settings, on made-up buffers:
random floats, and zeros for integers and bools. So a check that reads a
bool from an earlier kernel saw false and failed, even though it holds
for every real input. The export then stopped with "device-side assert
triggered". A Gaussian policy head, `MultivariateNormal(mean,
scale_tril=...)` with 14 actions, hits this.

A new pass in the CUDA backend now removes these checks before
compiling, so the CUDA delegate no longer runs them. The rest of
ExecuTorch already removes the same checks before a program is saved. A
failed device assert could not come back as an error anyway: it breaks
the CUDA context for the rest of the process. Checks on sizes
(`_assert_scalar`) stay, since they run on the host.

## float64 weights load in the CUDA backend

A program with a float64 weight lowered and saved, then failed to load
with `Malformed CUDA FQN weight metadata`. This happened with a float64
buffer, and with float64 math that constant propagation folds into one
constant, such as a sinusoidal time embedding. The export wrote the
weight correctly, but the runtime had no float64 dtype: the weight cache
refused it, and the runtime's tensor type and dtype shims had none
either.

- The runtime's tensor type now has `Double`, with its 8 byte size. The
same type wraps a method's inputs and outputs, so a float64 input or
output works too.
- The shims export `aoti_torch_dtype_float64`, which compiled code calls
to name the dtype of a float64 constant.
- The weight cache accepts `Double`, and uses 8 bytes when it checks
that a weight fits its storage.
- The shims that still refused float64 accept it: a float64 `.item()`
(`aoti_torch_item_float64`, which did not exist, so the first execute
ended the process), the single-element read those entry points share,
`index_put` with accumulate, and the sort shim. A float16 `.item()` had
the same problem with `aoti_torch_item_float16` and works now too.
- A float read with `.item()` reached Triton kernels truncated to an
integer, in float32 too, so a scale of 1.5 computed as 1 with no error.
AOTInductor declares every symbolic argument of a kernel's launcher
`int64_t`. A compile-time patch in the CUDA backend now declares it with
the float type the kernel takes, the change that the open
pytorch/pytorch#201882 makes in PyTorch.

## `aten._reshape_copy` lowers to the CUDA backend

Torch-TensorRT turns `aten.view` into `aten._reshape_copy`. A view that
TensorRT leaves to PyTorch reaches the CUDA backend in that form, and
the export failed with `missing fallback kernels: aten::_reshape_copy`,
since Inductor has no lowering for it and torch registers no
decomposition. The CUDA backend now decomposes it the way ATen computes
it: a contiguous copy, viewed to the new shape.

## `varlen_attn` lowers to the CUDA backend

`torch.nn.attention.varlen.varlen_attn` runs attention over several
sequences packed into one tensor. Lowering it failed with `missing
fallback kernels: torch_attn::_varlen_attn`, since it calls Flash or
cuDNN attention, which this backend does not ship. The CUDA backend now
decomposes it into ops Inductor lowers: attention over all the packed
tokens, with a mask that keeps each query in its own sequence. The
output is contiguous, like the op's output for a query in the usual
(tokens, heads, dim) order, so reshaping it before the output projection
works.

The decomposition matches the op for causal masks, sliding windows,
grouped-query attention, and query and key sequences of different
lengths. For a query sequence longer than `max_k + 1`, Flash attention 2
(PyTorch's default) and Flash attention 3 give different results for
some windows, because version 2 changes the window based on `max_k`. So
a window other than `(left, 0)` lowers only when `max_q <= max_k + 1` is
known at export time, as in self-attention, and raises a clear error
otherwise. `seqused_k` and `block_table` (paged KV) raise a clear error
too. It computes the weights with a softmax, which subtracts each row's
largest score first, so the weights still add up to one when scores are
large. Tokens before the first sequence or past the last one, such as
the padding of a fixed-size buffer, do not change any sequence's output,
even when they hold NaN. Unlike in Flash attention, a NaN or inf in one
sequence's values does reach the other sequences. It holds a float32
score per head for every pair of packed tokens and runs much slower than
Flash attention, so it suits packs of a few thousand tokens, such as a
few camera images.

## `scatter_reduce` with amax, amin, prod and mean lowers to the CUDA
backend

Lowering `x.scatter_reduce(dim, index, src, "amax")` failed with
`missing fallback kernels: aoti_torch_cuda_scatter_reduce_two_out`, and
so did "amin", "prod" and "mean". Inductor writes a scatter itself only
when it can add atomically, and leaves the other reductions to an ATen
kernel that this backend did not ship. A sum into int64 or bool, a sum
into bfloat16 on GPUs older than sm_90, and deterministic mode use the
same kernel.

- A new shim next to the index shims implements it the way ATen does:
`include_self`, elements the index does not name, the count and integer
rounding of the mean, NaN in amax and amin, and bool for sum only. Half
and bfloat16 sums add in float, as ATen does in deterministic mode. A
product rounds to the tensor's dtype at every step and a mean rounds its
sum before dividing, as ATen does, so half overflows and integers wrap
where ATen's do. A mean also counts its terms in the tensor's dtype, as
ATen does, so 128 int8 ones average to 1.
- It sorts the writes by the element they land on and reduces each
element's values in index order, so the result is deterministic. It also
works inside a CUDA graph. The sort is now one helper that `index_put`
uses too.
- It is slower than ATen's atomic kernel: 1.5 to 3.2 times on an A100 at
512 output rows, 4096 source rows and 1024 columns, and up to 7 times
when many values land on few elements. A decomposition into ops Inductor
lowers natively was measured first. It has to compare every output
element with every source element, and it was 8 to 89 times slower than
ATen's kernel.
- `aoti_cuda_shims.lib` and the wheel's shared library check list the
new shim. The import library now also lists the shims the DLL exported
but it left out, such as `aoti_torch_dtype_float16` and the
`aoti_torch_item_` getters, so a float16 model lowered for Windows
links.

## CUDA programs load without torch on machines with no libgomp

On Linux, Inductor adds OpenMP (`-fopenmp`, `-lgomp`) to every link.
Unless the compiler passes `--as-needed` to the linker, as Ubuntu's GCC
does by default, the compiled library lists `libgomp.so.1` as a
dependency even when it calls no OpenMP function. PyTorch ships a
libgomp, so this went unnoticed while torch was imported. A process
without torch failed to load the program with `libgomp.so.1: cannot open
shared object file` on any machine with no system libgomp, such as a
minimal container.

The CUDA backend now links with `-Wl,--as-needed`, so the linker keeps
only the libraries the program uses. A program that does call OpenMP
keeps libgomp. PyTorch already does the same for MPS builds on macOS,
and pytorch/pytorch#202902 adds it to Inductor for Linux. The torch-free
tests in `test_pybindings_cuda_dlpack.py` now run without a system
libgomp, and the ones that check which libraries got loaded also check
for libgomp. On an A100, a small MLP and CNN exported with this change
load without torch and match eager where the loader cannot find libgomp.

This patch, and the one that lets Triton templates run on GPUs with few
SMs, now stay in place while any thread lowers. Before, when two threads
lowered at once, the first one to finish removed the patch from the
other, and the rest of that compile ran without it.

## A failed CUDA load no longer leaves its library in the temporary
directory

To load a method, the CUDA backend writes the program's compiled library
to a temporary file, such as `/tmp/executorch_cuda_<pid>_0.so`. Only
`destroy()` removed that file, and `destroy()` never runs when the load
fails, so every load that failed after writing the file left it behind.
A scope guard now removes the file unless the load succeeds.
`test_missing_weights_blob.py` now checks that a load that fails for a
missing weights blob leaves nothing in the temporary directory. Without
the fix, that check fails.

The XNNPACK high-rank permute fix moved to #24380.

## The Triton SDPA leaves keys past the end out of the softmax

With `triton_kernel_mode` on (the default), the CUDA backend runs
`scaled_dot_product_attention` as its Triton kernel, `triton::sdpa`. For
power-of-two head sizes, its main kernel reads keys in tiles of 32, 64
or 128. When the number of keys is not a multiple of the tile, the last
tile reaches past the last key. The kernel loaded those positions as
zeros but never removed them from the softmax, so without an attention
mask or a causal mask each one got a score of 0 and took part of the
attention weight. Calls that pass `kv_len` with neither a mask nor
`is_causal`, such as the DFlash draft model's global attention layers,
had the same problem. On an A100, with the query at 0 and the values at
1, where the right output is 1, one key gave 0.031, 33 keys gave 0.516
and 80 keys gave 0.625. With random inputs and one key, the output was
off by 3.4 when the largest value was 3.67. All of these now match eager
PyTorch.

The kernel now gives every position past the last key, or past `kv_len`,
a score of minus infinity, as the other attention kernels in `sdpa.py`
already do. The first version of the kernel did this, and a later
rewrite dropped it. Checking every tile cost up to 8% where no tile
reaches past the end, so only calls that need the check pay for it. A
mask or a causal bound already drops those keys, so calls with one skip
it. The launcher also passes the largest tile size that divides the
number of keys, and tiles that divide it skip the check at compile time.
So calls with a mask or a causal bound, and tiles that divide a key
count known at export time, compile to the same code as before. Without
a mask or a causal bound, a `kv_len` or a symbolic key count checks
every tile. `test_triton_sdpa.py` drops its note that called this a
kernel limitation, runs its basic test with a single key, and runs every
tile without a mask over 80 and 96 keys and over a `kv_len` of 80. These
fail without the fix.

## `scatter` with a tensor source lowers to the CUDA backend

Lowering `x.scatter(dim, index, src)` failed with a `missing fallback
kernels` error that names `aoti_torch_cuda_scatter_src_out` when `src`
is bfloat16, int64 or bool. Inductor writes a scatter from a tensor
itself only in a dtype it can add atomically, so it leaves int64, bool
and, on GPUs older than sm_90, bfloat16 to an ATen kernel, and every
dtype in deterministic mode. A mixture-of-experts layer that writes its
expert outputs back with `torch.zeros_like(h).scatter(1, index, src)` in
bfloat16 hit this on an A100.

A new shim next to the `scatter_reduce` one implements it with the same
checks, the same sorting of the writes by the element they land on, and
the same kernel. The kernel gets a new mode in which only the last write
to each element stores its value. So when values land on the same
element, the last one in index order wins, as ATen does in deterministic
mode; ATen's default CUDA kernel keeps any one of them. As in that
default kernel, an index out of range, negative ones included, triggers
a device-side assert. In deterministic mode, ATen's scatter counts a
negative index from the end instead. The shim takes float, double, half,
bfloat16, the integer dtypes and bool. Like ATen, both scatter shims now
take an int32 index as well as an int64 one. Mostly because of the sort,
the shim is about 10 to 15 times slower than ATen's default kernel for a
mixture-of-experts style bfloat16 scatter of 4 to 34 million values on
an A100. The Windows import library `aoti_cuda_shims.lib` and the
wheel's shared library check now list the new shim. On an A100 with
PyTorch 2.14 and 2.15, scatters in float32, float16, bfloat16, int64 and
bool lower, run and match eager PyTorch exactly. So does a small
mixture-of-experts layer built the same way.
`test_scatter_with_tensor_source` fails without the fix, and its int32
index case fails when the shims take only int64.

## Review order

Start with the CUDA graph changes: `cuda_backend.cpp` and
`cuda_delegate_handle.h` in `backends/cuda/runtime`, the mask and
`.item()` shims in `runtime/shims/index.cu` and `memory.cpp`, and their
tests in `test_output_stride_rearrange.py`. Then the lowering side: the
passes in `backends/cuda/passes`, the decompositions and compile-time
patches in `backends/cuda/cuda_backend.py`, and the folding switch in
`backends/aoti/aoti_backend.py`. Then the scatter and scatter_reduce
shims in `index.cu` with `test_index_shims.py`. The remaining commits
are small follow-ups that stand on their own.

## Testing

On an A100, with the CUDA backend built from this branch:

- `test_index_shims.py`, `test_output_stride_rearrange.py`,
`test_cuda_export.py`, `test_antialiased_resize.py`,
`test_merge_ptes.py` and `test_cuda_weight_metadata.py` pass.
- With the backend built from main, the new CUDA graph tests fail.
- The replay error names the dim, for example "input 0 has size 4 in dim
1, captured with 3".
- `test_cuda_kv_cache` passes, and fails when `release()` keeps the
captured input shapes.
- With the min and max replaced by a plain `if`,
`test_bicubic_antialias_resize` fails.
- With the new data name refusal removed, or moved back behind the
compile, the data name test fails.
- A `torch.cond` on a host-memory flag matches eager on every call; with
a graph it returned the captured branch.
- A random program run from two processes started together drew the same
numbers in 2 of 3 tries before the seed change, and different ones in 3
of 3 after.
- Mask index programs exported from this branch match eager PyTorch on
every call, both on a runtime built from main with CUDA graphs off and
on this branch's runtime with CUDA graphs on.
- The shared shim unit tests pass in a standalone googletest build.
- `test_replace_masked_copy_with_where.py` passes, and fails when the
pass does nothing, is not registered, or skips its accumulate,
same-mask, boolean mask, shared picks or count check. It writes into a
destination filled with 7, so it fails if `where` loses the values the
mask does not pick. A contiguous destination with a channels_last
source, or with a channels_last mask, keeps its `index_put`; before, the
rewrite failed to lower when a later `view(-1)` needed the destination's
layout. It also fails when the pass walks only the top-level graph,
since a masked copy in a `torch.cond` branch then keeps its index, and
when it takes two draws of a random mask for the same mask. Two masks
computed with over a thousand ops each raised RecursionError before. A
check that reads the index's count but tests another size keeps the
index; before, the pass removed it.
- A masked copy lowered through the CUDA partitioner matches eager for
masks that pick some, none and all positions. The test records the graph
the pass returns, and fails when the pass is not registered or leaves
the index in place.
- A module that adds one to a device buffer on every call and reads a
mask's count returns the call number on every call, so the capture call
that runs again without a graph updates the buffer once. With the retry
made to run the call twice, the capture call returns one too many. With
PyTorch 2.14 it returned one on every call even without a graph, because
Inductor folded the written buffer into a fill; it passes now with 2.14
and with 2.15 and 2.16 nightlies.
- On the tiny Gemma 4 decoder from the Gemma 4 31B example's tests,
which writes a KV cache, with PyTorch 2.14 on an A100: with the folding
off, export took 193 s against 190.5 s with it on, a decode call took
945 µs against 1019 µs (medians of three exports and three runs on a
busy machine), and the 41 generated tokens were the same.
- The mask tests check that the runtime log reports one failed capture,
so they fail when CUDA graphs are off or a failed capture is tried
again. `test_host_read_runs_without_a_graph` also runs a module that
scales by a `.item()` read; without the capture check in the item shims,
the process aborts.
- With the debug check on the phase before the retry turned into a
release check, the mask tests pass.
- `test_distribution_argument_check` passes with PyTorch 2.14 and fails
with "device-side assert triggered" without the new pass. It also checks
that the backend lists the pass, since without the pass the export fails
only when autotuning happens to trip the assert. It writes the
`MultivariateNormal` check as `torch._assert_async`, since PyTorch 2.14
cannot export the distribution itself. It also checks that the pass
drops the check and the math that only fed it. A Gaussian policy head
with hidden sizes 16, 64 and 256 exports, runs, and matches eager
PyTorch.
- A float64 buffer and a folded float64 constant load and match eager
PyTorch. Before, both failed to load. `test_float64_weight_loads` fails
without the fix.
- `test_reshape_copy` in `test_cuda_export.py` fails without the fix.
The one in `test_index_shims.py` runs `_reshape_copy` on a transposed, a
sliced and a contiguous input and matches eager PyTorch.
- `test_varlen_attn` in `test_cuda_export.py` fails without the fix. It
lowers a program that flattens the output, compares the decomposition
with the op on CUDA only (on ROCm, varlen_attn runs AOTriton, which
lines an explicit window up with the start of each sequence, while the
decomposition follows Flash attention on CUDA, which lines it up with
the end), including a window in self-attention and NaN values outside
the key sequences, and checks that a window the Flash attention versions
disagree on raises. It also fails when the output is left
non-contiguous, when the window check is removed or refuses every such
window, and when the values outside the key sequences are not zeroed.
Both `test_varlen_attn` tests include queries and keys filled with 1024,
where every key gets the same weight; computing the weights as
`exp(scores - logsumexp)` fails them, since at that size float32 rounds
the log-sum-exp to a whole number and the weights no longer add up to
one. The `test_varlen_attn` in `test_index_shims.py` lowers and runs
programs that call `varlen_attn` with no window, a causal mask and the
windows (8, 0) and (4, 2), flatten each output, and take `cu_seq_q` and
`cu_seq_k` only at run time. They match eager PyTorch.
- `test_missing_weights_blob.py`, `test_cuda_weight_reuse.py` and
`test_device_placement.py` pass.
- `test_scatter_reduce` now runs the sum too, which for int64 goes to
the new shim. The test that a missing scatter kernel fails at export now
tries to lower a scatter of a scalar in deterministic mode. The backend
still lacks that kernel, so the test still checks the scatter fallback
now that the scatter_reduce and scatter shims exist. It fails when the
check stops watching that fallback.
`test_scatter_mean_counts_in_its_dtype` fails with the old count and
when a count that wraps to zero is not turned into one.
`test_float64_and_float16_values` (a sort and `.item()` in each dtype)
and the float64 masked accumulate fail with the old shims, and all pass
now. The `.item()` scale is 1.5, so that test also fails without the
patch that passes a float to Triton kernels as a float.
- `test_scatter_reduce` and `test_sort_shim.py` pass.
`test_scatter_reduce` fails without the fix, and also when the shim
ignores `include_self`, rounds the integer mean toward zero, or lets a
NaN lose in amax and amin. `test_scatter_strides` scatters along the
middle dim of a 3-D tensor, given as a negative dim, from a strided
source and from transposed operands, and fails when the shims walk only
the last two dims. `test_scatter_reduce_edge_cases` covers a bool sum,
int32 and half products that wrap and overflow, and an empty index.
`test_scatter_reduce_sum_adds_in_float` sums 1000 half and bfloat16
values in deterministic mode, and fails when the sum rounds to the dtype
at every step. `test_scatter_reduce_replays_in_a_graph` captures a
`scatter_reduce` program in a CUDA graph and matches eager on every
replay.
- The weight cache, runtime tensor and shim unit tests pass in a
standalone googletest build. Without the fix, the weight cache test of a
float64 entry fails.

- `test_small_gpu_override_survives_a_thread_that_leaves_first` overlaps
two threads inside the small-GPU patch, and fails with the old save and
restore.

- With the seed copy made to fail once, the random shim logs it, fails
that call, and seeds on the next one; before, it went on with an
unseeded state.

Not tested: a failed first graph launch (it cannot be triggered from a
test), a `std::random_device` that throws, Windows, macOS
case-insensitive file systems, the buffer folding change on Metal, and
the ROCm build. No test covers the seed change, since a test cannot make
two processes start in the same second.








### Checked on real robot policies

On the release/1.6 stack with this change, on A100 and H100:
- SmolVLA on the CUDA backend: one device-to-host copy per action chunk
(only the action download), matching eager within the usual tolerance.
- A Gaussian policy whose `torch.distributions` check used to stop the
CUDA export: exports and runs, 0.76 ms per chunk.
- A float64 weight that used to fail at load with "Malformed CUDA FQN
weight metadata": loads and runs, max difference 0.
- Four processes started together: four different random draws, against
two out of four before.

---------

Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>
Co-authored-by: Anthony Shoumikhin <shoumikhin@meta.com>
shoumikhin added a commit to shoumikhin/lerobot that referenced this pull request Nov 3, 2026
…d drive a robot with the bundle

The export tests compared bundles with their PyTorch policies, mostly
with the PyTorch test backend. Nothing exported the main policies with
every backend that ExecuTorch runs, checked where their programs run, or
ran `lerobot-rollout --bundle.path` on a bundle that a real compiler
wrote.

`tests/export/test_export_backends.py` exports tiny ACT, Diffusion
Policy, pi0, pi0.5, SmolVLA and GR00T checkpoints with
`executorch_xnnpack`, `executorch_cuda` and `executorch_tensorrt`. The
export itself only writes a bundle that reproduces the PyTorch policy's
test case within the bundle's tolerance. Then, for each bundle:

- Each program runs where its backend runs it. XNNPACK bundles hold only
  `XnnpackBackend` delegates. CUDA bundles hold only `CudaBackend`
  delegates, and TensorRT bundles `TensorRTBackend` and possibly
  `CudaBackend` ones, with no operator left on the CPU.
- `lerobot-rollout --bundle.path` drives a recording robot for at least
  12 actions, which takes several chunks, in a process that never loads
  PyTorch.

The recording robot can now show a bundle's test case: with
`--robot.frames=<test case file>` it has a camera for each image of the
test case, so a bundle of a policy with cameras can drive it.

Each backend takes its skip mark from `tests/export/backends.py`, so a
row that a released ExecuTorch or Torch-TensorRT cannot run yet skips
and says which fix it needs.

Two kinds of row fail on every wheel released so far, so they skip up to
the version with the bug and run again on a newer one:

- GR00T with XNNPACK: ExecuTorch 1.6.0's XNNPACK cannot load GR00T's
  vision program, which permutes an 8-D tensor (pytorch/executorch#24380).
- pi0 and pi0.5 with TensorRT: TensorRT 11.4.0.106 cannot build an engine
  for the tiny policies' concatenations. The full-size policies build.

Tested: see the following commit, which runs these tests in CI.
dijopaul added a commit to foss-xtensa/executorch that referenced this pull request Nov 12, 2026
commit 4776f71b6f0daa5dfc7d758d5836fc1cc0d40154
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 20:41:02 2026 -0800

    XNNPACK: fix wrong outputs when BatchNorm constants share a name, a bf16 matmul load crash, and skipped bmm tests (#24587)

    XNNPACK lowering can give silently wrong results when one Linear or Conv
    is used twice
    and each result goes into its own BatchNorm:

        def forward(self, x, y):
            return self.bn1(self.linear(x)), self.bn2(self.linear(y))

    When the BatchNorms are folded into the Linear, both folds ask for a
    constant with the
    same name, built only from the Linear weight name. The helper that
    creates constants
    returns the existing one when a name is taken, so the second output uses
    the first
    BatchNorm's statistics. The same thing happens when XNNPACK turns
    standalone
    BatchNorms with affine=False into depthwise convolutions: the names came
    from the
    BatchNorm weight, which they do not have, so all of them shared one
    name.

    The commits:

    1. Fold names now include the BatchNorm node, so each fold gets its own
    weight and
    bias. Models with one BatchNorm per Linear or Conv give the same .pte as
    before.
       Vulkan uses the same pass and gets the fix too.
    2. Depthwise convolution names for a standalone BatchNorm now come from
    the BatchNorm
       node, which is unique.
    3. Loading a bf16 batch matrix multiply or linear whose output tensor
    has no dims
    vector no longer crashes. The dims are read the same way defineTensor()
    reads them.
    4. backends/xnnpack/test/ops/test_bmm.py was skipped in pytest.ini and
    pytest-windows.ini. The file passes now, so the skip is removed and
    test_bf16_bmm
       runs in CI.

    Tested on Linux x86_64:
    - New tests for 1 and 2 fail before the fix and pass after it, including
    a lowered and
      serialized run.
    - A new C++ test for 3 crashes before the fix and passes after it.
    - test_bmm.py passes; test_bf16_bmm fails on a build from before the
    bf16 bmm fix.
    - backends/xnnpack/test/passes and backends/xnnpack/test/ops show no new
    failures.
    - resnet18, mobilenet_v2, mobilenet_v3_small and efficientnet_b0 lower
    to byte-identical
      .pte files before and after.
    macOS and Windows were not run locally; the unit test jobs here cover
    them.

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 0c510bf89f0e0f54f5ba72f097ae548367097dbe
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 20:40:54 2026 -0800

    exir and MLX: fix folded-output clones, shared constants, boolean masks, int64 scatter_add, lowering time and memory, and #24404 follow-ups (#24588)

    ### Problem

    Some LeRobot policies fail with Apple's MLX backend:

    - **smolvla, smolvla_libero and pi0** stop in the MLX partitioner with
    `SpecViolationError: ... aten.clone.default ... is not an allowed
    operator type`.
    - **vla_jepa** fails in `to_executorch` with
      ``AttributeError: `_prop_tensor_constant551` is not a buffer``.
    - **vla_jepa and lawam** fail at run time with `[Gather] Boolean indices
    not supported`, and an int64 `scatter_add` with `[ScatterAxis::eval_gpu]
    Does not support int64`.
    - A policy with hundreds of delegates spends about an hour in
    `to_backend`, then its memory grows until it is stopped.

    ### Fix

    - `constant_prop_pass` gives an ATen or training program
    `torch.ops.aten.clone.default` in front of a folded output, not an Edge
    clone.
    - `duplicate_constant_node` gave every user of a shared constant but one
    its own copy, so one program could list the same constant twice, and
    such a program cannot be unlifted. Now users with the same delegation
    tag, or none, share one placeholder. **Behavior change:** a graph
    without tags gets no copies, so callers must tag users first. The MLX
    builder now rejects two placeholders of one constant.
    - `to_backend` copies the shared constants of all delegates in one pass,
    and the result is the same on every run.
    - Fusing a partition sorts the graph in place, so earlier partitions are
    not recompiled. **Behavior change:** `create_submodule_from_nodes` no
    longer recompiles `gm`, so call `gm.recompile()` before you run `gm`.
    - MLX delegates share constant tensors while lowering, and every
    delegate that uses a weight refers to the same bytes.
    - The MLX index handler replaces a constant boolean mask with its
    integer positions, and other boolean indices stay on the CPU. The
    `scatter_add` handler leaves 8-byte types, such as int64, on the CPU.

    **Follow-ups to #24404:**

    - `constant_prop_pass` makes a folded zero-stride constant contiguous
    again. Since #24404 it could stay channels-last, and portable `add` then
    failed at run time with a contiguous input (`different dim orders`).
    - `VgfPartitioner` with `alias_buffer_mutations=True` raises a
    `ValueError` when `tag_mutated_buffer` keeps a mutated buffer in the
    owning program, since it can only alias a buffer the delegate owns.
    Before, it set the aliasing option anyway, with only a warning.
    - The CUDA and Metal partitioners now give a mutated buffer that no op
    reads to the delegate that writes its new value. When that value comes
    from outside the delegates, as in `self.state.copy_(x)`, the buffer
    stays in the owning program, where before lowering failed with `Buffer
    output x does not point to a buffer that exists`.
    - The CUDA overview and the `skip_h2d_for_method_inputs` error say when
    `tag_mutated_buffer` keeps a buffer out.

    ### Testing

    - Each code fix has a new test that fails without it, and the exir and
    MLX tests have no new failures.
    - On synthetic graphs, copying 400 shared constants takes 0.23 s instead
    of 71 s, fusing 500 partitions 3 s instead of 126 s, and weights shared
    by 10 delegates peak at 2.2 GiB instead of 9.2 GiB, with the same
    program.
    - vla_jepa and lawam now lower to MLX, and lingbot_vla_v2 exports with a
    32.6 GB peak.

    cc @digantdesai @freddan80 @per @zingo @oscarandersson8218 @mansnils
    @Sebastian-Larsson @robell @rascani

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 1bdf341de8e0d0cffd9f615507e6aeaffed894ee
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 14:53:30 2026 -0800

    Fix export of zero-stride constants and inputs, and of constants that delegates share (#24526)

    ### What is wrong

    **Zero strides.** ExecuTorch cannot store a zero stride, and
    `contiguous()` keeps one on a size-1 dimension:

    ```python
    t = torch.tensor(2.0).expand(1)
    t.stride()               # (0,)
    t.is_contiguous()        # True
    t.contiguous().stride()  # still (0,)
    ```

    So export fails with `0 in strides is not supported for ExecuTorch.`
    when `constant_prop_pass` folds `self.scale.expand(1)`, a parameter,
    buffer or constant method holds such a tensor, or an example input is
    expanded.

    **Strides of size-1 dimensions.** PyTorch also ignores the stride of a
    size-1 dimension when it checks contiguity, but ExecuTorch derives the
    dim order (the order of dimensions in memory) from every stride:

    ```python
    q = torch.randn(1, 8, 4).transpose(0, 1)
    q.stride()          # (4, 32, 1)
    q.is_contiguous()   # True, yet the program stores dim order (1, 0, 2)
    ```

    An op that reads such a constant fails at run time: portable `bmm` with
    `3 input tensors have different dim orders`, XNNPACK with `Propagating
    input shapes failed`. This happens for a parameter or buffer like `q`,
    and when `constant_prop_pass` folds `self.queries.transpose(0, 1) *
    0.5`.

    **Constants that ops in different delegates read.**
    `duplicate_constant_node` gives each such op its own copy.
    - An op that read it from a list, such as `cat`, kept the original, and
    lowering failed.
    - `tag_mutated_buffer` gave a mutated buffer to a delegate even when
    some readers or writers stayed outside. A reader outside got a stale
    copy, or lowering failed (new value computed outside, read outside, or
    also returned).

    ### What this change does

    - `constant_prop_pass` copies a folded constant with a zero stride into
    a contiguous tensor, also when the zero stride is on a size-1 dimension.
    `without_zero_strides()` in `exir/tensor.py` copies a tensor with a zero
    stride, keeping channels-last when PyTorch calls it channels-last but
    not contiguous. `convert_constant_dim_order_pass` (run by `to_edge`) and
    `TensorSpec.from_tensor(const=True)` use it. That pass also removes a
    zero stride from method inputs, so an input with a zero stride on a
    dimension larger than 1 must be passed contiguous.
    - `convert_constant_dim_order_pass` also checks the dim order that a
    constant's strides give. If it is neither the default nor channels-last,
    the pass copies the constant into the layout PyTorch reports. Constants
    whose strides already give one of those orders do not change, so a
    channels-last weight with a size-1 channel stays channels-last.
    - `duplicate_constant_node` copies the constant for every op that reads
    it, including from a list, and the graph output keeps the original. It
    raises instead of copying a mutated buffer.
    - `tag_mutated_buffer` gives a mutated buffer to a delegate only when
    these hold:
    - every op that reads it (old or new value) or writes it is in that
    delegate;
      - its new value is not returned;
    - some op reads it, unless the partitioner already tagged it for its
    writer.

    Otherwise it stays in the owning program, and any tag on it is removed
    with a warning.

    **Behavior change.** A mutated buffer used by ops in different
    partitions, which used to give stale reads, now stays in the owning
    program and is passed to each delegate: correct, but copied on every
    call. A buffer whose new value is a graph input, as in
    `self.state.copy_(x)`, is no longer tagged, so an existing test in
    `test_partitioner.py` now expects no tag. With the reader delegated,
    that model failed to lower before this change, and now it lowers and
    runs.

    ### Follow-up fixes

    - `constant_prop_pass` makes a folded constant with a zero stride
    contiguous again, as it was before #24404. With #24404 alone, folding a
    zero-stride weight before `to_edge` could give a channels-last constant,
    and a portable op that also reads a contiguous tensor then failed at run
    time.
    - The CUDA overview and the `skip_h2d_for_method_inputs` error now say
    when `tag_mutated_buffer` keeps a buffer out. The overview also says
    that the flag refuses only changed inputs that a delegate reads.

    ### Testing

    - New tests under `exir/emit`, `exir/tests` and `exir/backend/test` each
    fail without their fix.
    - Existing tests in those folders pass as before.
    - Measured on main: MobileNetV2 and a small Conv2d model, default and
    channels-last, give the same `.pte` bytes or the same export error as
    before, with portable, XNNPACK, and XNNPACK after `constant_prop_pass`.

    Tested on Linux with torch 2.14.0 (CPU).

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 812069113a0ecc4c6072f40e7239c9581464496c
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 14:53:22 2026 -0800

    Python runtime: stop a backend's log from deadlocking 2 threads (#24529)

    ## What is wrong today

    2 threads can hang forever when a backend logs while holding a lock, as
    XNNPACK does when a load fails. A log line from a thread that holds the
    GIL (Python's global interpreter lock) goes to `sys.stderr` at once, and
    that Python write can let another thread take the GIL. If that thread
    then waits for the lock, neither thread moves again:

    ```
    thread A: load_method -> takes lock L -> logs -> sys.stderr.write releases the GIL
    thread B: takes the GIL -> execute -> waits for lock L, holding the GIL
    thread A: waits for the GIL forever
    ```

    ## What this change does

    The log function never runs Python code. While `sys.stderr` is the
    process's stderr (fd 2), each line goes straight to fd 2.

    When Python has replaced `sys.stderr` (`capsys`, `redirect_stderr`, a
    Jupyter notebook), the lines wait:

    - A binding call's lines are written as it returns, with no backend lock
    held.
    - A line that Python's main thread logs outside a call while holding the
    GIL (for example while the LLM runner loads) is written before the next
    Python code runs, so it still lands in a short `redirect_stderr` block.
    - Other threads' lines go to a thread that the bindings start. It never
    writes from inside another thread's `sys.stderr.write`, so a stream
    whose `write` takes a lock cannot hang.

    Outside a binding call, threads that do not hold the GIL write to fd 2,
    as today. Up to 1 MiB waits, keeping the newest.

    On Linux and macOS, a line also waits while fd 2 is a pipe or socket
    that stays full, so a GIL holder does not block while a Python thread
    drains it (`wurlitzer.pipes()`). A terminal is written at once, since
    its reader is normally another process. A fatal line goes to fd 2 at
    once while there is room.

    On Linux with Python before 3.13.8, a daemon thread never writes through
    Python. Today it does, and Python can end it mid-write at exit, which
    crashes the process.

    ## Tests

    New tests cover the hang (also from the LLM runner), a stream whose
    `write` takes a lock, a full pipe or socket drained by a thread, lines
    inside a short redirect, daemon threads at exit, and cut error messages.
    Ran them on Linux x86_64 and macOS, and the logging cases in Jupyter
    with fd capture on and off.

    Also fixed: an error message with invalid UTF-8, such as a corrupt
    program's identifier, raised `UnicodeDecodeError`, not `RuntimeError`.
    The docs on registering a PAL (platform abstraction layer) now use the
    right namespace and a complete example.

    ## Follow-up fixes

    The second commit fixes problems found in review after the change merged
    on main:

    - The main thread no longer spins. With `sys.stderr` replaced, while
    some of its lines waited for the bindings' thread, its callback kept
    putting new lines back and asking Python to run it again, so a Python
    loop ran hundreds of times slower. Those lines now go behind the waiting
    ones.
    - Lines keep their order after a call that raised. On the main thread, a
    binding call made in an `except` block now writes the lines the failed
    call left waiting first, then its own.
    - At exit, the bindings' thread no longer goes back to a thread state
    Python may have freed. It stops once exit has begun, and exit waits
    while it takes the GIL back.
    - The README no longer says that every thread that logs outside a call
    hands its line over. Only a thread that holds the GIL does.
    - The bindings' thread writes a line at a time, so a line of normal
    length stays whole beside other threads' lines. It also waits for room
    when stderr is non-blocking and full, instead of dropping its lines.

    New tests cover the order after a call that raised, the loop speed while
    lines wait, and a non-blocking full stderr.

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 00aab140856d85dbd6512bc07576299b2f49baaa
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 14:53:19 2026 -0800

    CUDA backend: lower rotary embeddings written with complex numbers (#24550)

    ### What is wrong today

    Rotary position embeddings are often written with complex numbers:
    `torch.polar`, `torch.view_as_complex`, a product, then
    `torch.view_as_real`. Such a model exports, but the CUDA backend cannot
    lower it:

    ```
    RuntimeError: Method forward missing fallback kernels (5 total):
      - aoti_torch_cuda_mul_Tensor
      - aoti_torch_cuda_polar
      - aten::view_as_complex_copy
      - aten::view_as_real_copy
      - prims::convert_element_type
    ```

    Inductor generates no code for complex numbers, so it calls ATen
    kernels, which this backend does not ship. Torch-TensorRT leaves these
    ops to the CUDA backend, so its programs stop at the same error.

    ### What this change does

    A new pass, `ReplaceComplexWithRealPass`, stores each complex tensor as
    a real tensor with a last dim of size 2 (the layout of `view_as_real`)
    and rewrites the ops on it as real math:

    - `polar` becomes cosine and sine times the magnitude; a complex product
    becomes four real products.
    - `view_as_complex` and `view_as_real` go away.
    - Views, slices, splits, indexing, repeats, joins and casts keep their
    op, with the dims and dtype of the pair. This includes `_reshape_copy`,
    which Torch-TensorRT makes of every view, such as Llama's
    `freqs_cis.view(...)`.
    - Complex constants, buffers and parameters are stored in the real
    layout.

    If the pass cannot rewrite every op on a complex tensor, for example a
    complex add, a complex input or output of the partition, a `torch.cond`
    branch, or complex32, it leaves the program as it is and logs why. So
    the complex math has to stay inside one CUDA partition. Complex128
    becomes float64, which the CUDA runtime supports.

    Also in the CUDA backend:

    - With CUDA graphs on, a copy or clone of a CUDA tensor during the
    capture aborted the process. AOTI returns a part of a constant through
    such a clone. These shims now refuse inside a capture, as `.item()`
    does, and the call runs again without a graph.
    - On ROCm, `test_varlen_attn` compared no case. It now skips only
    windows over query and key sequences that differ, which AOTriton lines
    up differently.

    ### What was tested

    With torch 2.14 on an A100:

    - `test_complex_rotary_embedding` (GPU) and
    `test_replace_complex_with_real.py` (CPU) compare rewritten programs
    with eager, in float32, bfloat16 and complex128, with a dynamic length,
    `_reshape_copy` and a buffer with two placeholders. Unsupported programs
    stay as they are.
    - `test_constant_copy_runs_without_a_graph` and `test_aoti_torch_copy_`
    cover the copy and clone refusal.
    - A Llama-style rotary embedding lowers through Torch-TensorRT 2.14 and
    the CUDA backend.

    The new tests fail without their fixes, and the other CUDA tests pass.
    The ROCm change was not run on ROCm.

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 715e57baa024aaaf08adac95055d4a7613cbaa78
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 10:40:49 2026 -0800

    OpenVINO: fix wrong outputs when a partition returns a copy of its input (#24478)

    ### What is wrong today

    When an OpenVINO partition returns a copy of one of its inputs,
    ExecuTorch gets stale memory back. For example:

    ```python
    class M(torch.nn.Module):
        def forward(self, x):
            y = x.clone()
            return y, torch.sin(y)
    ```

    Lowered with `OpenvinoPartitioner` for CPU, `y` holds whatever its
    buffer held before, and `torch.sin(y)` is wrong too. OpenVINO can even
    overwrite `x`, so later ops that read `x` go wrong as well. The same
    happens for `x.detach()`, `x[:, :]`, and chains like
    `x.clone().clone()`. This made a robot policy exported with LeRobot
    return wrong actions.

    The cause is in OpenVINO. Its PyTorch frontend converts `aten.clone` and
    `aten.alias_copy` to nothing, so the converted model returns its input
    directly. ExecuTorch's runtime sets its output tensors after its input
    tensors. In that order the CPU plugin does not write such an output, and
    it can overwrite the input with the old contents of the output buffer. A
    plain OpenVINO script, without ExecuTorch, shows the same problem in
    every release tried, from 2025.2.0 to 2026.4.1 and a 2026.5 nightly.

    ### What this change does

    The partitioner leaves such a copy out of the partition when its result
    leaves the partition, so ExecuTorch's CPU kernel makes the copy. This
    covers `aten.clone`, `aten.alias_copy`, and
    `dim_order_ops._clone_dim_order` (which becomes `aten.clone` before
    conversion), including chains of them. A copy used only inside the
    partition stays there. OpenVINO skips it anyway, and taking it out could
    hand OpenVINO an input in a dim order it does not read.

    Not touched here: the backend still reads and writes partition inputs
    and outputs in the default dim order, so a channels-last tensor at the
    partition edge can give wrong values.

    Setting the output tensors first also avoids the bug, but only through
    an undocumented detail of the plugin, so this change does not rely on
    it.

    With dim order turned off, a channels-last copy of an input that leaves
    the partition now fails at export instead of giving wrong values.

    `execute_layer_test` gets an optional `compile_config`, to test lowering
    with dim order turned off, where a clone is `aten.clone`.

    ### Testing

    - New tests in `backends/openvino/tests/ops/test_copy.py`.
    `test_copy_of_input_as_output` fails without the partitioner change and
    passes with it. `test_copy_of_input_used_inside` checks that a copy used
    only inside the partition stays there.
    - All OpenVINO op tests pass on Linux x86_64 with OpenVINO 2026.4.1.
    - The robot policy above now exports to OpenVINO and passes its accuracy
    check.

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>
    Co-authored-by: suryasidd <surya.siddharth.pemmaraju@intel.com>
    Co-authored-by: Anthony Shoumikhin <shoumikhin@meta.com>

commit 5366fa1a2d7201cdefd7888b409451446350d2f5
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 10:27:45 2026 -0800

    CUDA backend: CUDA graph fixes for mask indexing, .item() and changed input shapes, masked copies as where, tensor checks dropped before compiling, float64, _reshape_copy, scatter_reduce and varlen_attn, follow-ups (#24512)

    ## What is wrong today

    With `enable_cuda_graph_for_method` set, the CUDA backend runs a method
    a few times normally, captures a CUDA graph on the fourth call, and
    replays that graph after it. Some calls go wrong:

    - **A call that cannot be captured fails.** A mask index, such as
    `x[mask]` or `x[mask] = v`, reads a count back to the host, and a
    capture cannot record that. The capture call returned an error. An
    output that is first strided at the capture call failed the same way. A
    `.item()` on a device tensor, such as a `torch.cond` predicate computed
    on the GPU, ended the process.
    - **A replay can return a wrong result with no error.** Replay checked
    only each input's byte count. An input that changes from `(2, 3, 4, 4)`
    to `(2, 4, 3, 4)` keeps its byte count, so it replayed the captured
    shape and returned the wrong output.

    ## What this change does

    - Replay compares each input's shape with the captured one and refuses a
    different shape with `InvalidArgument`. The error names the dim and both
    sizes. A captured graph only works for the input shapes of the capture
    call, and the code comment on the graph phases now says so.
    - When a capture fails, the backend runs the same call again without a
    graph and returns its result. Graphs stay off for that method, as
    before. The retry is safe because a capture records kernels without
    running them, and it happens only if the new graph never started
    running. The `.item()` shims now refuse to read inside a capture, as the
    mask index does, so a capture that reads a device value is retried too
    instead of ending the process.
    - A method whose program keeps a constant in host memory, such as a
    `torch.cond` flag updated on every call, now runs without a graph. Host
    code runs only during the capture, so a graph would keep the branch of
    the capture call, and a retry after a failed capture would take the
    other one. The log names the constant found in host memory, or says the
    constants could not be listed.
    - An expected capture failure, such as the mask index refusing to run
    inside a capture, is logged at Info instead of Error, since the call
    then succeeds. A real failure of the call without a graph is still
    logged at Error. AOTInductor's generated code still prints its own line
    for the refused call.
    - The allocations a captured graph makes are recorded only after its
    first launch succeeds. Before, a failed first launch left addresses that
    were never allocated, and a later cleanup passed them to `cudaFree`. A
    failed capture now cleans up with `CudaGraphState::release()` instead of
    a copy of it.
    - These CUDA graph changes do not change the exported program, so older
    programs get them too. A program that uses the new shims described below
    (scatter, scatter_reduce, float64 or float16) needs a runtime that has
    them.

    Smaller commits:

    - The CUDA random shims seed from `std::random_device` instead of the
    clock, so two processes started in the same second no longer draw the
    same numbers. If `std::random_device` throws, or the copy of the seed to
    the GPU fails, the shim logs an error and frees what it allocated, and
    the next call tries again.
    - The wheel's shared library check now lists the mask index and
    `index_put` shims.
    - With PyTorch 2.14, a program that writes a one-element buffer, such as
    a counter, kept returning its first update, because Inductor folded the
    update into a constant. The AOTI backends (CUDA and Metal) now turn off
    Inductor's joint-graph constant folding, for the whole program, when a
    program writes a buffer. On a small Gemma 4 decoder that writes its KV
    cache, folding changes two nodes per graph; with it off, export and
    decode times stayed within run-to-run noise and the generated tokens
    were identical.
    - Unit tests for `aoti_torch_get_size`.
    - Comments on the index shims and on `set_output_data_ptr` that
    described accumulation, the sort count limit and the output index
    wrongly are corrected.
    - The mask index tests move to a new `test_index_shims.py`, since they
    need the Python runtime. They add a 2-D mask, and `index_put` with
    repeated indices in deterministic mode (half and bfloat16 accumulation,
    last write wins, an int32 index).
    - `test_output_shape_changes_at_capture` ends with a call that only a
    live graph rejects, so it fails if graphs are off. The KV cache
    recapture test checks that dropping the graph also clears the captured
    input shapes.

    ## Follow-ups to #24314

    - Delete `test_align_corners_compiles_with_dynamic_sizes`. It could not
    fail: it passed with no resize rewrite at all and with the min and max
    in the align_corners ratio replaced by a plain `if`, because
    `torch.compile` compiles again for an output size of 1. With torch 2.14
    and `CI` set it also failed for an unrelated reason, and it is the one
    failing test of the CUDA unit test job on main.
    `test_bicubic_antialias_resize` already runs an exported program at an
    output height of 1, where a plain `if` breaks.
    - The comment on that min and max now gives the real reason: an exported
    program keeps the branch it was traced with, so a plain `if` divides by
    zero at an output size of 1.
    - A backend that keeps its data in the `.pte`, such as Metal, now
    refuses a `data_name` compile spec built by hand too, before compiling
    anything. Before, only `generate_data_name_compile_spec` refused it, and
    a hand-built spec was ignored with no name check.
    - The CUDA docs warn that Windows and macOS usually treat data names
    that differ only in case as the same file.

    ## Copies through a boolean mask no longer read the mask count back to
    the host

    `out[mask] = src[mask]` ran as a mask index and a mask `index_put`. Each
    of them read the mask's count back to the host and waited for the GPU,
    on every call. Transformers' SmolVLM vision embeddings do this for their
    position ids.

    When the values are the same mask's picks from a tensor shaped like the
    destination, every element goes back to where it came from. So a new
    pass in the CUDA backend writes the copy as `torch.where(mask, src,
    out)`, which gives the same result, bit for bit. It does so inside
    `torch.cond` branches and other subgraphs too. It rewrites only when
    `where` would lay out its result like the destination, since `where`
    takes its layout from its inputs, the mask first, while `index_put`
    keeps the destination's layout. It also drops the index and the checks
    on its size when nothing else reads them and each check tests only the
    index's count and holds for any mask. A user check on the count, such as
    `torch._check(x[mask].shape[0] >= 1)`, keeps the index. The pass
    compares the two masks with a work list, so masks with long histories do
    not hit Python's recursion limit. On an A100, five calls of the SmolVLM
    position id code went from 10 count reads and 10 stream waits to none.

    ## Tensor checks no longer stop the CUDA export

    The argument checks in `torch.distributions` export as
    `aten._assert_async.msg`. The CUDA backend compiled each one into a
    device assert inside a Triton kernel. While compiling, AOTInductor runs
    every kernel once to pick its launch settings, on made-up buffers:
    random floats, and zeros for integers and bools. So a check that reads a
    bool from an earlier kernel saw false and failed, even though it holds
    for every real input. The export then stopped with "device-side assert
    triggered". A Gaussian policy head, `MultivariateNormal(mean,
    scale_tril=...)` with 14 actions, hits this.

    A new pass in the CUDA backend now removes these checks before
    compiling, so the CUDA delegate no longer runs them. The rest of
    ExecuTorch already removes the same checks before a program is saved. A
    failed device assert could not come back as an error anyway: it breaks
    the CUDA context for the rest of the process. Checks on sizes
    (`_assert_scalar`) stay, since they run on the host.

    ## float64 weights load in the CUDA backend

    A program with a float64 weight lowered and saved, then failed to load
    with `Malformed CUDA FQN weight metadata`. This happened with a float64
    buffer, and with float64 math that constant propagation folds into one
    constant, such as a sinusoidal time embedding. The export wrote the
    weight correctly, but the runtime had no float64 dtype: the weight cache
    refused it, and the runtime's tensor type and dtype shims had none
    either.

    - The runtime's tensor type now has `Double`, with its 8 byte size. The
    same type wraps a method's inputs and outputs, so a float64 input or
    output works too.
    - The shims export `aoti_torch_dtype_float64`, which compiled code calls
    to name the dtype of a float64 constant.
    - The weight cache accepts `Double`, and uses 8 bytes when it checks
    that a weight fits its storage.
    - The shims that still refused float64 accept it: a float64 `.item()`
    (`aoti_torch_item_float64`, which did not exist, so the first execute
    ended the process), the single-element read those entry points share,
    `index_put` with accumulate, and the sort shim. A float16 `.item()` had
    the same problem with `aoti_torch_item_float16` and works now too.
    - A float read with `.item()` reached Triton kernels truncated to an
    integer, in float32 too, so a scale of 1.5 computed as 1 with no error.
    AOTInductor declares every symbolic argument of a kernel's launcher
    `int64_t`. A compile-time patch in the CUDA backend now declares it with
    the float type the kernel takes, the change that the open
    pytorch/pytorch#201882 makes in PyTorch.

    ## `aten._reshape_copy` lowers to the CUDA backend

    Torch-TensorRT turns `aten.view` into `aten._reshape_copy`. A view that
    TensorRT leaves to PyTorch reaches the CUDA backend in that form, and
    the export failed with `missing fallback kernels: aten::_reshape_copy`,
    since Inductor has no lowering for it and torch registers no
    decomposition. The CUDA backend now decomposes it the way ATen computes
    it: a contiguous copy, viewed to the new shape.

    ## `varlen_attn` lowers to the CUDA backend

    `torch.nn.attention.varlen.varlen_attn` runs attention over several
    sequences packed into one tensor. Lowering it failed with `missing
    fallback kernels: torch_attn::_varlen_attn`, since it calls Flash or
    cuDNN attention, which this backend does not ship. The CUDA backend now
    decomposes it into ops Inductor lowers: attention over all the packed
    tokens, with a mask that keeps each query in its own sequence. The
    output is contiguous, like the op's output for a query in the usual
    (tokens, heads, dim) order, so reshaping it before the output projection
    works.

    The decomposition matches the op for causal masks, sliding windows,
    grouped-query attention, and query and key sequences of different
    lengths. For a query sequence longer than `max_k + 1`, Flash attention 2
    (PyTorch's default) and Flash attention 3 give different results for
    some windows, because version 2 changes the window based on `max_k`. So
    a window other than `(left, 0)` lowers only when `max_q <= max_k + 1` is
    known at export time, as in self-attention, and raises a clear error
    otherwise. `seqused_k` and `block_table` (paged KV) raise a clear error
    too. It computes the weights with a softmax, which subtracts each row's
    largest score first, so the weights still add up to one when scores are
    large. Tokens before the first sequence or past the last one, such as
    the padding of a fixed-size buffer, do not change any sequence's output,
    even when they hold NaN. Unlike in Flash attention, a NaN or inf in one
    sequence's values does reach the other sequences. It holds a float32
    score per head for every pair of packed tokens and runs much slower than
    Flash attention, so it suits packs of a few thousand tokens, such as a
    few camera images.

    ## `scatter_reduce` with amax, amin, prod and mean lowers to the CUDA
    backend

    Lowering `x.scatter_reduce(dim, index, src, "amax")` failed with
    `missing fallback kernels: aoti_torch_cuda_scatter_reduce_two_out`, and
    so did "amin", "prod" and "mean". Inductor writes a scatter itself only
    when it can add atomically, and leaves the other reductions to an ATen
    kernel that this backend did not ship. A sum into int64 or bool, a sum
    into bfloat16 on GPUs older than sm_90, and deterministic mode use the
    same kernel.

    - A new shim next to the index shims implements it the way ATen does:
    `include_self`, elements the index does not name, the count and integer
    rounding of the mean, NaN in amax and amin, and bool for sum only. Half
    and bfloat16 sums add in float, as ATen does in deterministic mode. A
    product rounds to the tensor's dtype at every step and a mean rounds its
    sum before dividing, as ATen does, so half overflows and integers wrap
    where ATen's do. A mean also counts its terms in the tensor's dtype, as
    ATen does, so 128 int8 ones average to 1.
    - It sorts the writes by the element they land on and reduces each
    element's values in index order, so the result is deterministic. It also
    works inside a CUDA graph. The sort is now one helper that `index_put`
    uses too.
    - It is slower than ATen's atomic kernel: 1.5 to 3.2 times on an A100 at
    512 output rows, 4096 source rows and 1024 columns, and up to 7 times
    when many values land on few elements. A decomposition into ops Inductor
    lowers natively was measured first. It has to compare every output
    element with every source element, and it was 8 to 89 times slower than
    ATen's kernel.
    - `aoti_cuda_shims.lib` and the wheel's shared library check list the
    new shim. The import library now also lists the shims the DLL exported
    but it left out, such as `aoti_torch_dtype_float16` and the
    `aoti_torch_item_` getters, so a float16 model lowered for Windows
    links.

    ## CUDA programs load without torch on machines with no libgomp

    On Linux, Inductor adds OpenMP (`-fopenmp`, `-lgomp`) to every link.
    Unless the compiler passes `--as-needed` to the linker, as Ubuntu's GCC
    does by default, the compiled library lists `libgomp.so.1` as a
    dependency even when it calls no OpenMP function. PyTorch ships a
    libgomp, so this went unnoticed while torch was imported. A process
    without torch failed to load the program with `libgomp.so.1: cannot open
    shared object file` on any machine with no system libgomp, such as a
    minimal container.

    The CUDA backend now links with `-Wl,--as-needed`, so the linker keeps
    only the libraries the program uses. A program that does call OpenMP
    keeps libgomp. PyTorch already does the same for MPS builds on macOS,
    and pytorch/pytorch#202902 adds it to Inductor for Linux. The torch-free
    tests in `test_pybindings_cuda_dlpack.py` now run without a system
    libgomp, and the ones that check which libraries got loaded also check
    for libgomp. On an A100, a small MLP and CNN exported with this change
    load without torch and match eager where the loader cannot find libgomp.

    This patch, and the one that lets Triton templates run on GPUs with few
    SMs, now stay in place while any thread lowers. Before, when two threads
    lowered at once, the first one to finish removed the patch from the
    other, and the rest of that compile ran without it.

    ## A failed CUDA load no longer leaves its library in the temporary
    directory

    To load a method, the CUDA backend writes the program's compiled library
    to a temporary file, such as `/tmp/executorch_cuda_<pid>_0.so`. Only
    `destroy()` removed that file, and `destroy()` never runs when the load
    fails, so every load that failed after writing the file left it behind.
    A scope guard now removes the file unless the load succeeds.
    `test_missing_weights_blob.py` now checks that a load that fails for a
    missing weights blob leaves nothing in the temporary directory. Without
    the fix, that check fails.

    The XNNPACK high-rank permute fix moved to #24380.

    ## The Triton SDPA leaves keys past the end out of the softmax

    With `triton_kernel_mode` on (the default), the CUDA backend runs
    `scaled_dot_product_attention` as its Triton kernel, `triton::sdpa`. For
    power-of-two head sizes, its main kernel reads keys in tiles of 32, 64
    or 128. When the number of keys is not a multiple of the tile, the last
    tile reaches past the last key. The kernel loaded those positions as
    zeros but never removed them from the softmax, so without an attention
    mask or a causal mask each one got a score of 0 and took part of the
    attention weight. Calls that pass `kv_len` with neither a mask nor
    `is_causal`, such as the DFlash draft model's global attention layers,
    had the same problem. On an A100, with the query at 0 and the values at
    1, where the right output is 1, one key gave 0.031, 33 keys gave 0.516
    and 80 keys gave 0.625. With random inputs and one key, the output was
    off by 3.4 when the largest value was 3.67. All of these now match eager
    PyTorch.

    The kernel now gives every position past the last key, or past `kv_len`,
    a score of minus infinity, as the other attention kernels in `sdpa.py`
    already do. The first version of the kernel did this, and a later
    rewrite dropped it. Checking every tile cost up to 8% where no tile
    reaches past the end, so only calls that need the check pay for it. A
    mask or a causal bound already drops those keys, so calls with one skip
    it. The launcher also passes the largest tile size that divides the
    number of keys, and tiles that divide it skip the check at compile time.
    So calls with a mask or a causal bound, and tiles that divide a key
    count known at export time, compile to the same code as before. Without
    a mask or a causal bound, a `kv_len` or a symbolic key count checks
    every tile. `test_triton_sdpa.py` drops its note that called this a
    kernel limitation, runs its basic test with a single key, and runs every
    tile without a mask over 80 and 96 keys and over a `kv_len` of 80. These
    fail without the fix.

    ## `scatter` with a tensor source lowers to the CUDA backend

    Lowering `x.scatter(dim, index, src)` failed with a `missing fallback
    kernels` error that names `aoti_torch_cuda_scatter_src_out` when `src`
    is bfloat16, int64 or bool. Inductor writes a scatter from a tensor
    itself only in a dtype it can add atomically, so it leaves int64, bool
    and, on GPUs older than sm_90, bfloat16 to an ATen kernel, and every
    dtype in deterministic mode. A mixture-of-experts layer that writes its
    expert outputs back with `torch.zeros_like(h).scatter(1, index, src)` in
    bfloat16 hit this on an A100.

    A new shim next to the `scatter_reduce` one implements it with the same
    checks, the same sorting of the writes by the element they land on, and
    the same kernel. The kernel gets a new mode in which only the last write
    to each element stores its value. So when values land on the same
    element, the last one in index order wins, as ATen does in deterministic
    mode; ATen's default CUDA kernel keeps any one of them. As in that
    default kernel, an index out of range, negative ones included, triggers
    a device-side assert. In deterministic mode, ATen's scatter counts a
    negative index from the end instead. The shim takes float, double, half,
    bfloat16, the integer dtypes and bool. Like ATen, both scatter shims now
    take an int32 index as well as an int64 one. Mostly because of the sort,
    the shim is about 10 to 15 times slower than ATen's default kernel for a
    mixture-of-experts style bfloat16 scatter of 4 to 34 million values on
    an A100. The Windows import library `aoti_cuda_shims.lib` and the
    wheel's shared library check now list the new shim. On an A100 with
    PyTorch 2.14 and 2.15, scatters in float32, float16, bfloat16, int64 and
    bool lower, run and match eager PyTorch exactly. So does a small
    mixture-of-experts layer built the same way.
    `test_scatter_with_tensor_source` fails without the fix, and its int32
    index case fails when the shims take only int64.

    ## Review order

    Start with the CUDA graph changes: `cuda_backend.cpp` and
    `cuda_delegate_handle.h` in `backends/cuda/runtime`, the mask and
    `.item()` shims in `runtime/shims/index.cu` and `memory.cpp`, and their
    tests in `test_output_stride_rearrange.py`. Then the lowering side: the
    passes in `backends/cuda/passes`, the decompositions and compile-time
    patches in `backends/cuda/cuda_backend.py`, and the folding switch in
    `backends/aoti/aoti_backend.py`. Then the scatter and scatter_reduce
    shims in `index.cu` with `test_index_shims.py`. The remaining commits
    are small follow-ups that stand on their own.

    ## Testing

    On an A100, with the CUDA backend built from this branch:

    - `test_index_shims.py`, `test_output_stride_rearrange.py`,
    `test_cuda_export.py`, `test_antialiased_resize.py`,
    `test_merge_ptes.py` and `test_cuda_weight_metadata.py` pass.
    - With the backend built from main, the new CUDA graph tests fail.
    - The replay error names the dim, for example "input 0 has size 4 in dim
    1, captured with 3".
    - `test_cuda_kv_cache` passes, and fails when `release()` keeps the
    captured input shapes.
    - With the min and max replaced by a plain `if`,
    `test_bicubic_antialias_resize` fails.
    - With the new data name refusal removed, or moved back behind the
    compile, the data name test fails.
    - A `torch.cond` on a host-memory flag matches eager on every call; with
    a graph it returned the captured branch.
    - A random program run from two processes started together drew the same
    numbers in 2 of 3 tries before the seed change, and different ones in 3
    of 3 after.
    - Mask index programs exported from this branch match eager PyTorch on
    every call, both on a runtime built from main with CUDA graphs off and
    on this branch's runtime with CUDA graphs on.
    - The shared shim unit tests pass in a standalone googletest build.
    - `test_replace_masked_copy_with_where.py` passes, and fails when the
    pass does nothing, is not registered, or skips its accumulate,
    same-mask, boolean mask, shared picks or count check. It writes into a
    destination filled with 7, so it fails if `where` loses the values the
    mask does not pick. A contiguous destination with a channels_last
    source, or with a channels_last mask, keeps its `index_put`; before, the
    rewrite failed to lower when a later `view(-1)` needed the destination's
    layout. It also fails when the pass walks only the top-level graph,
    since a masked copy in a `torch.cond` branch then keeps its index, and
    when it takes two draws of a random mask for the same mask. Two masks
    computed with over a thousand ops each raised RecursionError before. A
    check that reads the index's count but tests another size keeps the
    index; before, the pass removed it.
    - A masked copy lowered through the CUDA partitioner matches eager for
    masks that pick some, none and all positions. The test records the graph
    the pass returns, and fails when the pass is not registered or leaves
    the index in place.
    - A module that adds one to a device buffer on every call and reads a
    mask's count returns the call number on every call, so the capture call
    that runs again without a graph updates the buffer once. With the retry
    made to run the call twice, the capture call returns one too many. With
    PyTorch 2.14 it returned one on every call even without a graph, because
    Inductor folded the written buffer into a fill; it passes now with 2.14
    and with 2.15 and 2.16 nightlies.
    - On the tiny Gemma 4 decoder from the Gemma 4 31B example's tests,
    which writes a KV cache, with PyTorch 2.14 on an A100: with the folding
    off, export took 193 s against 190.5 s with it on, a decode call took
    945 µs against 1019 µs (medians of three exports and three runs on a
    busy machine), and the 41 generated tokens were the same.
    - The mask tests check that the runtime log reports one failed capture,
    so they fail when CUDA graphs are off or a failed capture is tried
    again. `test_host_read_runs_without_a_graph` also runs a module that
    scales by a `.item()` read; without the capture check in the item shims,
    the process aborts.
    - With the debug check on the phase before the retry turned into a
    release check, the mask tests pass.
    - `test_distribution_argument_check` passes with PyTorch 2.14 and fails
    with "device-side assert triggered" without the new pass. It also checks
    that the backend lists the pass, since without the pass the export fails
    only when autotuning happens to trip the assert. It writes the
    `MultivariateNormal` check as `torch._assert_async`, since PyTorch 2.14
    cannot export the distribution itself. It also checks that the pass
    drops the check and the math that only fed it. A Gaussian policy head
    with hidden sizes 16, 64 and 256 exports, runs, and matches eager
    PyTorch.
    - A float64 buffer and a folded float64 constant load and match eager
    PyTorch. Before, both failed to load. `test_float64_weight_loads` fails
    without the fix.
    - `test_reshape_copy` in `test_cuda_export.py` fails without the fix.
    The one in `test_index_shims.py` runs `_reshape_copy` on a transposed, a
    sliced and a contiguous input and matches eager PyTorch.
    - `test_varlen_attn` in `test_cuda_export.py` fails without the fix. It
    lowers a program that flattens the output, compares the decomposition
    with the op on CUDA only (on ROCm, varlen_attn runs AOTriton, which
    lines an explicit window up with the start of each sequence, while the
    decomposition follows Flash attention on CUDA, which lines it up with
    the end), including a window in self-attention and NaN values outside
    the key sequences, and checks that a window the Flash attention versions
    disagree on raises. It also fails when the output is left
    non-contiguous, when the window check is removed or refuses every such
    window, and when the values outside the key sequences are not zeroed.
    Both `test_varlen_attn` tests include queries and keys filled with 1024,
    where every key gets the same weight; computing the weights as
    `exp(scores - logsumexp)` fails them, since at that size float32 rounds
    the log-sum-exp to a whole number and the weights no longer add up to
    one. The `test_varlen_attn` in `test_index_shims.py` lowers and runs
    programs that call `varlen_attn` with no window, a causal mask and the
    windows (8, 0) and (4, 2), flatten each output, and take `cu_seq_q` and
    `cu_seq_k` only at run time. They match eager PyTorch.
    - `test_missing_weights_blob.py`, `test_cuda_weight_reuse.py` and
    `test_device_placement.py` pass.
    - `test_scatter_reduce` now runs the sum too, which for int64 goes to
    the new shim. The test that a missing scatter kernel fails at export now
    tries to lower a scatter of a scalar in deterministic mode. The backend
    still lacks that kernel, so the test still checks the scatter fallback
    now that the scatter_reduce and scatter shims exist. It fails when the
    check stops watching that fallback.
    `test_scatter_mean_counts_in_its_dtype` fails with the old count and
    when a count that wraps to zero is not turned into one.
    `test_float64_and_float16_values` (a sort and `.item()` in each dtype)
    and the float64 masked accumulate fail with the old shims, and all pass
    now. The `.item()` scale is 1.5, so that test also fails without the
    patch that passes a float to Triton kernels as a float.
    - `test_scatter_reduce` and `test_sort_shim.py` pass.
    `test_scatter_reduce` fails without the fix, and also when the shim
    ignores `include_self`, rounds the integer mean toward zero, or lets a
    NaN lose in amax and amin. `test_scatter_strides` scatters along the
    middle dim of a 3-D tensor, given as a negative dim, from a strided
    source and from transposed operands, and fails when the shims walk only
    the last two dims. `test_scatter_reduce_edge_cases` covers a bool sum,
    int32 and half products that wrap and overflow, and an empty index.
    `test_scatter_reduce_sum_adds_in_float` sums 1000 half and bfloat16
    values in deterministic mode, and fails when the sum rounds to the dtype
    at every step. `test_scatter_reduce_replays_in_a_graph` captures a
    `scatter_reduce` program in a CUDA graph and matches eager on every
    replay.
    - The weight cache, runtime tensor and shim unit tests pass in a
    standalone googletest build. Without the fix, the weight cache test of a
    float64 entry fails.

    - `test_small_gpu_override_survives_a_thread_that_leaves_first` overlaps
    two threads inside the small-GPU patch, and fails with the old save and
    restore.

    - With the seed copy made to fail once, the random shim logs it, fails
    that call, and seeds on the next one; before, it went on with an
    unseeded state.

    Not tested: a failed first graph launch (it cannot be triggered from a
    test), a `std::random_device` that throws, Windows, macOS
    case-insensitive file systems, the buffer folding change on Metal, and
    the ROCm build. No test covers the seed change, since a test cannot make
    two processes start in the same second.

    ### Checked on real robot policies

    On the release/1.6 stack with this change, on A100 and H100:
    - SmolVLA on the CUDA backend: one device-to-host copy per action chunk
    (only the action download), matching eager within the usual tolerance.
    - A Gaussian policy whose `torch.distributions` check used to stop the
    CUDA export: exports and runs, 0.76 ms per chunk.
    - A float64 weight that used to fail at load with "Malformed CUDA FQN
    weight metadata": loads and runs, max difference 0.
    - Four processes started together: four different random draws, against
    two out of four before.

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>
    Co-authored-by: Anthony Shoumikhin <shoumikhin@meta.com>

commit 7c905611a44158d704d583a1d9b12d55737d8a65
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 10:02:57 2026 -0800

    [release/1.6] Suppress AMD export complexity lint inline (#24511)

    Fixes the release branch [Lint
    failure](https://github.com/pytorch/executorch/actions/runs/41681451895):
    `examples/cuda/scripts/export_amd_pointwise.py` fails Flake8 C901
    because `main` has complexity 13, above the repository limit of 12.

    As requested, add only `# noqa: C901` to the existing `main` definition.
    The earlier refactor is removed; the original script logic, ROCm
    settings and validation checks are restored. All other lint checks
    remain active.

    ## Verification

    The repository-configured Flake8 check passes. AST comparison verifies
    that the entire script is identical to the release baseline apart from
    the comment.

    The final PR diff changes one line in one file. Full ROCm export was not
    run locally on macOS; no executable code changes.

    Prepared with OpenAI Codex.

commit 0a01e1be061f1a6db8560d30a1406d4e9a640703
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:37:09 2026 -0800

    [release/1.6] Fix NXP MCUXpresso CIFAR link failure (#24509)

    Fixes the NXP MCUXpresso failure seen on #24490 and on the release
    branch.

    The [failed
    job](https://github.com/pytorch/executorch/actions/runs/41601038988/job/125799646998)
    reaches the final CIFAR firmware link, then fails with `undefined
    reference to SYS_INFO_PrintAll`. The SDK example calls this helper, but
    our standalone CMake target omits
    `examples/eiq_examples/common/sys_info/sys_info.c`.

    Add that source to the firmware target. The helper also needs
    `MCUXSDK_VERSION_FULL_STR`, which the SDK's normal build supplies
    through a generated header. Our standalone target now uses the SDK's
    `mcux_version.cmake` parser and sets the equivalent compile definition
    from the checked-out SDK version.

    ## Verification

    A focused host CMake build reused the actual example target's source
    list and include paths, the real SDK helper/header, and the SDK version
    parser. The board/runtime sources were replaced with empty fixtures and
    the application with a small C++ caller.

    The original source list reproduced the unresolved `SYS_INFO_PrintAll`
    link error. Adding only the helper reproduced the missing
    `MCUXSDK_VERSION_FULL_STR` compile error. With both changes, the
    executable linked and printed `MCUX SDK version: 2026.12.00-pvw1`.

    `git diff --check` passed. The full ARM firmware build and execution on
    hardware were not run locally; the NXP CI job must validate the complete
    build.

    Only the example's CMakeLists.txt changes (eight added lines). Based on
    release/1.6 after #24490; this PR can land independently of the
    remaining clean backend picks.

    Prepared with OpenAI Codex.

commit 39352871e553fc3b1b565dd2ed8639546710fc13
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:09:25 2026 -0800

    [release/1.6] Add portable antialiased bicubic resize (#24494)

    Supersedes #24447 with a clean release pick from #24400.

    Adds the portable antialiased bicubic kernel, edge-verifier exception,
    registration/build wiring, regression tests and matching Arm
    recipe/documentation updates from the source PR.

    Changes exactly the 15 source PR paths.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24493 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 15
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

    cc @digantdesai @freddan80 @per @zingo @oscarandersson8218 @mansnils
    @Sebastian-Larsson @robell @rascani

commit 986c76fb0863e539f6ccd5a0cb625ff7e8eaa830
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:05:04 2026 -0800

    [release/1.6] Fix OpenVINO bool operations and masked reads (#24493)

    Supersedes #24446 with a clean release pick from #24396.

    Keeps unsupported bool-only min/max/clamp/sign operations on the CPU and
    populates tensor metadata for masked-read lowering. Includes their
    regression tests.

    The bool test class is moved unchanged to test_bool_min_max.py so this
    PR can be based directly on release/1.6 without carrying the core
    OpenVINO commit.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24492 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 4
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed. The combined OpenVINO
    production code matches the previously reviewed final #24446 code; the
    bool test class is preserved unchanged.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

commit 0b72572b56c40c9449ded97339929c6cfe023914
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:04:56 2026 -0800

    [release/1.6] Fix OpenVINO scalars, precision, dynamic outputs and reductions (#24492)

    Supersedes #24377 with a clean release pick from #24294.

    Fixes scalar tensors, float32 CPU defaults, dynamic output buffers and
    integer reductions. Includes the related #24396 runtime, folded-cumsum,
    parameter-count and CI runner follow-ups previously spread across #24377
    and #24446.

    This pick contains the complete core OpenVINO fix and its required
    follow-ups. Bool-op handling and masked-read metadata are isolated in
    the next clean pick. The source float32 default can cost speed on CPUs
    with bfloat16 hardware; inference_precision=bf16 remains available.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24491 in the
    verified landing order. The OpenVINO pair follows the CUDA picks; these
    backend groups can otherwise be reviewed separately.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 16
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed. The combined OpenVINO
    production code matches the previously reviewed final #24446 code; the
    bool test class is preserved unchanged.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

commit 5253dfaccfdb312d96e15d739d1ae1abfb507732
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:04:44 2026 -0800

    [release/1.6] Lower fused CUDA attention variants (#24491)

    Supersedes #24455 with a clean release pick from #24426.

    Restores inference-only fused flash, efficient and cuDNN attention calls
    to scaled_dot_product_attention when the source pass can preserve their
    semantics.

    The fused-attention test is moved unchanged to avoid conflicts with the
    earlier indexing pick. The existing release missing-kernel regression
    test is retained.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24490 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 5
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed. The existing CPU
    graph rewrite test passed its nine cases using the real inherited
    AotiPartitioner implementation. The GPU import/pass-registration test
    could not run locally because Triton is unavailable on macOS.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

commit f3a9b06f548f27359d95a106a825d7b7fe3e39da
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:04:24 2026 -0800

    [release/1.6] Delete duplicate CUDA output handles once (#24490)

    Supersedes #24448 with a clean release pick from #24420.

    Deletes each aliased CUDA output handle once, including error cleanup,
    and carries its regression test.

    The original three source files are the complete scope of this pick.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24489 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 3
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

commit 1f49f64b0026413a38671e1918536e1a17b3d50d
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:03:48 2026 -0800

    [release/1.6] Fix CUDA weights filenames and antialiased resize (#24489)

    Supersedes #24324 with a clean release pick from #24314.

    Adds validated per-program CUDA weights filenames and lowerings for
    antialiased bilinear/bicubic resize. Retains the data-name validation,
    resize-test removal and documentation follow-ups already carried by
    #24324.

    Preserves the release behavior that mismatched CUDA weights fail to
    load. The resize rewrite follows the source PR tolerances rather than
    promising bit-identical floating-point results.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24488 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 10
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
   …
dijopaul added a commit to foss-xtensa/executorch that referenced this pull request Nov 13, 2026
commit 4776f71b6f0daa5dfc7d758d5836fc1cc0d40154
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 20:41:02 2026 -0800

    XNNPACK: fix wrong outputs when BatchNorm constants share a name, a bf16 matmul load crash, and skipped bmm tests (#24587)

    XNNPACK lowering can give silently wrong results when one Linear or Conv
    is used twice
    and each result goes into its own BatchNorm:

        def forward(self, x, y):
            return self.bn1(self.linear(x)), self.bn2(self.linear(y))

    When the BatchNorms are folded into the Linear, both folds ask for a
    constant with the
    same name, built only from the Linear weight name. The helper that
    creates constants
    returns the existing one when a name is taken, so the second output uses
    the first
    BatchNorm's statistics. The same thing happens when XNNPACK turns
    standalone
    BatchNorms with affine=False into depthwise convolutions: the names came
    from the
    BatchNorm weight, which they do not have, so all of them shared one
    name.

    The commits:

    1. Fold names now include the BatchNorm node, so each fold gets its own
    weight and
    bias. Models with one BatchNorm per Linear or Conv give the same .pte as
    before.
       Vulkan uses the same pass and gets the fix too.
    2. Depthwise convolution names for a standalone BatchNorm now come from
    the BatchNorm
       node, which is unique.
    3. Loading a bf16 batch matrix multiply or linear whose output tensor
    has no dims
    vector no longer crashes. The dims are read the same way defineTensor()
    reads them.
    4. backends/xnnpack/test/ops/test_bmm.py was skipped in pytest.ini and
    pytest-windows.ini. The file passes now, so the skip is removed and
    test_bf16_bmm
       runs in CI.

    Tested on Linux x86_64:
    - New tests for 1 and 2 fail before the fix and pass after it, including
    a lowered and
      serialized run.
    - A new C++ test for 3 crashes before the fix and passes after it.
    - test_bmm.py passes; test_bf16_bmm fails on a build from before the
    bf16 bmm fix.
    - backends/xnnpack/test/passes and backends/xnnpack/test/ops show no new
    failures.
    - resnet18, mobilenet_v2, mobilenet_v3_small and efficientnet_b0 lower
    to byte-identical
      .pte files before and after.
    macOS and Windows were not run locally; the unit test jobs here cover
    them.

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 0c510bf89f0e0f54f5ba72f097ae548367097dbe
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 20:40:54 2026 -0800

    exir and MLX: fix folded-output clones, shared constants, boolean masks, int64 scatter_add, lowering time and memory, and #24404 follow-ups (#24588)

    ### Problem

    Some LeRobot policies fail with Apple's MLX backend:

    - **smolvla, smolvla_libero and pi0** stop in the MLX partitioner with
    `SpecViolationError: ... aten.clone.default ... is not an allowed
    operator type`.
    - **vla_jepa** fails in `to_executorch` with
      ``AttributeError: `_prop_tensor_constant551` is not a buffer``.
    - **vla_jepa and lawam** fail at run time with `[Gather] Boolean indices
    not supported`, and an int64 `scatter_add` with `[ScatterAxis::eval_gpu]
    Does not support int64`.
    - A policy with hundreds of delegates spends about an hour in
    `to_backend`, then its memory grows until it is stopped.

    ### Fix

    - `constant_prop_pass` gives an ATen or training program
    `torch.ops.aten.clone.default` in front of a folded output, not an Edge
    clone.
    - `duplicate_constant_node` gave every user of a shared constant but one
    its own copy, so one program could list the same constant twice, and
    such a program cannot be unlifted. Now users with the same delegation
    tag, or none, share one placeholder. **Behavior change:** a graph
    without tags gets no copies, so callers must tag users first. The MLX
    builder now rejects two placeholders of one constant.
    - `to_backend` copies the shared constants of all delegates in one pass,
    and the result is the same on every run.
    - Fusing a partition sorts the graph in place, so earlier partitions are
    not recompiled. **Behavior change:** `create_submodule_from_nodes` no
    longer recompiles `gm`, so call `gm.recompile()` before you run `gm`.
    - MLX delegates share constant tensors while lowering, and every
    delegate that uses a weight refers to the same bytes.
    - The MLX index handler replaces a constant boolean mask with its
    integer positions, and other boolean indices stay on the CPU. The
    `scatter_add` handler leaves 8-byte types, such as int64, on the CPU.

    **Follow-ups to #24404:**

    - `constant_prop_pass` makes a folded zero-stride constant contiguous
    again. Since #24404 it could stay channels-last, and portable `add` then
    failed at run time with a contiguous input (`different dim orders`).
    - `VgfPartitioner` with `alias_buffer_mutations=True` raises a
    `ValueError` when `tag_mutated_buffer` keeps a mutated buffer in the
    owning program, since it can only alias a buffer the delegate owns.
    Before, it set the aliasing option anyway, with only a warning.
    - The CUDA and Metal partitioners now give a mutated buffer that no op
    reads to the delegate that writes its new value. When that value comes
    from outside the delegates, as in `self.state.copy_(x)`, the buffer
    stays in the owning program, where before lowering failed with `Buffer
    output x does not point to a buffer that exists`.
    - The CUDA overview and the `skip_h2d_for_method_inputs` error say when
    `tag_mutated_buffer` keeps a buffer out.

    ### Testing

    - Each code fix has a new test that fails without it, and the exir and
    MLX tests have no new failures.
    - On synthetic graphs, copying 400 shared constants takes 0.23 s instead
    of 71 s, fusing 500 partitions 3 s instead of 126 s, and weights shared
    by 10 delegates peak at 2.2 GiB instead of 9.2 GiB, with the same
    program.
    - vla_jepa and lawam now lower to MLX, and lingbot_vla_v2 exports with a
    32.6 GB peak.

    cc @digantdesai @freddan80 @per @zingo @oscarandersson8218 @mansnils
    @Sebastian-Larsson @robell @rascani

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 1bdf341de8e0d0cffd9f615507e6aeaffed894ee
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 14:53:30 2026 -0800

    Fix export of zero-stride constants and inputs, and of constants that delegates share (#24526)

    ### What is wrong

    **Zero strides.** ExecuTorch cannot store a zero stride, and
    `contiguous()` keeps one on a size-1 dimension:

    ```python
    t = torch.tensor(2.0).expand(1)
    t.stride()               # (0,)
    t.is_contiguous()        # True
    t.contiguous().stride()  # still (0,)
    ```

    So export fails with `0 in strides is not supported for ExecuTorch.`
    when `constant_prop_pass` folds `self.scale.expand(1)`, a parameter,
    buffer or constant method holds such a tensor, or an example input is
    expanded.

    **Strides of size-1 dimensions.** PyTorch also ignores the stride of a
    size-1 dimension when it checks contiguity, but ExecuTorch derives the
    dim order (the order of dimensions in memory) from every stride:

    ```python
    q = torch.randn(1, 8, 4).transpose(0, 1)
    q.stride()          # (4, 32, 1)
    q.is_contiguous()   # True, yet the program stores dim order (1, 0, 2)
    ```

    An op that reads such a constant fails at run time: portable `bmm` with
    `3 input tensors have different dim orders`, XNNPACK with `Propagating
    input shapes failed`. This happens for a parameter or buffer like `q`,
    and when `constant_prop_pass` folds `self.queries.transpose(0, 1) *
    0.5`.

    **Constants that ops in different delegates read.**
    `duplicate_constant_node` gives each such op its own copy.
    - An op that read it from a list, such as `cat`, kept the original, and
    lowering failed.
    - `tag_mutated_buffer` gave a mutated buffer to a delegate even when
    some readers or writers stayed outside. A reader outside got a stale
    copy, or lowering failed (new value computed outside, read outside, or
    also returned).

    ### What this change does

    - `constant_prop_pass` copies a folded constant with a zero stride into
    a contiguous tensor, also when the zero stride is on a size-1 dimension.
    `without_zero_strides()` in `exir/tensor.py` copies a tensor with a zero
    stride, keeping channels-last when PyTorch calls it channels-last but
    not contiguous. `convert_constant_dim_order_pass` (run by `to_edge`) and
    `TensorSpec.from_tensor(const=True)` use it. That pass also removes a
    zero stride from method inputs, so an input with a zero stride on a
    dimension larger than 1 must be passed contiguous.
    - `convert_constant_dim_order_pass` also checks the dim order that a
    constant's strides give. If it is neither the default nor channels-last,
    the pass copies the constant into the layout PyTorch reports. Constants
    whose strides already give one of those orders do not change, so a
    channels-last weight with a size-1 channel stays channels-last.
    - `duplicate_constant_node` copies the constant for every op that reads
    it, including from a list, and the graph output keeps the original. It
    raises instead of copying a mutated buffer.
    - `tag_mutated_buffer` gives a mutated buffer to a delegate only when
    these hold:
    - every op that reads it (old or new value) or writes it is in that
    delegate;
      - its new value is not returned;
    - some op reads it, unless the partitioner already tagged it for its
    writer.

    Otherwise it stays in the owning program, and any tag on it is removed
    with a warning.

    **Behavior change.** A mutated buffer used by ops in different
    partitions, which used to give stale reads, now stays in the owning
    program and is passed to each delegate: correct, but copied on every
    call. A buffer whose new value is a graph input, as in
    `self.state.copy_(x)`, is no longer tagged, so an existing test in
    `test_partitioner.py` now expects no tag. With the reader delegated,
    that model failed to lower before this change, and now it lowers and
    runs.

    ### Follow-up fixes

    - `constant_prop_pass` makes a folded constant with a zero stride
    contiguous again, as it was before #24404. With #24404 alone, folding a
    zero-stride weight before `to_edge` could give a channels-last constant,
    and a portable op that also reads a contiguous tensor then failed at run
    time.
    - The CUDA overview and the `skip_h2d_for_method_inputs` error now say
    when `tag_mutated_buffer` keeps a buffer out. The overview also says
    that the flag refuses only changed inputs that a delegate reads.

    ### Testing

    - New tests under `exir/emit`, `exir/tests` and `exir/backend/test` each
    fail without their fix.
    - Existing tests in those folders pass as before.
    - Measured on main: MobileNetV2 and a small Conv2d model, default and
    channels-last, give the same `.pte` bytes or the same export error as
    before, with portable, XNNPACK, and XNNPACK after `constant_prop_pass`.

    Tested on Linux with torch 2.14.0 (CPU).

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 812069113a0ecc4c6072f40e7239c9581464496c
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 14:53:22 2026 -0800

    Python runtime: stop a backend's log from deadlocking 2 threads (#24529)

    ## What is wrong today

    2 threads can hang forever when a backend logs while holding a lock, as
    XNNPACK does when a load fails. A log line from a thread that holds the
    GIL (Python's global interpreter lock) goes to `sys.stderr` at once, and
    that Python write can let another thread take the GIL. If that thread
    then waits for the lock, neither thread moves again:

    ```
    thread A: load_method -> takes lock L -> logs -> sys.stderr.write releases the GIL
    thread B: takes the GIL -> execute -> waits for lock L, holding the GIL
    thread A: waits for the GIL forever
    ```

    ## What this change does

    The log function never runs Python code. While `sys.stderr` is the
    process's stderr (fd 2), each line goes straight to fd 2.

    When Python has replaced `sys.stderr` (`capsys`, `redirect_stderr`, a
    Jupyter notebook), the lines wait:

    - A binding call's lines are written as it returns, with no backend lock
    held.
    - A line that Python's main thread logs outside a call while holding the
    GIL (for example while the LLM runner loads) is written before the next
    Python code runs, so it still lands in a short `redirect_stderr` block.
    - Other threads' lines go to a thread that the bindings start. It never
    writes from inside another thread's `sys.stderr.write`, so a stream
    whose `write` takes a lock cannot hang.

    Outside a binding call, threads that do not hold the GIL write to fd 2,
    as today. Up to 1 MiB waits, keeping the newest.

    On Linux and macOS, a line also waits while fd 2 is a pipe or socket
    that stays full, so a GIL holder does not block while a Python thread
    drains it (`wurlitzer.pipes()`). A terminal is written at once, since
    its reader is normally another process. A fatal line goes to fd 2 at
    once while there is room.

    On Linux with Python before 3.13.8, a daemon thread never writes through
    Python. Today it does, and Python can end it mid-write at exit, which
    crashes the process.

    ## Tests

    New tests cover the hang (also from the LLM runner), a stream whose
    `write` takes a lock, a full pipe or socket drained by a thread, lines
    inside a short redirect, daemon threads at exit, and cut error messages.
    Ran them on Linux x86_64 and macOS, and the logging cases in Jupyter
    with fd capture on and off.

    Also fixed: an error message with invalid UTF-8, such as a corrupt
    program's identifier, raised `UnicodeDecodeError`, not `RuntimeError`.
    The docs on registering a PAL (platform abstraction layer) now use the
    right namespace and a complete example.

    ## Follow-up fixes

    The second commit fixes problems found in review after the change merged
    on main:

    - The main thread no longer spins. With `sys.stderr` replaced, while
    some of its lines waited for the bindings' thread, its callback kept
    putting new lines back and asking Python to run it again, so a Python
    loop ran hundreds of times slower. Those lines now go behind the waiting
    ones.
    - Lines keep their order after a call that raised. On the main thread, a
    binding call made in an `except` block now writes the lines the failed
    call left waiting first, then its own.
    - At exit, the bindings' thread no longer goes back to a thread state
    Python may have freed. It stops once exit has begun, and exit waits
    while it takes the GIL back.
    - The README no longer says that every thread that logs outside a call
    hands its line over. Only a thread that holds the GIL does.
    - The bindings' thread writes a line at a time, so a line of normal
    length stays whole beside other threads' lines. It also waits for room
    when stderr is non-blocking and full, instead of dropping its lines.

    New tests cover the order after a call that raised, the loop speed while
    lines wait, and a non-blocking full stderr.

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 00aab140856d85dbd6512bc07576299b2f49baaa
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 14:53:19 2026 -0800

    CUDA backend: lower rotary embeddings written with complex numbers (#24550)

    ### What is wrong today

    Rotary position embeddings are often written with complex numbers:
    `torch.polar`, `torch.view_as_complex`, a product, then
    `torch.view_as_real`. Such a model exports, but the CUDA backend cannot
    lower it:

    ```
    RuntimeError: Method forward missing fallback kernels (5 total):
      - aoti_torch_cuda_mul_Tensor
      - aoti_torch_cuda_polar
      - aten::view_as_complex_copy
      - aten::view_as_real_copy
      - prims::convert_element_type
    ```

    Inductor generates no code for complex numbers, so it calls ATen
    kernels, which this backend does not ship. Torch-TensorRT leaves these
    ops to the CUDA backend, so its programs stop at the same error.

    ### What this change does

    A new pass, `ReplaceComplexWithRealPass`, stores each complex tensor as
    a real tensor with a last dim of size 2 (the layout of `view_as_real`)
    and rewrites the ops on it as real math:

    - `polar` becomes cosine and sine times the magnitude; a complex product
    becomes four real products.
    - `view_as_complex` and `view_as_real` go away.
    - Views, slices, splits, indexing, repeats, joins and casts keep their
    op, with the dims and dtype of the pair. This includes `_reshape_copy`,
    which Torch-TensorRT makes of every view, such as Llama's
    `freqs_cis.view(...)`.
    - Complex constants, buffers and parameters are stored in the real
    layout.

    If the pass cannot rewrite every op on a complex tensor, for example a
    complex add, a complex input or output of the partition, a `torch.cond`
    branch, or complex32, it leaves the program as it is and logs why. So
    the complex math has to stay inside one CUDA partition. Complex128
    becomes float64, which the CUDA runtime supports.

    Also in the CUDA backend:

    - With CUDA graphs on, a copy or clone of a CUDA tensor during the
    capture aborted the process. AOTI returns a part of a constant through
    such a clone. These shims now refuse inside a capture, as `.item()`
    does, and the call runs again without a graph.
    - On ROCm, `test_varlen_attn` compared no case. It now skips only
    windows over query and key sequences that differ, which AOTriton lines
    up differently.

    ### What was tested

    With torch 2.14 on an A100:

    - `test_complex_rotary_embedding` (GPU) and
    `test_replace_complex_with_real.py` (CPU) compare rewritten programs
    with eager, in float32, bfloat16 and complex128, with a dynamic length,
    `_reshape_copy` and a buffer with two placeholders. Unsupported programs
    stay as they are.
    - `test_constant_copy_runs_without_a_graph` and `test_aoti_torch_copy_`
    cover the copy and clone refusal.
    - A Llama-style rotary embedding lowers through Torch-TensorRT 2.14 and
    the CUDA backend.

    The new tests fail without their fixes, and the other CUDA tests pass.
    The ROCm change was not run on ROCm.

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>

commit 715e57baa024aaaf08adac95055d4a7613cbaa78
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 10:40:49 2026 -0800

    OpenVINO: fix wrong outputs when a partition returns a copy of its input (#24478)

    ### What is wrong today

    When an OpenVINO partition returns a copy of one of its inputs,
    ExecuTorch gets stale memory back. For example:

    ```python
    class M(torch.nn.Module):
        def forward(self, x):
            y = x.clone()
            return y, torch.sin(y)
    ```

    Lowered with `OpenvinoPartitioner` for CPU, `y` holds whatever its
    buffer held before, and `torch.sin(y)` is wrong too. OpenVINO can even
    overwrite `x`, so later ops that read `x` go wrong as well. The same
    happens for `x.detach()`, `x[:, :]`, and chains like
    `x.clone().clone()`. This made a robot policy exported with LeRobot
    return wrong actions.

    The cause is in OpenVINO. Its PyTorch frontend converts `aten.clone` and
    `aten.alias_copy` to nothing, so the converted model returns its input
    directly. ExecuTorch's runtime sets its output tensors after its input
    tensors. In that order the CPU plugin does not write such an output, and
    it can overwrite the input with the old contents of the output buffer. A
    plain OpenVINO script, without ExecuTorch, shows the same problem in
    every release tried, from 2025.2.0 to 2026.4.1 and a 2026.5 nightly.

    ### What this change does

    The partitioner leaves such a copy out of the partition when its result
    leaves the partition, so ExecuTorch's CPU kernel makes the copy. This
    covers `aten.clone`, `aten.alias_copy`, and
    `dim_order_ops._clone_dim_order` (which becomes `aten.clone` before
    conversion), including chains of them. A copy used only inside the
    partition stays there. OpenVINO skips it anyway, and taking it out could
    hand OpenVINO an input in a dim order it does not read.

    Not touched here: the backend still reads and writes partition inputs
    and outputs in the default dim order, so a channels-last tensor at the
    partition edge can give wrong values.

    Setting the output tensors first also avoids the bug, but only through
    an undocumented detail of the plugin, so this change does not rely on
    it.

    With dim order turned off, a channels-last copy of an input that leaves
    the partition now fails at export instead of giving wrong values.

    `execute_layer_test` gets an optional `compile_config`, to test lowering
    with dim order turned off, where a clone is `aten.clone`.

    ### Testing

    - New tests in `backends/openvino/tests/ops/test_copy.py`.
    `test_copy_of_input_as_output` fails without the partitioner change and
    passes with it. `test_copy_of_input_used_inside` checks that a copy used
    only inside the partition stays there.
    - All OpenVINO op tests pass on Linux x86_64 with OpenVINO 2026.4.1.
    - The robot policy above now exports to OpenVINO and passes its accuracy
    check.

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>
    Co-authored-by: suryasidd <surya.siddharth.pemmaraju@intel.com>
    Co-authored-by: Anthony Shoumikhin <shoumikhin@meta.com>

commit 5366fa1a2d7201cdefd7888b409451446350d2f5
Author: pytorchbot <soumith+bot@pytorch.org>
Date:   Tue Nov 3 10:27:45 2026 -0800

    CUDA backend: CUDA graph fixes for mask indexing, .item() and changed input shapes, masked copies as where, tensor checks dropped before compiling, float64, _reshape_copy, scatter_reduce and varlen_attn, follow-ups (#24512)

    ## What is wrong today

    With `enable_cuda_graph_for_method` set, the CUDA backend runs a method
    a few times normally, captures a CUDA graph on the fourth call, and
    replays that graph after it. Some calls go wrong:

    - **A call that cannot be captured fails.** A mask index, such as
    `x[mask]` or `x[mask] = v`, reads a count back to the host, and a
    capture cannot record that. The capture call returned an error. An
    output that is first strided at the capture call failed the same way. A
    `.item()` on a device tensor, such as a `torch.cond` predicate computed
    on the GPU, ended the process.
    - **A replay can return a wrong result with no error.** Replay checked
    only each input's byte count. An input that changes from `(2, 3, 4, 4)`
    to `(2, 4, 3, 4)` keeps its byte count, so it replayed the captured
    shape and returned the wrong output.

    ## What this change does

    - Replay compares each input's shape with the captured one and refuses a
    different shape with `InvalidArgument`. The error names the dim and both
    sizes. A captured graph only works for the input shapes of the capture
    call, and the code comment on the graph phases now says so.
    - When a capture fails, the backend runs the same call again without a
    graph and returns its result. Graphs stay off for that method, as
    before. The retry is safe because a capture records kernels without
    running them, and it happens only if the new graph never started
    running. The `.item()` shims now refuse to read inside a capture, as the
    mask index does, so a capture that reads a device value is retried too
    instead of ending the process.
    - A method whose program keeps a constant in host memory, such as a
    `torch.cond` flag updated on every call, now runs without a graph. Host
    code runs only during the capture, so a graph would keep the branch of
    the capture call, and a retry after a failed capture would take the
    other one. The log names the constant found in host memory, or says the
    constants could not be listed.
    - An expected capture failure, such as the mask index refusing to run
    inside a capture, is logged at Info instead of Error, since the call
    then succeeds. A real failure of the call without a graph is still
    logged at Error. AOTInductor's generated code still prints its own line
    for the refused call.
    - The allocations a captured graph makes are recorded only after its
    first launch succeeds. Before, a failed first launch left addresses that
    were never allocated, and a later cleanup passed them to `cudaFree`. A
    failed capture now cleans up with `CudaGraphState::release()` instead of
    a copy of it.
    - These CUDA graph changes do not change the exported program, so older
    programs get them too. A program that uses the new shims described below
    (scatter, scatter_reduce, float64 or float16) needs a runtime that has
    them.

    Smaller commits:

    - The CUDA random shims seed from `std::random_device` instead of the
    clock, so two processes started in the same second no longer draw the
    same numbers. If `std::random_device` throws, or the copy of the seed to
    the GPU fails, the shim logs an error and frees what it allocated, and
    the next call tries again.
    - The wheel's shared library check now lists the mask index and
    `index_put` shims.
    - With PyTorch 2.14, a program that writes a one-element buffer, such as
    a counter, kept returning its first update, because Inductor folded the
    update into a constant. The AOTI backends (CUDA and Metal) now turn off
    Inductor's joint-graph constant folding, for the whole program, when a
    program writes a buffer. On a small Gemma 4 decoder that writes its KV
    cache, folding changes two nodes per graph; with it off, export and
    decode times stayed within run-to-run noise and the generated tokens
    were identical.
    - Unit tests for `aoti_torch_get_size`.
    - Comments on the index shims and on `set_output_data_ptr` that
    described accumulation, the sort count limit and the output index
    wrongly are corrected.
    - The mask index tests move to a new `test_index_shims.py`, since they
    need the Python runtime. They add a 2-D mask, and `index_put` with
    repeated indices in deterministic mode (half and bfloat16 accumulation,
    last write wins, an int32 index).
    - `test_output_shape_changes_at_capture` ends with a call that only a
    live graph rejects, so it fails if graphs are off. The KV cache
    recapture test checks that dropping the graph also clears the captured
    input shapes.

    ## Follow-ups to #24314

    - Delete `test_align_corners_compiles_with_dynamic_sizes`. It could not
    fail: it passed with no resize rewrite at all and with the min and max
    in the align_corners ratio replaced by a plain `if`, because
    `torch.compile` compiles again for an output size of 1. With torch 2.14
    and `CI` set it also failed for an unrelated reason, and it is the one
    failing test of the CUDA unit test job on main.
    `test_bicubic_antialias_resize` already runs an exported program at an
    output height of 1, where a plain `if` breaks.
    - The comment on that min and max now gives the real reason: an exported
    program keeps the branch it was traced with, so a plain `if` divides by
    zero at an output size of 1.
    - A backend that keeps its data in the `.pte`, such as Metal, now
    refuses a `data_name` compile spec built by hand too, before compiling
    anything. Before, only `generate_data_name_compile_spec` refused it, and
    a hand-built spec was ignored with no name check.
    - The CUDA docs warn that Windows and macOS usually treat data names
    that differ only in case as the same file.

    ## Copies through a boolean mask no longer read the mask count back to
    the host

    `out[mask] = src[mask]` ran as a mask index and a mask `index_put`. Each
    of them read the mask's count back to the host and waited for the GPU,
    on every call. Transformers' SmolVLM vision embeddings do this for their
    position ids.

    When the values are the same mask's picks from a tensor shaped like the
    destination, every element goes back to where it came from. So a new
    pass in the CUDA backend writes the copy as `torch.where(mask, src,
    out)`, which gives the same result, bit for bit. It does so inside
    `torch.cond` branches and other subgraphs too. It rewrites only when
    `where` would lay out its result like the destination, since `where`
    takes its layout from its inputs, the mask first, while `index_put`
    keeps the destination's layout. It also drops the index and the checks
    on its size when nothing else reads them and each check tests only the
    index's count and holds for any mask. A user check on the count, such as
    `torch._check(x[mask].shape[0] >= 1)`, keeps the index. The pass
    compares the two masks with a work list, so masks with long histories do
    not hit Python's recursion limit. On an A100, five calls of the SmolVLM
    position id code went from 10 count reads and 10 stream waits to none.

    ## Tensor checks no longer stop the CUDA export

    The argument checks in `torch.distributions` export as
    `aten._assert_async.msg`. The CUDA backend compiled each one into a
    device assert inside a Triton kernel. While compiling, AOTInductor runs
    every kernel once to pick its launch settings, on made-up buffers:
    random floats, and zeros for integers and bools. So a check that reads a
    bool from an earlier kernel saw false and failed, even though it holds
    for every real input. The export then stopped with "device-side assert
    triggered". A Gaussian policy head, `MultivariateNormal(mean,
    scale_tril=...)` with 14 actions, hits this.

    A new pass in the CUDA backend now removes these checks before
    compiling, so the CUDA delegate no longer runs them. The rest of
    ExecuTorch already removes the same checks before a program is saved. A
    failed device assert could not come back as an error anyway: it breaks
    the CUDA context for the rest of the process. Checks on sizes
    (`_assert_scalar`) stay, since they run on the host.

    ## float64 weights load in the CUDA backend

    A program with a float64 weight lowered and saved, then failed to load
    with `Malformed CUDA FQN weight metadata`. This happened with a float64
    buffer, and with float64 math that constant propagation folds into one
    constant, such as a sinusoidal time embedding. The export wrote the
    weight correctly, but the runtime had no float64 dtype: the weight cache
    refused it, and the runtime's tensor type and dtype shims had none
    either.

    - The runtime's tensor type now has `Double`, with its 8 byte size. The
    same type wraps a method's inputs and outputs, so a float64 input or
    output works too.
    - The shims export `aoti_torch_dtype_float64`, which compiled code calls
    to name the dtype of a float64 constant.
    - The weight cache accepts `Double`, and uses 8 bytes when it checks
    that a weight fits its storage.
    - The shims that still refused float64 accept it: a float64 `.item()`
    (`aoti_torch_item_float64`, which did not exist, so the first execute
    ended the process), the single-element read those entry points share,
    `index_put` with accumulate, and the sort shim. A float16 `.item()` had
    the same problem with `aoti_torch_item_float16` and works now too.
    - A float read with `.item()` reached Triton kernels truncated to an
    integer, in float32 too, so a scale of 1.5 computed as 1 with no error.
    AOTInductor declares every symbolic argument of a kernel's launcher
    `int64_t`. A compile-time patch in the CUDA backend now declares it with
    the float type the kernel takes, the change that the open
    pytorch/pytorch#201882 makes in PyTorch.

    ## `aten._reshape_copy` lowers to the CUDA backend

    Torch-TensorRT turns `aten.view` into `aten._reshape_copy`. A view that
    TensorRT leaves to PyTorch reaches the CUDA backend in that form, and
    the export failed with `missing fallback kernels: aten::_reshape_copy`,
    since Inductor has no lowering for it and torch registers no
    decomposition. The CUDA backend now decomposes it the way ATen computes
    it: a contiguous copy, viewed to the new shape.

    ## `varlen_attn` lowers to the CUDA backend

    `torch.nn.attention.varlen.varlen_attn` runs attention over several
    sequences packed into one tensor. Lowering it failed with `missing
    fallback kernels: torch_attn::_varlen_attn`, since it calls Flash or
    cuDNN attention, which this backend does not ship. The CUDA backend now
    decomposes it into ops Inductor lowers: attention over all the packed
    tokens, with a mask that keeps each query in its own sequence. The
    output is contiguous, like the op's output for a query in the usual
    (tokens, heads, dim) order, so reshaping it before the output projection
    works.

    The decomposition matches the op for causal masks, sliding windows,
    grouped-query attention, and query and key sequences of different
    lengths. For a query sequence longer than `max_k + 1`, Flash attention 2
    (PyTorch's default) and Flash attention 3 give different results for
    some windows, because version 2 changes the window based on `max_k`. So
    a window other than `(left, 0)` lowers only when `max_q <= max_k + 1` is
    known at export time, as in self-attention, and raises a clear error
    otherwise. `seqused_k` and `block_table` (paged KV) raise a clear error
    too. It computes the weights with a softmax, which subtracts each row's
    largest score first, so the weights still add up to one when scores are
    large. Tokens before the first sequence or past the last one, such as
    the padding of a fixed-size buffer, do not change any sequence's output,
    even when they hold NaN. Unlike in Flash attention, a NaN or inf in one
    sequence's values does reach the other sequences. It holds a float32
    score per head for every pair of packed tokens and runs much slower than
    Flash attention, so it suits packs of a few thousand tokens, such as a
    few camera images.

    ## `scatter_reduce` with amax, amin, prod and mean lowers to the CUDA
    backend

    Lowering `x.scatter_reduce(dim, index, src, "amax")` failed with
    `missing fallback kernels: aoti_torch_cuda_scatter_reduce_two_out`, and
    so did "amin", "prod" and "mean". Inductor writes a scatter itself only
    when it can add atomically, and leaves the other reductions to an ATen
    kernel that this backend did not ship. A sum into int64 or bool, a sum
    into bfloat16 on GPUs older than sm_90, and deterministic mode use the
    same kernel.

    - A new shim next to the index shims implements it the way ATen does:
    `include_self`, elements the index does not name, the count and integer
    rounding of the mean, NaN in amax and amin, and bool for sum only. Half
    and bfloat16 sums add in float, as ATen does in deterministic mode. A
    product rounds to the tensor's dtype at every step and a mean rounds its
    sum before dividing, as ATen does, so half overflows and integers wrap
    where ATen's do. A mean also counts its terms in the tensor's dtype, as
    ATen does, so 128 int8 ones average to 1.
    - It sorts the writes by the element they land on and reduces each
    element's values in index order, so the result is deterministic. It also
    works inside a CUDA graph. The sort is now one helper that `index_put`
    uses too.
    - It is slower than ATen's atomic kernel: 1.5 to 3.2 times on an A100 at
    512 output rows, 4096 source rows and 1024 columns, and up to 7 times
    when many values land on few elements. A decomposition into ops Inductor
    lowers natively was measured first. It has to compare every output
    element with every source element, and it was 8 to 89 times slower than
    ATen's kernel.
    - `aoti_cuda_shims.lib` and the wheel's shared library check list the
    new shim. The import library now also lists the shims the DLL exported
    but it left out, such as `aoti_torch_dtype_float16` and the
    `aoti_torch_item_` getters, so a float16 model lowered for Windows
    links.

    ## CUDA programs load without torch on machines with no libgomp

    On Linux, Inductor adds OpenMP (`-fopenmp`, `-lgomp`) to every link.
    Unless the compiler passes `--as-needed` to the linker, as Ubuntu's GCC
    does by default, the compiled library lists `libgomp.so.1` as a
    dependency even when it calls no OpenMP function. PyTorch ships a
    libgomp, so this went unnoticed while torch was imported. A process
    without torch failed to load the program with `libgomp.so.1: cannot open
    shared object file` on any machine with no system libgomp, such as a
    minimal container.

    The CUDA backend now links with `-Wl,--as-needed`, so the linker keeps
    only the libraries the program uses. A program that does call OpenMP
    keeps libgomp. PyTorch already does the same for MPS builds on macOS,
    and pytorch/pytorch#202902 adds it to Inductor for Linux. The torch-free
    tests in `test_pybindings_cuda_dlpack.py` now run without a system
    libgomp, and the ones that check which libraries got loaded also check
    for libgomp. On an A100, a small MLP and CNN exported with this change
    load without torch and match eager where the loader cannot find libgomp.

    This patch, and the one that lets Triton templates run on GPUs with few
    SMs, now stay in place while any thread lowers. Before, when two threads
    lowered at once, the first one to finish removed the patch from the
    other, and the rest of that compile ran without it.

    ## A failed CUDA load no longer leaves its library in the temporary
    directory

    To load a method, the CUDA backend writes the program's compiled library
    to a temporary file, such as `/tmp/executorch_cuda_<pid>_0.so`. Only
    `destroy()` removed that file, and `destroy()` never runs when the load
    fails, so every load that failed after writing the file left it behind.
    A scope guard now removes the file unless the load succeeds.
    `test_missing_weights_blob.py` now checks that a load that fails for a
    missing weights blob leaves nothing in the temporary directory. Without
    the fix, that check fails.

    The XNNPACK high-rank permute fix moved to #24380.

    ## The Triton SDPA leaves keys past the end out of the softmax

    With `triton_kernel_mode` on (the default), the CUDA backend runs
    `scaled_dot_product_attention` as its Triton kernel, `triton::sdpa`. For
    power-of-two head sizes, its main kernel reads keys in tiles of 32, 64
    or 128. When the number of keys is not a multiple of the tile, the last
    tile reaches past the last key. The kernel loaded those positions as
    zeros but never removed them from the softmax, so without an attention
    mask or a causal mask each one got a score of 0 and took part of the
    attention weight. Calls that pass `kv_len` with neither a mask nor
    `is_causal`, such as the DFlash draft model's global attention layers,
    had the same problem. On an A100, with the query at 0 and the values at
    1, where the right output is 1, one key gave 0.031, 33 keys gave 0.516
    and 80 keys gave 0.625. With random inputs and one key, the output was
    off by 3.4 when the largest value was 3.67. All of these now match eager
    PyTorch.

    The kernel now gives every position past the last key, or past `kv_len`,
    a score of minus infinity, as the other attention kernels in `sdpa.py`
    already do. The first version of the kernel did this, and a later
    rewrite dropped it. Checking every tile cost up to 8% where no tile
    reaches past the end, so only calls that need the check pay for it. A
    mask or a causal bound already drops those keys, so calls with one skip
    it. The launcher also passes the largest tile size that divides the
    number of keys, and tiles that divide it skip the check at compile time.
    So calls with a mask or a causal bound, and tiles that divide a key
    count known at export time, compile to the same code as before. Without
    a mask or a causal bound, a `kv_len` or a symbolic key count checks
    every tile. `test_triton_sdpa.py` drops its note that called this a
    kernel limitation, runs its basic test with a single key, and runs every
    tile without a mask over 80 and 96 keys and over a `kv_len` of 80. These
    fail without the fix.

    ## `scatter` with a tensor source lowers to the CUDA backend

    Lowering `x.scatter(dim, index, src)` failed with a `missing fallback
    kernels` error that names `aoti_torch_cuda_scatter_src_out` when `src`
    is bfloat16, int64 or bool. Inductor writes a scatter from a tensor
    itself only in a dtype it can add atomically, so it leaves int64, bool
    and, on GPUs older than sm_90, bfloat16 to an ATen kernel, and every
    dtype in deterministic mode. A mixture-of-experts layer that writes its
    expert outputs back with `torch.zeros_like(h).scatter(1, index, src)` in
    bfloat16 hit this on an A100.

    A new shim next to the `scatter_reduce` one implements it with the same
    checks, the same sorting of the writes by the element they land on, and
    the same kernel. The kernel gets a new mode in which only the last write
    to each element stores its value. So when values land on the same
    element, the last one in index order wins, as ATen does in deterministic
    mode; ATen's default CUDA kernel keeps any one of them. As in that
    default kernel, an index out of range, negative ones included, triggers
    a device-side assert. In deterministic mode, ATen's scatter counts a
    negative index from the end instead. The shim takes float, double, half,
    bfloat16, the integer dtypes and bool. Like ATen, both scatter shims now
    take an int32 index as well as an int64 one. Mostly because of the sort,
    the shim is about 10 to 15 times slower than ATen's default kernel for a
    mixture-of-experts style bfloat16 scatter of 4 to 34 million values on
    an A100. The Windows import library `aoti_cuda_shims.lib` and the
    wheel's shared library check now list the new shim. On an A100 with
    PyTorch 2.14 and 2.15, scatters in float32, float16, bfloat16, int64 and
    bool lower, run and match eager PyTorch exactly. So does a small
    mixture-of-experts layer built the same way.
    `test_scatter_with_tensor_source` fails without the fix, and its int32
    index case fails when the shims take only int64.

    ## Review order

    Start with the CUDA graph changes: `cuda_backend.cpp` and
    `cuda_delegate_handle.h` in `backends/cuda/runtime`, the mask and
    `.item()` shims in `runtime/shims/index.cu` and `memory.cpp`, and their
    tests in `test_output_stride_rearrange.py`. Then the lowering side: the
    passes in `backends/cuda/passes`, the decompositions and compile-time
    patches in `backends/cuda/cuda_backend.py`, and the folding switch in
    `backends/aoti/aoti_backend.py`. Then the scatter and scatter_reduce
    shims in `index.cu` with `test_index_shims.py`. The remaining commits
    are small follow-ups that stand on their own.

    ## Testing

    On an A100, with the CUDA backend built from this branch:

    - `test_index_shims.py`, `test_output_stride_rearrange.py`,
    `test_cuda_export.py`, `test_antialiased_resize.py`,
    `test_merge_ptes.py` and `test_cuda_weight_metadata.py` pass.
    - With the backend built from main, the new CUDA graph tests fail.
    - The replay error names the dim, for example "input 0 has size 4 in dim
    1, captured with 3".
    - `test_cuda_kv_cache` passes, and fails when `release()` keeps the
    captured input shapes.
    - With the min and max replaced by a plain `if`,
    `test_bicubic_antialias_resize` fails.
    - With the new data name refusal removed, or moved back behind the
    compile, the data name test fails.
    - A `torch.cond` on a host-memory flag matches eager on every call; with
    a graph it returned the captured branch.
    - A random program run from two processes started together drew the same
    numbers in 2 of 3 tries before the seed change, and different ones in 3
    of 3 after.
    - Mask index programs exported from this branch match eager PyTorch on
    every call, both on a runtime built from main with CUDA graphs off and
    on this branch's runtime with CUDA graphs on.
    - The shared shim unit tests pass in a standalone googletest build.
    - `test_replace_masked_copy_with_where.py` passes, and fails when the
    pass does nothing, is not registered, or skips its accumulate,
    same-mask, boolean mask, shared picks or count check. It writes into a
    destination filled with 7, so it fails if `where` loses the values the
    mask does not pick. A contiguous destination with a channels_last
    source, or with a channels_last mask, keeps its `index_put`; before, the
    rewrite failed to lower when a later `view(-1)` needed the destination's
    layout. It also fails when the pass walks only the top-level graph,
    since a masked copy in a `torch.cond` branch then keeps its index, and
    when it takes two draws of a random mask for the same mask. Two masks
    computed with over a thousand ops each raised RecursionError before. A
    check that reads the index's count but tests another size keeps the
    index; before, the pass removed it.
    - A masked copy lowered through the CUDA partitioner matches eager for
    masks that pick some, none and all positions. The test records the graph
    the pass returns, and fails when the pass is not registered or leaves
    the index in place.
    - A module that adds one to a device buffer on every call and reads a
    mask's count returns the call number on every call, so the capture call
    that runs again without a graph updates the buffer once. With the retry
    made to run the call twice, the capture call returns one too many. With
    PyTorch 2.14 it returned one on every call even without a graph, because
    Inductor folded the written buffer into a fill; it passes now with 2.14
    and with 2.15 and 2.16 nightlies.
    - On the tiny Gemma 4 decoder from the Gemma 4 31B example's tests,
    which writes a KV cache, with PyTorch 2.14 on an A100: with the folding
    off, export took 193 s against 190.5 s with it on, a decode call took
    945 µs against 1019 µs (medians of three exports and three runs on a
    busy machine), and the 41 generated tokens were the same.
    - The mask tests check that the runtime log reports one failed capture,
    so they fail when CUDA graphs are off or a failed capture is tried
    again. `test_host_read_runs_without_a_graph` also runs a module that
    scales by a `.item()` read; without the capture check in the item shims,
    the process aborts.
    - With the debug check on the phase before the retry turned into a
    release check, the mask tests pass.
    - `test_distribution_argument_check` passes with PyTorch 2.14 and fails
    with "device-side assert triggered" without the new pass. It also checks
    that the backend lists the pass, since without the pass the export fails
    only when autotuning happens to trip the assert. It writes the
    `MultivariateNormal` check as `torch._assert_async`, since PyTorch 2.14
    cannot export the distribution itself. It also checks that the pass
    drops the check and the math that only fed it. A Gaussian policy head
    with hidden sizes 16, 64 and 256 exports, runs, and matches eager
    PyTorch.
    - A float64 buffer and a folded float64 constant load and match eager
    PyTorch. Before, both failed to load. `test_float64_weight_loads` fails
    without the fix.
    - `test_reshape_copy` in `test_cuda_export.py` fails without the fix.
    The one in `test_index_shims.py` runs `_reshape_copy` on a transposed, a
    sliced and a contiguous input and matches eager PyTorch.
    - `test_varlen_attn` in `test_cuda_export.py` fails without the fix. It
    lowers a program that flattens the output, compares the decomposition
    with the op on CUDA only (on ROCm, varlen_attn runs AOTriton, which
    lines an explicit window up with the start of each sequence, while the
    decomposition follows Flash attention on CUDA, which lines it up with
    the end), including a window in self-attention and NaN values outside
    the key sequences, and checks that a window the Flash attention versions
    disagree on raises. It also fails when the output is left
    non-contiguous, when the window check is removed or refuses every such
    window, and when the values outside the key sequences are not zeroed.
    Both `test_varlen_attn` tests include queries and keys filled with 1024,
    where every key gets the same weight; computing the weights as
    `exp(scores - logsumexp)` fails them, since at that size float32 rounds
    the log-sum-exp to a whole number and the weights no longer add up to
    one. The `test_varlen_attn` in `test_index_shims.py` lowers and runs
    programs that call `varlen_attn` with no window, a causal mask and the
    windows (8, 0) and (4, 2), flatten each output, and take `cu_seq_q` and
    `cu_seq_k` only at run time. They match eager PyTorch.
    - `test_missing_weights_blob.py`, `test_cuda_weight_reuse.py` and
    `test_device_placement.py` pass.
    - `test_scatter_reduce` now runs the sum too, which for int64 goes to
    the new shim. The test that a missing scatter kernel fails at export now
    tries to lower a scatter of a scalar in deterministic mode. The backend
    still lacks that kernel, so the test still checks the scatter fallback
    now that the scatter_reduce and scatter shims exist. It fails when the
    check stops watching that fallback.
    `test_scatter_mean_counts_in_its_dtype` fails with the old count and
    when a count that wraps to zero is not turned into one.
    `test_float64_and_float16_values` (a sort and `.item()` in each dtype)
    and the float64 masked accumulate fail with the old shims, and all pass
    now. The `.item()` scale is 1.5, so that test also fails without the
    patch that passes a float to Triton kernels as a float.
    - `test_scatter_reduce` and `test_sort_shim.py` pass.
    `test_scatter_reduce` fails without the fix, and also when the shim
    ignores `include_self`, rounds the integer mean toward zero, or lets a
    NaN lose in amax and amin. `test_scatter_strides` scatters along the
    middle dim of a 3-D tensor, given as a negative dim, from a strided
    source and from transposed operands, and fails when the shims walk only
    the last two dims. `test_scatter_reduce_edge_cases` covers a bool sum,
    int32 and half products that wrap and overflow, and an empty index.
    `test_scatter_reduce_sum_adds_in_float` sums 1000 half and bfloat16
    values in deterministic mode, and fails when the sum rounds to the dtype
    at every step. `test_scatter_reduce_replays_in_a_graph` captures a
    `scatter_reduce` program in a CUDA graph and matches eager on every
    replay.
    - The weight cache, runtime tensor and shim unit tests pass in a
    standalone googletest build. Without the fix, the weight cache test of a
    float64 entry fails.

    - `test_small_gpu_override_survives_a_thread_that_leaves_first` overlaps
    two threads inside the small-GPU patch, and fails with the old save and
    restore.

    - With the seed copy made to fail once, the random shim logs it, fails
    that call, and seeds on the next one; before, it went on with an
    unseeded state.

    Not tested: a failed first graph launch (it cannot be triggered from a
    test), a `std::random_device` that throws, Windows, macOS
    case-insensitive file systems, the buffer folding change on Metal, and
    the ROCm build. No test covers the seed change, since a test cannot make
    two processes start in the same second.

    ### Checked on real robot policies

    On the release/1.6 stack with this change, on A100 and H100:
    - SmolVLA on the CUDA backend: one device-to-host copy per action chunk
    (only the action download), matching eager within the usual tolerance.
    - A Gaussian policy whose `torch.distributions` check used to stop the
    CUDA export: exports and runs, 0.76 ms per chunk.
    - A float64 weight that used to fail at load with "Malformed CUDA FQN
    weight metadata": loads and runs, max difference 0.
    - Four processes started together: four different random draws, against
    two out of four before.

    ---------

    Co-authored-by: Anthony Shoumikhin <anthony@shoumikh.in>
    Co-authored-by: Anthony Shoumikhin <shoumikhin@meta.com>

commit 7c905611a44158d704d583a1d9b12d55737d8a65
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 10:02:57 2026 -0800

    [release/1.6] Suppress AMD export complexity lint inline (#24511)

    Fixes the release branch [Lint
    failure](https://github.com/pytorch/executorch/actions/runs/41681451895):
    `examples/cuda/scripts/export_amd_pointwise.py` fails Flake8 C901
    because `main` has complexity 13, above the repository limit of 12.

    As requested, add only `# noqa: C901` to the existing `main` definition.
    The earlier refactor is removed; the original script logic, ROCm
    settings and validation checks are restored. All other lint checks
    remain active.

    ## Verification

    The repository-configured Flake8 check passes. AST comparison verifies
    that the entire script is identical to the release baseline apart from
    the comment.

    The final PR diff changes one line in one file. Full ROCm export was not
    run locally on macOS; no executable code changes.

    Prepared with OpenAI Codex.

commit 0a01e1be061f1a6db8560d30a1406d4e9a640703
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:37:09 2026 -0800

    [release/1.6] Fix NXP MCUXpresso CIFAR link failure (#24509)

    Fixes the NXP MCUXpresso failure seen on #24490 and on the release
    branch.

    The [failed
    job](https://github.com/pytorch/executorch/actions/runs/41601038988/job/125799646998)
    reaches the final CIFAR firmware link, then fails with `undefined
    reference to SYS_INFO_PrintAll`. The SDK example calls this helper, but
    our standalone CMake target omits
    `examples/eiq_examples/common/sys_info/sys_info.c`.

    Add that source to the firmware target. The helper also needs
    `MCUXSDK_VERSION_FULL_STR`, which the SDK's normal build supplies
    through a generated header. Our standalone target now uses the SDK's
    `mcux_version.cmake` parser and sets the equivalent compile definition
    from the checked-out SDK version.

    ## Verification

    A focused host CMake build reused the actual example target's source
    list and include paths, the real SDK helper/header, and the SDK version
    parser. The board/runtime sources were replaced with empty fixtures and
    the application with a small C++ caller.

    The original source list reproduced the unresolved `SYS_INFO_PrintAll`
    link error. Adding only the helper reproduced the missing
    `MCUXSDK_VERSION_FULL_STR` compile error. With both changes, the
    executable linked and printed `MCUX SDK version: 2026.12.00-pvw1`.

    `git diff --check` passed. The full ARM firmware build and execution on
    hardware were not run locally; the NXP CI job must validate the complete
    build.

    Only the example's CMakeLists.txt changes (eight added lines). Based on
    release/1.6 after #24490; this PR can land independently of the
    remaining clean backend picks.

    Prepared with OpenAI Codex.

commit 39352871e553fc3b1b565dd2ed8639546710fc13
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:09:25 2026 -0800

    [release/1.6] Add portable antialiased bicubic resize (#24494)

    Supersedes #24447 with a clean release pick from #24400.

    Adds the portable antialiased bicubic kernel, edge-verifier exception,
    registration/build wiring, regression tests and matching Arm
    recipe/documentation updates from the source PR.

    Changes exactly the 15 source PR paths.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24493 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 15
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

    cc @digantdesai @freddan80 @per @zingo @oscarandersson8218 @mansnils
    @Sebastian-Larsson @robell @rascani

commit 986c76fb0863e539f6ccd5a0cb625ff7e8eaa830
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:05:04 2026 -0800

    [release/1.6] Fix OpenVINO bool operations and masked reads (#24493)

    Supersedes #24446 with a clean release pick from #24396.

    Keeps unsupported bool-only min/max/clamp/sign operations on the CPU and
    populates tensor metadata for masked-read lowering. Includes their
    regression tests.

    The bool test class is moved unchanged to test_bool_min_max.py so this
    PR can be based directly on release/1.6 without carrying the core
    OpenVINO commit.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24492 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 4
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed. The combined OpenVINO
    production code matches the previously reviewed final #24446 code; the
    bool test class is preserved unchanged.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

commit 0b72572b56c40c9449ded97339929c6cfe023914
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:04:56 2026 -0800

    [release/1.6] Fix OpenVINO scalars, precision, dynamic outputs and reductions (#24492)

    Supersedes #24377 with a clean release pick from #24294.

    Fixes scalar tensors, float32 CPU defaults, dynamic output buffers and
    integer reductions. Includes the related #24396 runtime, folded-cumsum,
    parameter-count and CI runner follow-ups previously spread across #24377
    and #24446.

    This pick contains the complete core OpenVINO fix and its required
    follow-ups. Bool-op handling and masked-read metadata are isolated in
    the next clean pick. The source float32 default can cost speed on CPUs
    with bfloat16 hardware; inference_precision=bf16 remains available.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24491 in the
    verified landing order. The OpenVINO pair follows the CUDA picks; these
    backend groups can otherwise be reviewed separately.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 16
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed. The combined OpenVINO
    production code matches the previously reviewed final #24446 code; the
    bool test class is preserved unchanged.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

commit 5253dfaccfdb312d96e15d739d1ae1abfb507732
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:04:44 2026 -0800

    [release/1.6] Lower fused CUDA attention variants (#24491)

    Supersedes #24455 with a clean release pick from #24426.

    Restores inference-only fused flash, efficient and cuDNN attention calls
    to scaled_dot_product_attention when the source pass can preserve their
    semantics.

    The fused-attention test is moved unchanged to avoid conflicts with the
    earlier indexing pick. The existing release missing-kernel regression
    test is retained.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24490 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 5
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed. The existing CPU
    graph rewrite test passed its nine cases using the real inherited
    AotiPartitioner implementation. The GPU import/pass-registration test
    could not run locally because Triton is unavailable on macOS.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

commit f3a9b06f548f27359d95a106a825d7b7fe3e39da
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:04:24 2026 -0800

    [release/1.6] Delete duplicate CUDA output handles once (#24490)

    Supersedes #24448 with a clean release pick from #24420.

    Deletes each aliased CUDA output handle once, including error cleanup,
    and carries its regression test.

    The original three source files are the complete scope of this pick.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24489 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 3
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
    simulated squash merges. No QNN files are changed.

    Native CUDA, OpenVINO and portable C++ suites were not run locally on
    this macOS host; PR CI remains required before landing.

    Prepared with OpenAI Codex.

commit 1f49f64b0026413a38671e1918536e1a17b3d50d
Author: Jacob Szwejbka <jakeszwe@meta.com>
Date:   Tue Nov 3 09:03:48 2026 -0800

    [release/1.6] Fix CUDA weights filenames and antialiased resize (#24489)

    Supersedes #24324 with a clean release pick from #24314.

    Adds validated per-program CUDA weights filenames and lowerings for
    antialiased bilinear/bicubic resize. Retains the data-name validation,
    resize-test removal and documentation follow-ups already carried by
    #24324.

    Preserves the release behavior that mismatched CUDA weights fail to
    load. The resize rewrite follows the source PR tolerances rather than
    promising bit-identical floating-point results.

    ## Scope and landing order

    Land after https://github.com/pytorch/executorch/pull/24488 in the
    verified landing order.

    This branch starts directly at release/1.6 commit
    `dfb78b9ecd933a5fee33ebc94f69ed4b71cbb1e7`. Its GitHub diff contains 10
    files for this pick; it does not carry duplicate #24298 history or the
    excluded unmerged QNN work. Dependencies are documented here rather than
    embedded as other cherry-pick commits.

    ## Verification

    All changed Python files compile and pass Ruff F821 checks. All seven
    replacements merge cleanly in the documented sequence, including
   …
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. release notes: xnnpack Changes to the XNNPack backend delegate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants