Skip to content

Fix integer overflow in max_pool1d shape checks - #194112

Closed
malfet wants to merge 1 commit into
mainfrom
malfet/fix-pooling-int64-overflow
Closed

malfet wants to merge 1 commit into
mainfrom
malfet/fix-pooling-int64-overflow

Conversation

@malfet

@malfet malfet commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

torch.max_pool1d segfaults for several out-of-domain integer arguments.
There are three separate silent integer overflows in the shape math, and all three have to go for the op to be safe — fixing (1) alone makes (3) newly reachable.

1. div_rtn() floor-divides in int

 template <typename T>
 static inline T div_rtn(T x, T y) {
-  int q = x / y;
-  int r = x % y;
+  T q = x / y;
+  T r = x % y;

Every call site passes div_rtn<int64_t>, so the truncated remainder gets the wrong sign, the floor correction is skipped, and the quotient wraps. For #73190 (kernel_size = stride = dilation = 2147483697) the true output size -2147483694 becomes +2147483602 and sails past TORCH_CHECK(OW > 0); for #136719 (kernel_size = stride = INT64_MAX) a true 0 becomes 1. In both cases the kernel then indexes out of bounds.

The helper is shared, so this also affects the shape checks in im2col_shape_check.h, ConvolutionMM2d/3d.cpp, DilatedConvolutionUtils.h, the CUDA Im2Col/Col2Im/ConvolutionMM2d kernels and MPS Pooling.mm. Two side effects, both improvements: slow_conv_dilated2d with dilation = 2147483697 used to silently return a [1, 1, 0, 0] tensor and now raises calculated output size -1 -1 is too small, and F.unfold with an INT32-boundary stride now fails in the im2col shape check instead of downstream in numel.

Checked the two bodies against an __int128 floor-division reference: identical on all 1,000,100 realistic in-range cases (|x| <= 5000, |y| <= 50); over 3,000,000 random int64 pairs the old one is wrong 1,499,994 times and the new one 0.

2. dilation * (kernel_size - 1) + 1 overflows in pooling_output_shape()

This is #142454, a different root — div_rtn is doing exact arithmetic on already-garbage input. With kernel_size = 8608480567731124087 and dilation = 1250999896764, the effective kernel size wraps to +3689346979942061737, so the pad check passes; the numerator wraps to +4919136089788855880, so OW comes out 1. Computed with c10::mul_overflows/add_overflows and rejected instead.

This is also where the nonsensical pad should be at most half of effective kernel size, but got pad=0 messages came from: the wrapped bound went negative, so pad = 0 failed a check about padding for reasons that had nothing to do with padding. Those inputs now report the actual problem.

3. at::divup() overflows — handled in #195035

PoolingParams1D::valid_output_end bounds the output range with divup, so with a large stride the CPU kernel got a range whose window starts past the end of the input:

torch.max_pool1d(torch.full((2, 10, 4), 0.5, dtype=torch.float64),
                 [2], [2**63 - 1], [0], [2147483647], True)   # SIGSEGV with only (1) applied

Reachable only once (1) is fixed, and only on the non-autograd CPU path — max_pool1d_with_indices rejects such strides in safe_downcast<int>, which is why it stayed hidden. OW = 1 is correct here; the fixed result matches what max_pool1d_with_indices computes for the same arguments.

Testing

Error cases added to the nn.functional.max_pool1d OpInfo (the INT32-boundary kernels, the INT64_MAX kernel, and the effective-kernel-size overflow). (3) produces a correct result rather than an error, so it goes in the existing test_max_pool1d_corner_cases as one more check(...) — adding it as an OpInfo sample input instead fails 10 generic tests, since the with_indices variant legitimately rejects INT64_MAX strides.

🤖 Generated with Claude Code

@malfet
malfet requested a review from mruberry as a code owner August 19, 2026 20:45
@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 18 Pending, 2 Unrelated Failures, 2 Unclassified Failures

As of commit 7acd36a with merge base fdc97e8 (image):

NEW FAILURE - The following job has failed:

  • BC Lint / bc_linter (gh)

    AI verdict: AI verdict: not related

    The BC linter failure flags "Function reduce_event: function deleted", but this commit only modifies pooling-related C++ headers and test files. The reduce_event function lives in distributed/FSDP code that this commit does not touch at all.

    Full reasoning on HUD →

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:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

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

@drisspg

drisspg commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

@claude fable do your thing and review this one

@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Claude finished @drisspg's task in 19m 35s —— View job


Reviewed the three overflow fixes: the div_rtn, effective_kernel_size, and ceil_div_stride changes are correct and well-tested, but the numerator in pooling_output_shape_pad_lr can still overflow int64 (UB) via the same max_pool1d entry point when ceil_mode=True with a huge stride, and the Python mirrors of pooling_output_shape (meta/JIT) were not updated.

PR Review: #194112 (click to expand)

Note: This review was generated by an AI assistant (Claude) at the request of @drisspg.

Summary

Fixes three silent int64/int overflows in max_pool1d shape math (div_rtn flooring in int, dilation * (kernelSize - 1) + 1 wrapping, at::divup wrapping in PoolingParams1D), closing three segfault issues. The individual fixes are correct and each has a regression test, but one overflow in the same function remains reachable, and the eager change diverges from the Python shape-function mirrors.

Code Quality

  1. Residual int64 overflow (UB) in pooling_output_shape_pad_lr — aten/src/ATen/native/Pool.h:79. The numerator inputSize + pad_l + pad_r - dilation * (kernelSize - 1) - 1 + (ceil_mode ? stride - 1 : 0) still overflows after the new effective_kernel_size check passes. Concrete case reachable through the exact entry point this PR fixes:

    torch.max_pool1d(torch.rand(2, 10, 4), kernel_size=2, stride=2**63 - 1, dilation=1, ceil_mode=True)

    effective_kernel_size = 2 (no overflow), pad check passes, but the numerator is 4 - 2 + (2**63 - 2) = 2**63, one past INT64_MAX — signed overflow, i.e. UB. On two's-complement wraparound it lands at -2**63, div_rtn floors to -2, and check_max_pool1d rejects with Invalid computed output size: -1 — while the mathematically correct output size is 1 (the same answer your new ceil_div_stride test case produces for a nearby input). So the symptom today is "only" a spurious rejection plus UB that UBSan builds will trap on, but it is the same bug class, in the same function, as fix (2). Note your sweep contains this exact combination (kernel=2, stride=INT64_MAX, dilation=1, ceil_mode on) — it doesn't crash, which is why it passed, but it is still UB. Suggest computing the numerator with the c10::add_overflows/c10::mul_overflows machinery this PR already introduces (or special-casing stride - 1 in ceil mode, since overflow there implies the quotient term is 0 or 1). Fix this →

  2. Python mirrors of pooling_output_shape not updated — torch/_meta_registrations.py:5050 and torch/jit/_shape_functions.py:240 replicate this function. Python ints don't wrap, so they won't crash, but for the overflow inputs the meta/JIT paths now raise a different error than eager (Invalid computed output size / pad-check message vs. the new effective kernel size overflows). If you want eager/compile error parity, the same rejection should be mirrored there; at minimum this is a known divergence worth a comment or follow-up.

  3. Pre-existing double semicolon on the line adjacent to your edit: int64_t ij = index(kj, 0);; — aten/src/ATen/native/MaxPooling.h:87. You're already touching this function; drop the stray ;.

Testing

  • The div_rtn fix changes observable behavior on the conv/im2col paths, per the PR description (slow_conv_dilated2d with dilation = 2147483697 goes from silently returning a [1, 1, 0, 0] tensor to raising, and F.unfold now fails earlier in the im2col shape check). Neither behavior change has a regression test; without one, a future revert of the div_rtn change would silently restore the wrong-result path. Add an error input (or a test_convolution.py case) for at least the slow_conv_dilated2d case.

Recommendation

Request Changes

Blocking: item 1 — the PR's stated goal is making this shape math overflow-safe, and an int64 signed-overflow (UB) remains reachable in the very function being fixed, through the very op being fixed, using the tooling the PR already adds. Items 2–3 are should-fix but wouldn't block on their own.


  • Read PR diff and changed files
  • Run /pr-review analysis (verified div_rtn call sites, safe_numerics semantics, check_max_pool1d flow, meta registrations; residual-overflow claim independently fact-checked)
  • Post review

@@ -3874,6 +3870,24 @@ def error_inputs_max_pool1d(op_info, device, **kwargs):
kwargs={'kernel_size': 5, 'stride': 1, 'padding': 0, 'dilation': 1}),
error_regex=error_msg)

# error inputs for invalid output size, with a kernel past INT32_MAX:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This won't run out of space or require largeTensor decorators?

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.

No, because it should never allocate, just error out right away

@janeyx99
janeyx99 requested a review from drisspg August 21, 2026 06:49
@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 21, 2026
@malfet
malfet force-pushed the malfet/fix-pooling-int64-overflow branch 2 times, most recently from ceafc74 to e393227 Compare August 23, 2026 21:48
Comment thread aten/src/ATen/Parallel.h Outdated
// Not (x + y - 1) / y: that overflows for large x or y and silently rounds
// down. Truncation already rounds a negative quotient up, so only a positive
// remainder needs the correction.
return x / y + (x % y > 0);

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.

I hate that this is not called ceil_div

Comment thread aten/src/ATen/div_rtn.h Resolved

@Skylion007 Skylion007 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I have my nit about the possible static assert otherwise looks good.

@malfet
malfet force-pushed the malfet/fix-pooling-int64-overflow branch from e393227 to 1a3537c Compare August 27, 2026 19:09
@malfet
malfet changed the base branch from main to malfet/divup-safe-numerics August 27, 2026 19:10
`torch.max_pool1d` segfaults for several out-of-domain integer arguments.
Two overflows in the shape math remain after the `at::divup` fix this is
stacked on:

1. `div_rtn()` computed the floor quotient in `int` regardless of `T`,
   although every call site passes `div_rtn<int64_t>`. The truncated
   remainder gets the wrong sign, so the floor correction is skipped and
   the quotient wraps: for #73190 the true output size `-2147483694`
   became `+2147483602`, sailing past `TORCH_CHECK(OW > 0)`. Also fixes
   the shape checks in im2col/col2im, ConvolutionMM2d/3d and the CUDA
   and MPS pooling paths, which use the same helper.

2. `dilation * (kernel_size - 1) + 1` in `pooling_output_shape()`
   overflows int64 for large kernels, wrapping the pad bound positive
   and producing a bogus output size (#142454). Compute it with
   `c10::mul_overflows` and reject the overflow instead. This is also
   what produced the nonsensical "pad should be at most half of
   effective kernel size, but got pad=0" message.

The third overflow, in `at::divup`, is the parent PR: `PoolingParams1D`
bounds the output range with it, so the CPU kernel read a window
starting past the end of the input. That one is only reachable once (1)
is fixed, and only on the non-autograd CPU path -- `max_pool1d_with_indices`
rejects such strides in `safe_downcast<int>`.

Fixes #73190, #136719, #142454

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EFzKNdrvb8pUYeCUSxhtEA
@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

Attention! native_functions.yaml was changed

If you are adding a new function or defaulted argument to native_functions.yaml, you cannot use it from pre-existing Python frontend code until our FC window passes (two weeks). Split your PR into two PRs, one which adds the new C++ functionality, and one that makes use of it from Python, and land them two weeks apart. See https://github.com/pytorch/pytorch/wiki/PyTorch's-Python-Frontend-Backward-and-Forward-Compatibility-Policy#forwards-compatibility-fc for more info.


Attention! PyTorch one of the C-stable API file was changed

You MUST NOT change existing function declarations in this, as this header defines a stable C ABI. If you need to change the signature for a function, introduce a new v2 version of the function and modify code generation to target the new version of the function.

@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

5 similar comments
@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@malfet

malfet commented Aug 31, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "Pull and trunk are green, rest of the failures seems unrelated"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

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

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged open source 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