Skip to content

Fix assert_close to support comparisons involving Python and NumPy scalars - #188945

Closed
Partha-Shankar wants to merge 3 commits into
pytorch:mainfrom
Partha-Shankar:issue-161863-assert-close-scalars
Closed

Partha-Shankar wants to merge 3 commits into
pytorch:mainfrom
Partha-Shankar:issue-161863-assert-close-scalars

Conversation

@Partha-Shankar

@Partha-Shankar Partha-Shankar commented Jul 4, 2026 •

Copy link
Copy Markdown

Description

This PR resolves issue #161863 where torch.testing.assert_close would raise a TypeError (no comparison pair was able to handle inputs) when comparing a torch.Tensor to a Python scalar (int, float, complex, bool) or a NumPy scalar (np.generic).

Implementation Details

  • Modified TensorLikePair._process_inputs to identify if either input is a Python or NumPy scalar. If so, we bypass the strict directly_related subclass and type matching checks.
  • Bypassed spurious device mismatch errors by dynamically identifying the target device of the torch.Tensor operand and initializing the scalar directly on that device via torch.as_tensor(tensor_like, device=device) during conversion.
  • This device-coercion approach is extremely clean and eliminates the need for keeping temporary instance variables or modifying attribute matching methods in TensorLikePair.
  • Preserves expected behavior of check_dtype=True, which will still correctly raise an AssertionError for mismatched dtypes (e.g., float32 vs float64), as documented.

Link to Issue

Fixes #161863

Test Plan

  1. Added regression tests in test/test_testing.py covering CPU tensor vs scalar, CUDA tensor vs scalar, NumPy scalar vs tensor, and type checks.
  2. Ran regression test:
    python test/test_testing.py -k test_tensor_vs_scalar
    

cc @mruberry @rgommers

@pytorch-bot

pytorch-bot Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 2 New Failures, 45 Unclassified Failures

As of commit f57775f with merge base 447c525 (image):

NEW FAILURES - The following jobs have failed:

  • Lint / lintrunner-noclang-partial / lint (gh)
    >>> Lint for torch/testing/_comparison.py:

    AI verdict: AI verdict: related

    The commit modified torch/testing/_comparison.py with new multi-line expressions that likely exceed the line length limit (B950), and the lint failure is specifically on that file. Trunk commits all pass lint cleanly.

    Full reasoning on HUD →

  • Lint / lintrunner-pyrefly-partial / lint (gh)
    >>> Lint for torch/testing/_comparison.py:

    AI verdict: AI verdict: probably related

    The commit modified torch/testing/_comparison.py, which triggered the pyrefly-partial lint job to run on that file. The lint failed with both a PYFMT formatting issue on the changed lines and a PYREFLY linter crash, while trunk passes pyrefly-all (including this file) successfully.

    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:

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Jul 4, 2026 •

Copy link
Copy Markdown

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

  • ✅ login: Partha-Shankar / name: Partha-Shankar (a0e2cc5)

@Partha-Shankar

Copy link
Copy Markdown
Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Jul 4, 2026
@drisspg drisspg added triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module module: numpy Related to numpy support, and also numpy compatibility of our operators labels Jul 6, 2026
@Partha-Shankar

Copy link
Copy Markdown
Author

Hi @mruberry @rgommers — following up since it's been about a week since triage. Would appreciate it if someone could approve the CI workflows so tests can run, and any review feedback when you have a chance. Thanks!

…ed test failure)

torch.compile/Dynamo traces NumPy scalars as 0-dimensional ndarrays rather than np.generic instances, so the scalar-detection check needed to account for that.
@Partha-Shankar

Copy link
Copy Markdown
Author

Hi @mruberry @rgommers — following up with a fix for the dynamo_wrapped CI failures:

Root Cause

Under dynamo_wrapped test configurations, torch.compile/Dynamo traces NumPy scalars (like np.float64(1.0)) as 0-dimensional numpy.ndarray objects instead of np.generic instances. This caused the scalar detection check in TensorLikePair._process_inputs to miss them, raising an unexpected TypeError.

Fix Applied

  1. Modified TensorLikePair._process_inputs in torch/testing/_comparison.py to identify 0-dimensional numpy.ndarray objects (ndim == 0) as scalars.
  2. Added regression tests in test/test_testing.py to verify comparing 0-d NumPy arrays against torch.Tensor under both eager and compiled (torch.compile) modes.
  3. Verified that non-scalar NumPy arrays (1-d/2-d) still raise TypeError as expected.

Pushed as commit f57775f. Happy to address any review feedback once CI reruns on this commit.

@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Oct 10, 2026
@github-actions github-actions Bot closed this Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module: numpy Related to numpy support, and also numpy compatibility of our operators open source Stale topic: not user facing topic category 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.

torch.testing.assert_close doesn't accept tensor-likes

3 participants