Repository navigation
Conversation
🔗 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 FailuresAs of commit 7867cbf with merge base b0eccff ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
b9ac375 to
febcac6
Compare
|
@pytorchmergebot rebase |
|
@claude review these changes |
|
@pytorchmergebot rebase |
|
@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here |
|
Successfully rebased |
febcac6 to
7867cbf
Compare
|
@claude review these changes |
|
Claude finished @lakshayg's task in 21m 0s —— View job Reviewed the Detailed review of #192287Checklist
VerdictThe core change is correct. Specifically, I verified: 1. Signature matches the protocol. 2. 3. Dropping the 4. The double cast is the right idiom here, not a workaround to replace. 5. Reference lifetime is safe. Under 6. All call sites are positional-only, so the loss of
Note the Suggestions (all non-blocking)a) Collapse the {{"{entry_func}", reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>({entry_func}_py)), METH_FASTCALL, ""}},b) Consider a one-line comment on the // 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. Minor behavioral note (no action needed)Calling a kernel with keyword arguments previously fell through to the generic Things I could not verifyI 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 |
aorenste
left a comment
There was a problem hiding this comment.
(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[] = {{ | |||
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
Lines 2374 to 2376 in 2760264
pytorch/torch/csrc/utils/pycfunction_helpers.h
Lines 20 to 26 in 2760264
The double reinterpret_cast approach seems to be the standard way of doing this.
|
@aorenste here are the numbers and the benchmarking script
#!/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() |
|
@aorenste is this good to merge or do you have more suggestions? |
|
@lakshayg I already approved - so good to merge. |
|
@pytorchmergebot merge |
Merge startedYour 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 |
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
This PR reduces the Python overhead for inductor generated python
bindings by replacing
METH_VARARGSwithMETH_FASTCALL.I used Codex to create a benchmark for Python bindings generated by
CppPythonBindingsCodeCache.load_pybindingit shows a consistentreduction 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