Skip to content

Add Barebones Unsigned Integer Support to the Clamp Family - #189953

Closed
colalb1 wants to merge 10 commits into
pytorch:mainfrom
colalb1:colalb1/clamp_additions
Closed

colalb1 wants to merge 10 commits into
pytorch:mainfrom
colalb1:colalb1/clamp_additions

Conversation

@colalb1

@colalb1 colalb1 commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Adds uint16, uint32, and uint64 support to clamp functions on CPU and CUDA. These ops previously rejected the barebones unsigned dtypes because their kernels dispatched through AT_DISPATCH_ALL_TYPES_AND2, which omits them.

Relationship to #189872

Unblocks #189872 ("Add Autograd Support for Low-Level Bessel Functions"). That PR restricts the x > 0 Bessel OpInfos (special.bessel_y0, bessel_y1, modified_bessel_k0, modified_bessel_k1) to domain=(0, None), which makes the unary sample generator call clamp_min on the sample dtypes. For the barebones unsigned dtypes that call currently raises NotImplementedError, so #189872 marks the uint16/uint32/uint64 forward reference-numerics tests as expectedFailure. With clamp supporting these dtypes, those tests pass and the xfails can be removed there.

cc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01

@pytorch-bot

pytorch-bot Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ You can merge normally! (3 Unrelated Failures), 1 Unclassified Failure

As of commit 194114f with merge base 100c32b (image):

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

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

@pytorch-bot pytorch-bot Bot added the module: cpu CPU specific problem (e.g., perf, algorithm) label Jul 14, 2026
@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jul 15, 2026
Skylion007
Skylion007 previously approved these changes Jul 16, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator

Could we extend our current clamp tests to cover these unsigned integer types? I think they aren't covered by optests?

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.

Pull request overview

This PR extends the clamp kernel implementations (tensor- and scalar-bound variants) on CPU and CUDA to accept the barebones unsigned integer dtypes (uint16, uint32, uint64) by migrating the dispatch sites to AT_DISPATCH_V2 with AT_BAREBONES_UNSIGNED_TYPES.

Changes:

  • Switch CUDA clamp / clamp_scalar dispatch to AT_DISPATCH_V2 and include AT_BAREBONES_UNSIGNED_TYPES.
  • Switch CPU clamp / clamp_scalar / clamp_min_scalar / clamp_max_scalar dispatch to AT_DISPATCH_V2 and include AT_BAREBONES_UNSIGNED_TYPES.
  • Add Dispatch_v2 include for the updated CPU dispatch usage.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
aten/src/ATen/native/cuda/TensorCompare.cu Extend CUDA clamp-family dispatch to include barebones unsigned integer dtypes via AT_DISPATCH_V2.
aten/src/ATen/native/cpu/TensorCompareKernel.cpp Extend CPU clamp-family dispatch to include barebones unsigned integer dtypes via AT_DISPATCH_V2.

@colalb1
colalb1 requested a review from Skylion007 July 16, 2026 17:32
Comment thread test/test_shape_ops.py Resolved
@colalb1
colalb1 requested a review from Skylion007 July 16, 2026 18:06
_barebones_unsigned_types = _dispatch_dtypes((torch.uint16, torch.uint32, torch.uint64))


def barebones_unsigned_types():

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.

We don't need a function, we have the internal we can just import above? UNless it needs to be a function for some reason?

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.

nvm, I guess this is a common idiom here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@Skylion007 Could you trigger CI when you get the chance?

Thank you.

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR again

@claude

claude Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 31m 18s —— View job


Review

The dispatch changes look correct and the test now genuinely exercises the new dtypes, but the test's bound selection avoids the two cases most likely to be broken (min=None/max=None at extremes and any bound above the signed max), and the maximum/minimum widening in BinaryOpsKernel.cpp / MaxMinElementwiseKernel.cu silently expands torch.maximum/torch.minimum beyond their declared OpInfo dtypes without a matching OpInfo update.

Full review details

Scope note

Since the last review round the PR grew beyond the clamp kernels: it now also widens maximum_kernel / minimum_kernel (aten/src/ATen/native/cpu/BinaryOpsKernel.cpp:663,698) and maximum_kernel_cuda / minimum_kernel_cuda (aten/src/ATen/native/cuda/MaxMinElementwiseKernel.cu:19,47) from AT_DISPATCH_INTEGRAL_TYPES to AT_EXPAND(AT_INTEGRAL_TYPES_V2). That is required for this PR — clamp_min_Tensor_out / clamp_max_Tensor_out route to maximum_stub/minimum_stub (aten/src/ATen/native/TensorCompare.cpp:857,877,891), so tensor-bound clamp_min/clamp_max would still NotImplementedError without it. Worth calling out in the PR description, though, because it is a user-visible side effect (see next point).

1. torch.maximum / torch.minimum now accept uint16/32/64 but their OpInfos don't claim it

BinaryUfuncInfo('maximum', ...) and BinaryUfuncInfo('minimum', ...) (plus the min/max variant_test_name='binary' entries) still declare dtypes=all_types_and(torch.float16, torch.bfloat16, torch.bool) — common_methods_invocations.py:14707-14740 and neighbours. TestCommon.test_dtypes iterates all_types_and_complex_and(...), which does not include the barebones unsigned types, so it won't catch the mismatch — but the ops are now silently more permissive than what the OpInfo advertises. Either add the dtypes to those four OpInfos, or state explicitly in the PR description that the maximum/minimum widening is intentional collateral needed by tensor-bound clamp_min/clamp_max.

2. The test's bound choice sidesteps the interesting cases

test/test_shape_ops.py:345-354 picks min_bound, max_bound = info.max // 4, info.max // 2 for the unsigned dtypes. For uint64 that's 2^62 / 2^63 - 1-ish — both fit in int64, so the Scalar carries Tag::HAS_i and never exercises the Tag::HAS_u path in Scalar::to<T>() (c10/core/Scalar.h:131). Combined with the data generation at line 305-308 (mostly randint(0, 50) plus four values near info.max), the actual test coverage is:

  • values near 2^64 get clamped down to max_bound, and
  • values in [0, 50) get clamped up to min_bound.

so nothing in X ever lands inside [min_bound, max_bound] for uint64. A pass-through element (min_bound <= x <= max_bound) is exactly the case a signed-comparison bug would corrupt, and it's currently untested. Adding, say, info.max // 3 to the top list would cover it cheaply.

Separately, the comment on line 346-347 says a bound straddling the signed max "would promote a Long scalar against a UInt64 one, which is unsupported". That's accurate for the tensor-bound path (promoteTypes hard-errors on barebones unsigned in c10/core/ScalarType.cpp:94-99), but for the scalar path a Python int > INT64_MAX becomes Scalar(uint64_t) with Tag::HAS_u (python_arg_parser.cpp:2006-2012), and clamp does its own manual promotion via update_result_type_state(const Scalar&, ...). That path plausibly works for uint64 and is where a truncation bug would live. Worth at least a targeted torch.clamp_max(x, 2**63 + 7) assertion on uint64, or an explicit comment/assertRaises recording that it is deliberately unsupported. Right now the reader can't tell "we checked and it errors" from "we didn't check".

3. astype(X_np.dtype) can mask a real reference mismatch

test/test_shape_ops.py:327-330 casts the NumPy result back to the input dtype. The comment explains the motivation (avoid ulonglong reaching from_numpy) and that's legitimate, but .astype is an unconditional narrowing cast — if NumPy's clip ever produced an out-of-range or sign-flipped value, the cast would wrap it into range and the assertion would pass. Consider np.clip(...).astype(X_np.dtype, casting="safe") (or an explicit assert r.min() >= 0 guard) so the reference stays a reference. Minor, but this is the only oracle in the test.

Also note the pinned NumPy versions in CI span 1.23 through 2.3 (.ci/docker/requirements-ci.txt:139-142), and NEP 50 changed integer-scalar promotion in 2.0. The .astype normalizes the dtype so the test should be stable across both, but it's worth confirming the values agree on the 1.23 leg too, not just the dtype.

4. MPS is left behind — check whether it now errors differently

The MPS clamp kernels are still narrow: clamp_scalar_kernel_mps uses AT_DISPATCH_ALL_TYPES_AND3 (aten/src/ATen/native/mps/operations/TensorCompare.mm:234) and the Metal side only instantiates long/int/short/uchar/char/bool/float/half/bfloat (kernels/TensorCompare.metal:46-55). Meanwhile getMPSDataType does map UInt16/32/64 (OperationUtils.mm:78-83), and check_for_unsupported_clamp_dtypes only rejects complex — so nothing at the meta level blocks a uint64 clamp on MPS. test_shape_ops.py doesn't pass allow_mps=True to instantiate_device_type_tests (line 893), so CI won't tell you either way. Not a blocker for this PR, but please confirm the MPS failure is a clean dispatch error rather than a missing-kernel crash, and if you're leaving MPS out, say so in the PR description.

5. Small things

  • common_dtype.py:164 — barebones_unsigned_types() matches the file's existing accessor idiom, so this is fine as-is (agreeing with your follow-up on the earlier thread).
  • test_shape_ops.py:354 and :395 — the tuple(product(...)) change is a genuine bug fix (the bare generator was exhausted after the first op, so only torch.clamp was ever tested against all four arg combinations; the other five ops silently tested nothing). That's worth an explicit sentence in the commit message, since it changes what the pre-existing int64/float32 coverage actually is and could surface unrelated failures.
  • CPU vectorized path: Vectorized<uint16_t> etc. have no explicit specializations, so clamp/clamp_min/clamp_max fall back to the generic element-wise loops in vec_base.h:937-1010, which use std::min/std::max on the unsigned type — correct, just unvectorized. Fine, but a one-line note in the PR description would set perf expectations.
  • CUDA scalar path: opmath_type<uint64_t> is the identity (no specialization in OpMathType.h), so lim0.to<opmath_t>() keeps full width and the _isnan branch compiles to false for integrals (NumericUtils.h:25-28). Looks correct.
| Branch: [`colalb1/clamp_additions`](https://github.com/pytorch/pytorch/tree/colalb1/clamp_additions)

Skylion007
Skylion007 previously approved these changes Jul 31, 2026
@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 31, 2026
@Skylion007 Skylion007 added release notes: cuda release notes category release notes: cpu (x86) release notes category for x86, intel, etc. release notes: cpu (aarch64) release notes category for aarch64, arm, etc. and removed ciflow/trunk Trigger trunk jobs on your pull request labels Jul 31, 2026
@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@pytorchmergebot
pytorchmergebot force-pushed the colalb1/clamp_additions branch from 5f225a2 to e58136b Compare August 5, 2026 16:18
@Skylion007

Copy link
Copy Markdown
Collaborator

What is the fix here? The original seemed like a legitimate internal compiler bug?

// The barebones unsigned types have no Vectorized specialization, and gcc-13
// ICEs auto-vectorizing the vec_base.h emulation for fixed-length SVE.
template <typename scalar_t>
constexpr bool use_vectorized_minmax =

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.

We should be specific and only include the affected compiler versions if we are going to use this workaround. It did look like it was surfacing a legit compiler bug

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, I think the fix was too broad in hindsight. I believe the issue was with GCC 13 where a predicate conversion pattern arose where SVE does not have a Vectorized<uint8_t> or Vectorized<Half> specialization, so the clamp_kernel_impl used emulation for uint8 and uint16 types.

I will remove this workaround and leave a guard scoped to GCC < 14 and a fixed length SVE.

@colalb1
colalb1 requested a review from Skylion007 August 5, 2026 23:54
@Skylion007

Skylion007 commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

@malfet @atalman what happened about dropping GCC13 for Aarch?

@colalb1

colalb1 commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

@Skylion007 I believe the failing check is unrelated to these changes.

If there is anything else I should change for merging, please let me know.

Thank you.

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot 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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: linux-binary-manywheel / libtorch-rocm7_14-shared-with-deps-release-extract

Details for Dev Infra team Raised by workflow job

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: linux-binary-manywheel / libtorch-rocm7_14-shared-with-deps-release-extract

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

ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
…189953)

Adds `uint16`, `uint32`, and `uint64` support to `clamp` functions on CPU and CUDA. These ops previously rejected the barebones unsigned dtypes because their kernels dispatched through `AT_DISPATCH_ALL_TYPES_AND2`, which omits them.

## Relationship to pytorch#189872

Unblocks pytorch#189872 ("Add Autograd Support for Low-Level Bessel Functions"). That PR restricts the `x > 0` Bessel OpInfos (`special.bessel_y0`, `bessel_y1`, `modified_bessel_k0`, `modified_bessel_k1`) to `domain=(0, None)`, which makes the unary sample generator call `clamp_min` on the sample dtypes. For the barebones unsigned dtypes that call currently raises `NotImplementedError`, so pytorch#189872 marks the `uint16/uint32/uint64` forward reference-numerics tests as `expectedFailure`. With clamp supporting these dtypes, those tests pass and the xfails can be removed there.

Pull Request resolved: pytorch#189953
Approved by: https://github.com/Skylion007
gavinwang269 pushed a commit to gavinwang269/pytorch that referenced this pull request Aug 13, 2026
…189953)

Adds `uint16`, `uint32`, and `uint64` support to `clamp` functions on CPU and CUDA. These ops previously rejected the barebones unsigned dtypes because their kernels dispatched through `AT_DISPATCH_ALL_TYPES_AND2`, which omits them.

## Relationship to pytorch#189872

Unblocks pytorch#189872 ("Add Autograd Support for Low-Level Bessel Functions"). That PR restricts the `x > 0` Bessel OpInfos (`special.bessel_y0`, `bessel_y1`, `modified_bessel_k0`, `modified_bessel_k1`) to `domain=(0, None)`, which makes the unary sample generator call `clamp_min` on the sample dtypes. For the barebones unsigned dtypes that call currently raises `NotImplementedError`, so pytorch#189872 marks the `uint16/uint32/uint64` forward reference-numerics tests as `expectedFailure`. With clamp supporting these dtypes, those tests pass and the xfails can be removed there.

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

Labels

ci-no-td Do not run TD on this PR ciflow/binaries Trigger all binary build and upload jobs on the PR ciflow/trunk Trigger trunk jobs on your pull request Merged module: cpu CPU specific problem (e.g., perf, algorithm) open source release notes: cpu (aarch64) release notes category for aarch64, arm, etc. release notes: cpu (x86) release notes category for x86, intel, etc. release notes: cuda release notes category Reverted 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.

8 participants