Skip to content

Use METH_FASTCALL for Inductor C++ Python bindings - #192287

Closed
lakshayg wants to merge 1 commit into
pytorch:mainfrom
lakshayg:inductor-fastcall
Closed

lakshayg wants to merge 1 commit into
pytorch:mainfrom
lakshayg:inductor-fastcall

Conversation

@lakshayg

@lakshayg lakshayg commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

This PR reduces the Python overhead for inductor generated python
bindings by replacing METH_VARARGS with METH_FASTCALL.

I used Codex to create a benchmark for Python bindings generated by
CppPythonBindingsCodeCache.load_pybinding it shows a consistent
reduction of 40-50% reduction in execution times of no-op kernels with
differing number of params and types.

Related-to: #49476

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

@pytorch-bot

pytorch-bot Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

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

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

@lakshayg lakshayg added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 6, 2026
@lakshayg
lakshayg force-pushed the inductor-fastcall branch from b9ac375 to febcac6 Compare August 6, 2026 20:41
@lakshayg
lakshayg marked this pull request as ready for review August 6, 2026 20:42
@lakshayg lakshayg added ciflow/trunk Trigger trunk jobs on your pull request and removed ciflow/trunk Trigger trunk jobs on your pull request labels Aug 6, 2026
@lakshayg lakshayg self-assigned this Aug 6, 2026
@lakshayg

lakshayg commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchmergebot rebase

@jansel

jansel commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@lakshayg

lakshayg commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchmergebot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased inductor-fastcall onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout inductor-fastcall && git pull --rebase)

@lakshayg

lakshayg commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review these changes

@claude

claude Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Claude finished @lakshayg's task in 21m 0s —— View job


Reviewed the METH_VARARGS → METH_FASTCALL conversion — the change is correct as written; I have three non-blocking notes (a style/line-budget nit, a latent footgun if METH_KEYWORDS is ever added, and missing test coverage).

Detailed review of #192287

Checklist

  • Gather context (diff, template, all call sites)
  • Verify METH_FASTCALL signature/cast correctness
  • Verify all callers are positional-only
  • Check reference-lifetime and error-path semantics
  • Check Python version floor and linter budget
  • Post review

Verdict

The core change is correct. Specifically, I verified:

1. Signature matches the protocol. torch/_inductor/codecache.py:4091 uses PyObject* {entry_func}_py(PyObject* self, PyObject* const* args, Py_ssize_t nargs), which is exactly _PyCFunctionFast. Good.

2. nargs needs no PyVectorcall_NARGS. For plain METH_FASTCALL, CPython's cfunction_vectorcall_FASTCALL already applies PyVectorcall_NARGS(nargsf) before invoking the method, so the raw nargs at line 4093 is the true positional count. The bare nargs != {arg_len} check is right.

3. Dropping the PyTuple_CheckExact / PyTuple_GET_SIZE guard is correct, not a lost safety check — there is no tuple to validate under the fastcall convention, and arity is still enforced.

4. The double cast is the right idiom here, not a workaround to replace. reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(...)) at line 4108 is what GCC/Clang documents for silencing -Wcast-function-type, and it matches castPyCFunctionFast in torch/csrc/utils/pycfunction_helpers.h. Worth stating explicitly for future readers: you cannot simplify this to CPython's _PyCFunction_CAST(...), because that macro only landed in 3.11 and pyproject.toml:348 still declares requires-python = ">=3.10". And you can't include the PyTorch helper header, since cpp_compile_command_flags sets include_pytorch: False for this cache precisely to avoid the slow headers (see the comment at line 4062). So hand-rolling it is correct.

5. Reference lifetime is safe. Under METH_VARARGS the args tuple held strong refs for the call duration; under METH_FASTCALL the array holds borrowed refs owned by the caller's frame. That's fine here because parse_arg consumes each element immediately (extracting a data_ptr, Py_ssize_t, double, or capsule pointer) and nothing stashes a PyObject* beyond the call. The std::vector<AtenTensorHandle> specialization at line 4308 also copies out raw handles before returning.

6. All call sites are positional-only, so the loss of **kwargs support is a non-issue. I traced every path:

  • torch/_inductor/codegen/wrapper.py:3782 (wrap_kernel_call) — positional join, reached for CPU/MPS at wrapper.py:4006/4009
  • torch/_inductor/codegen/cpp_wrapper_cpu.py:1831 — f(input_handles), single positional arg
  • torch/_inductor/graph.py:2970 — compiled_fn(input_handles)
  • Halide: torch/_inductor/codegen/halide.py:1836 appends stream_name positionally, matching the extra uintptr_t appended to binding_types at codecache.py:4619

Note the load_pybinding(argtypes=..., main_code=...) kwargs at cpp_wrapper_cpu.py:1742 and graph.py:2830 are Python-side classmethod kwargs, not calls into the C binding — unaffected.

Suggestions (all non-blocking)

a) Collapse the PyMethodDef entry back onto one line. The 6-line reformat at lines 4106-4111 pushes CppPythonBindingsCodeCache from ~203 to ~206 lines, and tools/linter/adapters/docstring_linter-grandfather.json:30 pins it at 191 with a 10% tolerance (TOLERANCE_PERCENT = 10 in docstring_linter.py:27) — an effective ceiling of 210. That leaves only ~4 lines of headroom for the next person to touch this class. Since this is generated C++ with no column limit, a single line costs nothing and also matches the repo style guidance about not splitting for the sake of splitting:

{{"{entry_func}", reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>({entry_func}_py)), METH_FASTCALL, ""}},

Fix this →

b) Consider a one-line comment on the nargs check. The correctness of reading nargs directly is a real but non-obvious invariant: it holds only for plain METH_FASTCALL. If anyone later adds METH_KEYWORDS to get kwarg support, line 4093 becomes silently wrong (the high PY_VECTORCALL_ARGUMENTS_OFFSET bit would leak in and the arity check would spuriously fail), and the bug would surface as a confusing requires N args error. This is the kind of hidden constraint that earns a comment:

// Plain METH_FASTCALL: CPython already applied PyVectorcall_NARGS, so nargs is exact.
// Adding METH_KEYWORDS would require unpacking it here.

c) No test covers the new binding shape. test/inductor/test_codecache.py:494-505 already asserts on the generated source (assertIn("Py_NewRef(Py_None)", generated_source)), so an assertIn("METH_FASTCALL", generated_source) there is nearly free and would catch an accidental revert. A functional arity test (calling a loaded binding with the wrong number of args and asserting RuntimeError) would be stronger, since that's the one runtime behavior this diff rewrites.

Minor behavioral note (no action needed)

Calling a kernel with keyword arguments previously fell through to the generic METH_VARARGS handling; now CPython raises TypeError: kernel() takes no keyword arguments before your code runs. Since nothing in the codebase calls these bindings with kwargs (verified above), and the arity RuntimeError message is unchanged, this is harmless.

Things I could not verify

I did not build PyTorch or run the inductor test suite in this environment, so I have not empirically confirmed the 40-50% speedup or compiled the generated C++ on all supported compilers. CI on the PR is currently green (40 pending, no failures) per Dr. CI. The claimed win is plausible on its face: this removes a tuple allocation plus per-arg PyTuple_GET_ITEM indirection from every kernel invocation, which is exactly where no-op-kernel benchmarks spend their time.

| Branch: `inductor-fastcall`

@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 10, 2026
@zou3519
zou3519 requested review from aorenste and eellison August 10, 2026 03:40

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

(Reviewed by me, assisted by AI)

[cleanup] My agent says: the 40-50% number is the entire justification for this change, but the benchmark isn't committed and the description carries no absolute numbers, so nobody can re-measure it or catch a later regression against it. Worth pasting the benchmark script and a before/after table into the description, and saying explicitly that this is dispatch overhead on no-op kernels (best case) rather than an end-to-end win.

@@ -4105,7 +4103,12 @@ def cache_clear() -> None:
}}

static PyMethodDef py_methods[] = {{

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.

[cleanup] My agent says: the double reinterpret_cast type-checks nothing, so a later signature edit compiles clean and only breaks at runtime -- a static_assert above py_methods turns the METH_KEYWORDS footgun from a comment into a build error:

static_assert(std::is_same_v<decltype(&{entry_func}_py), PyObject* (*)(PyObject*, PyObject* const*, Py_ssize_t)>,
              "{entry_func}_py must match the METH_FASTCALL signature");

Checked against CPython 3.10 headers at -Wall -std=c++20: adding a PyObject* kwnames parameter to {entry_func}_py still builds today, and fails to compile with the assert in place.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

pytorch/torch/csrc/Module.cpp

Lines 2374 to 2376 in 2760264

{"_has_torch_function_variadic",
reinterpret_cast<PyCFunction>(
reinterpret_cast<void (*)()>(THPModule_has_torch_function_variadic)),

inline PyCFunction castPyCFunctionFast(PyCFunctionFast func) {
C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wcast-function-type")
C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wcast-function-type-strict")
return reinterpret_cast<PyCFunction>(func);
C10_DIAGNOSTIC_POP()
C10_DIAGNOSTIC_POP()
}

The double reinterpret_cast approach seems to be the standard way of doing this.

@lakshayg

Copy link
Copy Markdown
Collaborator Author

@aorenste here are the numbers and the benchmarking script

Scenario after before
kernel() 12.8 ns 25.3 ns
kernel(a, b, c, d) 26.4 ns 54.1 ns
kernel(A, B, C, D) 41.1 ns 71.7 ns
kernel(A, B, C, D, a, b, c, d) 54.3 ns 89.7 ns
  • kernel is a no-op kernel
  • lowercase represents integer, uppercase represents tensor.
#!/usr/bin/env python3

"""Microbenchmark Inductor's generated C++ Python binding call overhead."""

import argparse

import torch
from torch._inductor.codecache import CppPythonBindingsCodeCache
from torch.utils.benchmark import Timer


def make_binding(argtypes):
    parameters = ", ".join(argtypes)
    source = f'extern "C" void kernel({parameters}) {{}}'
    return CppPythonBindingsCodeCache.load_pybinding(argtypes, source)


def benchmark(name, statement, namespace, min_run_time):
    measurement = Timer(stmt=statement, globals=namespace).blocked_autorange(
        min_run_time=min_run_time
    )
    print(
        f"{name:<24} {measurement.median * 1e9:8.1f} ns "
        f"(IQR {measurement.iqr * 1e9:.1f} ns)"
    )


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--min-run-time", type=float, default=10.0)
    args = parser.parse_args()

    tensors = {f"x{index}": torch.ones(1) for index in range(4)}
    print(f"PyTorch build: {torch.version.git_version}")
    benchmark(
        "no arguments",
        "op()",
        {"op": make_binding([])},
        args.min_run_time,
    )
    benchmark(
        "four integers",
        "op(1, 2, 3, 4)",
        {"op": make_binding(["int64_t"] * 4)},
        args.min_run_time,
    )
    benchmark(
        "four tensors",
        "op(x0, x1, x2, x3)",
        {"op": make_binding(["float*"] * 4), **tensors},
        args.min_run_time,
    )
    benchmark(
        "tensors and integers",
        "op(x0, x1, x2, x3, 1, 2, 3, 4)",
        {"op": make_binding(["float*"] * 4 + ["int64_t"] * 4), **tensors},
        args.min_run_time,
    )


if __name__ == "__main__":
    main()

@lakshayg

Copy link
Copy Markdown
Collaborator Author

@aorenste is this good to merge or do you have more suggestions?

@aorenste

Copy link
Copy Markdown
Contributor

@lakshayg I already approved - so good to merge.

@lakshayg

Copy link
Copy Markdown
Collaborator Author

@pytorchmergebot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@lakshayg
lakshayg deleted the inductor-fastcall branch August 12, 2026 20:25
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
This PR reduces the Python overhead for inductor generated python
bindings by replacing `METH_VARARGS` with `METH_FASTCALL`.

I used Codex to create a benchmark for Python bindings generated by
`CppPythonBindingsCodeCache.load_pybinding` it shows a consistent
reduction of 40-50% reduction in execution times of no-op kernels with
differing number of params and types.

Related-to: pytorch#49476

Pull Request resolved: pytorch#192287
Approved by: https://github.com/aorenste
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source release notes: inductor triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants