Skip to content

[exir] Add pow to executorch_prim - #25768

Open
themanoj-025 wants to merge 5 commits into
pytorch:mainfrom
themanoj-025:fix-sym-pow-emitter
Open

themanoj-025 wants to merge 5 commits into
pytorch:mainfrom
themanoj-025:fix-sym-pow-emitter

Conversation

@themanoj-025

@themanoj-025 themanoj-025 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #25767
Part of huggingface/transformers#51303

When exporting models with dynamic shapes where a SymInt is raised to an integer power (e.g. x.shape[0] ** 2 in SeamlessM4T's relative positional bias calculation), lowering fails with:

executorch.exir.error.InternalError: Failed with error: invalid target for call_function <built-in function pow>

Because executorch_prim does not define a pow kernel, operator.pow remained an invalid target during emission. This PR adds it.

Test plan

  1. Verified locally against the minimal reproduction script in [exir] operator.pow on a SymInt has no emitter target #25767:
import torch
from executorch.exir import to_edge_transform_and_lower

class M(torch.nn.Module):
    def forward(self, x):
        return x.new_zeros(x.shape[0] ** 2)

ep = torch.export.export(M(), (torch.randn(4),), dynamic_shapes=({0: torch.export.Dim.AUTO},))
to_edge_transform_and_lower(ep).to_executorch()
  1. Added unit test test_edge_to_backend_sym_pow in exir/tests/test_passes.py.

cc @nil-is-all

…ToBackendOpsPass

When exporting models with dynamic shapes where a SymInt is raised to an integer power (e.g. SeamlessM4T's relative position bias calculation x.shape[0] ** 2), to_executorch() fails with:
executorch.exir.error.InternalError: Failed with error: invalid target for call_function <built-in function pow>

Because executorch_prim does not have a pow operator, this commit rewrites operator.pow(base, exp) for non-negative integer exponents into a scalar multiplication chain using _PYTHON_SYM_OPS_TO_EXECUTORCH_SYM_OPS[operator.mul].

Tracked in huggingface/transformers#51303 (Item 1).
@pytorch-bot

pytorch-bot Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 5 New Failures, 5 Pending, 1 Unrelated Failure, 3 Unclassified Failures

As of commit 3cf8ea8 with merge base ddb19ca (image):

NEW FAILURES - The following jobs have failed:

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@meta-cla

meta-cla Bot commented Nov 27, 2026

Copy link
Copy Markdown

Hi @themanoj-025!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks!

@linux-foundation-easycla

linux-foundation-easycla Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

CLA Signed
The committers listed above are authorized under a signed CLA.

@themanoj-025

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: none"

@pytorch-bot pytorch-bot Bot added the release notes: none Do not include this in the release notes label Nov 27, 2026
@meta-cla

meta-cla Bot commented Nov 27, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 27, 2026
@executorch-triage executorch-triage Bot added the community: contribution PRs coming from community (excluding hardware partners) label Nov 27, 2026

@JacobSzwejbka JacobSzwejbka 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.

@JakeStevens JakeStevens 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.

please also update the PR title/summary to match the new approach, we are not using a mul chain

return a / b # pyre-ignore


@bind_pattern_to_op(executorch_prims_lib, "pow.Scalar(Scalar a, Scalar b) -> Scalar")

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.

Could you also add operator.pow: ops.backend.executorch_prim.pow.Scalar to _PYTHON_SYM_OPS_TO_EXECUTORCH_SYM_OPS? EdgeToBackendOpsPass uses that map to rewrite FX targets. On the pinned PyTorch nightly, the new test still raises invalid target for call_function <built-in function pow>. Adding that entry made the same model emit executorch_prim::pow.Scalar.

Comment thread kernels/prim_ops/register_prim_ops.cpp Outdated
Kernel(
"executorch_prim::pow.Scalar",
[](KernelRuntimeContext& context, Span<EValue*> stack) {
ET_UNUSED(context);

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.

Please replace this line with __ET_PRIM_OP_NUM_ARGS_CHECK_IMPL(stack, context) before indexing stack. ET_UNUSED expands to [[maybe_unused]], which Clang rejects here. The existing arity check also returns InvalidProgram if the call is missing an operand or the output slot.

Comment thread kernels/prim_ops/register_prim_ops.cpp Outdated
int64_t base = a.toInt();
int64_t exp = b.toInt();
if (exp >= 0) {
out = EValue(static_cast<int64_t>(std::pow(base, exp)));

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.

Please use checked integer exponentiation for nonnegative integer exponents. 3 ** 34 fits in int64_t and equals 16677181699666569. This expression returned 16677181699666570 locally because std::pow rounds through double. A kernel test with (3, 34) would catch the precision loss.

Comment thread kernels/prim_ops/register_prim_ops.cpp Outdated
}
} else {
double base = a.isInt() ? static_cast<double>(a.toInt()) : a.toDouble();
double exp = b.isInt() ? static_cast<double>(b.toInt()) : b.toDouble();

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.

x.shape[0] ** True emits a Bool exponent once the lowering map is wired up. This branch calls toDouble() on that value, which aborts on the tag check. Please handle Boolean operands as integers on either side and return InvalidType through context for unsupported tags.

} else {
double base = a.isInt() ? static_cast<double>(a.toInt()) : a.toDouble();
double exp = b.isInt() ? static_cast<double>(b.toInt()) : b.toDouble();
out = EValue(std::pow(base, exp));

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.

At input length 3, (x.shape[0] - 3) ** -1 raises ZeroDivisionError in the exported PyTorch model. Here std::pow(0.0, -1.0) returns infinity and the kernel reports success. Please return InvalidArgument for a zero base and negative exponent in both floating-result paths.

Comment thread exir/tests/test_passes.py
M(), (torch.randn(4),), dynamic_shapes=({0: torch.export.Dim.AUTO},)
)
new_prog = to_edge(ep).to_executorch()
self.assertIsNotNone(new_prog)

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.

Could you run the emitted program at a second input length? For example, bound the dynamic dimension at 4, export at length 4, then run the portable runtime at length 3 and assert the output shape is (9,). That exercises the C++ registration and catches a result frozen to the example shape.

themanoj-025 and others added 2 commits December 5, 2026 00:45
Check the accumulator product and repeated squaring so an overflowing symbolic shape calculation returns InvalidArgument. Cover each multiplication path in the kernel test.

Authored with assistance from OpenAI Codex.
@JakeStevens JakeStevens changed the title [exir] Rewrite operator.pow on SymInt to multiplication chain in EdgeToBackendOpsPass [exir] Add pow to executorch_prim Dec 5, 2026
Authored with assistance from OpenAI Codex.

This branch has not been deployed

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

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. community: contribution PRs coming from community (excluding hardware partners) release notes: none Do not include this in the release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[exir] operator.pow on a SymInt has no emitter target

3 participants