Skip to content

[ATen]: complex type support for arange method - #194890

Closed
PyDevC wants to merge 11 commits into
pytorch:mainfrom
PyDevC:complex-arange-support
Closed

PyDevC wants to merge 11 commits into
pytorch:mainfrom
PyDevC:complex-arange-support

Conversation

@PyDevC

@PyDevC PyDevC commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Added support ComplexFloat and ComplexDouble for arange_cpu via linspace dispatch.

Issue: #160629

@ngimel @malfet

cc @ezyang @anjali411 @dylanbespalko @mruberry @nikitaved @amjames

dipatched arange_out to linspace stub for complex types. To get
same behvavior from the linspace we edited the end scalar to get proper
steps
@pytorch-bot

pytorch-bot Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 3 New Failures, 5 Unrelated Failures, 3 Unclassified Failures

As of commit bb84e66 with merge base 6b1f3af (image):

NEW FAILURES - The following jobs have failed:

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following jobs failed, but the AI CI Advisor judged the failures not to be evidence against this change:

  • docs-build / linux-docs / build-docs-cpp-false (gh)
    Could not load credentials from any providers

    AI verdict: AI verdict: infra issue

    The docs-build job failed during runner setup: the aws-actions/configure-aws-credentials step could not load credentials. The suspect only edits a test skip in common_methods_invocations.py, which cannot affect AWS credential loading, and trunk runs of the same job at the same time were green.

    Full reasoning on HUD →

  • docs-build / linux-docs / build-docs-python-false (gh)
    ModuleNotFoundError: No module named 'matplotlib'

    AI verdict: AI verdict: not related

    The docs build fails because build_activation_images.py hits ModuleNotFoundError: No module named 'matplotlib'. That comes from the PR's stale base: its CI image (pinned via .ci/docker/requirements-docs.txt) installs no matplotlib for Python 3.11, and trunk has since fixed that pin. The suspect commit only changes OpInfo skip decorators for arange on MPS, which has nothing to do with the docs environment.

    Full reasoning on HUD →

  • pull / linux-noble-xpu-n-py3.11 / build (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    Could not load credentials from any providers

    AI verdict: AI verdict: infra issue

    The job failed in its setup phase, at the aws-actions/configure-aws-credentials step. The OIDC role assumption failed with "Could not load credentials from any providers", and the action also warned that the id-token permission may be missing. This happened before any build ran. The suspect commit only edits test skip decorators in common_methods_invocations.py and touches no workflow or CI configuration, so it cannot have caused a credential failure.

    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:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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

@PyDevC

PyDevC commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Aug 26, 2026
@PyDevC
PyDevC marked this pull request as ready for review August 26, 2026 11:49
@albanD
albanD requested a review from ngimel August 26, 2026 15:57
@albanD albanD added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 26, 2026
@ngimel

ngimel commented Aug 26, 2026

Copy link
Copy Markdown
Collaborator

You'd probably need to change dtype support in opinfo tests at least

@PyDevC

PyDevC commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@ngimel I have added ComplexFloat, ComplexDouble as well as torch.bool in OpInfo.

There was one more question about this codeblock.

def arange(
start: NumberType = 0,
end: NumberType | None = None,
step: NumberType = 1,
*,
dtype: torch.dtype | None = None,
layout: torch.layout = torch.strided,
device: DeviceLikeType | None = None,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
utils.check_layout(layout)
utils.check_pin_memory(pin_memory)
device = torch.device(utils.device_or_default(device))
if isinstance(start, complex):
raise AssertionError("arange does not support complex start")
if isinstance(end, complex):
raise AssertionError("arange does not support complex end")
if isinstance(step, complex):
raise AssertionError("arange does not support complex step")
# Case: torch.arange(5)
if end is None:
end = start
start = 0
torch._check(step != 0, lambda: "step must be nonzero")
if step > 0:
torch._check(
end >= start,
lambda: "upper bound and lower bound inconsistent with step sign",
)
elif step < 0:
torch._check(
end <= start,
lambda: "upper bound and lower bound inconsistent with step sign",
)

Should I remove the assertions since Complex types are now supported, It still works completely fine with complex types.

@ngimel

ngimel commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

YEs remove those assertions too

@PyDevC

PyDevC commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@ngimel

def arange(
start: NumberType = 0,
end: NumberType | None = None,
step: NumberType = 1,
*,
dtype: torch.dtype | None = None,
layout: torch.layout = torch.strided,
device: DeviceLikeType | None = None,
pin_memory: bool = False,
requires_grad: bool = False,
) -> TensorLikeType:
utils.check_layout(layout)
utils.check_pin_memory(pin_memory)
device = torch.device(utils.device_or_default(device))
if isinstance(start, complex):
raise AssertionError("arange does not support complex start")
if isinstance(end, complex):
raise AssertionError("arange does not support complex end")
if isinstance(step, complex):
raise AssertionError("arange does not support complex step")
# Case: torch.arange(5)
if end is None:
end = start
start = 0
torch._check(step != 0, lambda: "step must be nonzero")
if step > 0:
torch._check(
end >= start,
lambda: "upper bound and lower bound inconsistent with step sign",
)
elif step < 0:
torch._check(
end <= start,
lambda: "upper bound and lower bound inconsistent with step sign",
)

I just noticed, if we remove these assertions, then we would have to do some bounds check again for complex numbers too. But same is already done in C++ bounds check at RangeUtils.h. Is there a need to do write code to do bounds check at both C++ and Python level?

@ngimel

ngimel commented Aug 27, 2026

Copy link
Copy Markdown
Collaborator

Yes python refs and c++ impls need to be in sync

@PyDevC

PyDevC commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@ngimel Changes done.
But the behavior of arange is now little different from numpy.

something like torch.arange(1+1j, 10+10j, step=2+2j, dtype=torch.complex64) work in torch but does not work in numpy, similarly following is possible in numpy but not possible in torch

np.arange(1+1j, 5+5j)=array([1.+1.j, 2.+1.j, 3.+1.j, 4.+1.j])
Traceback (most recent call last):
  File "/home/pydevc/work/project/exp/pytorchContrib/arange_not_implemented_for_cmplx_no.py", line 18, in <module>
    print(f"{torch.arange(1+1j, 5+5j)=}")
             ~~~~~~~~~~~~^^^^^^^^^^^^

imo the step is 1 + 0j instead of 1 + 1j, so its expected to throw error.

@PyDevC

PyDevC commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel can you start off the workflow?

fix included handling for size 0 and 1 for arange, as well as fixed the
expected Failure issues
@PyDevC

PyDevC commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

@ngimel current fixes should fix all previous failures.

Can you verify if semantics is as expected for torch.arange. Since current behavior diverges from numpy implementation of np.arange.

>>> torch.arange(1+1j, 10+10j, step=2+2j, dtype=torch.complex64)
tensor([1.+1.j, 3.+3.j, 5.+5.j, 7.+7.j, 9.+9.j])
>>> np.arange(1+1j, 10+10j, step=2+2j, dtype=np.complex64)
array([], dtype=complex64)

@ngimel

ngimel commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

cc @albanD

@albanD

albanD commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator

Is the decision here that the default step is 1 + 0j ?
For a different start and end you could use (end - start) / (end - start). That will guarantee that you consistently go from the start to the end?

For the discrepency with NumPy for 1+1j, 10+10j, step=2+2j , that sounds fair to me yes. It is the behavior I expect.

@PyDevC

PyDevC commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Is the decision here that the default step is 1 + 0j ?

yes the default step is if not specified must be 1 +0j.

For a different start and end you could use .....

if that is the expected behavior then we will go with it.

@PyDevC

PyDevC commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@albanD @ngimel linspace kernel already accounts for that.

The only required change was to ease the check for step.imag == 0.
Now Ig only final approval needed?

@rgommers

rgommers commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

I'll confirm that the numpy behavior makes no sense, there's a long-standing issue about it: numpy/numpy#10332. The docs were updated to make clear that only int/float dtypes are supported; the discussion on that issue leans towards a hard error, because there are several reasonable ways complex steps could be implemented. jax.numpy deprecated complex support more recently, because it inherited the bad numpy behavior: jax-ml/jax#33837.

Is the decision here that the default step is 1 + 0j ?
For a different start and end you could use (end - start) / (end - start). That will guarantee that you consistently go from the start to the end?

I like some version of the latter suggestion better, since a default where the last element isn't approaching end feels wrong. Not the actual formula though, because that still gives zero for the imaginary component:

>>> start = 0; end = 4+8j
>>> (end - start) / (end - start)
(1+0j)

There's no nice answer though, because if you approach the end point in a uniform fashion you'll get non-integer numbers:

>>> (end - start) / abs(end - start)
(0.4472135954999579+0.8944271909999159j)

Might be cleaner to require a step value, because for an arange(0, 4+8j) you probably want something like [0, 1+2j, 2+4j, 3+6j] as a user, but there's no way to get that behavior automatically.

@albanD

albanD commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

Ho yes sorry. I forgot that complex division is not R2.
And also that things on the L2 unit circle will not give you round numbers.

Requiring the step to be specified sounds very fair to me indeed.
The other benefit, is that, if we later find a clever default step, we can change the error with this new value and that is not BC breaking.

@PyDevC

PyDevC commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel approved for the merge?

@ngimel

ngimel commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator

@claude was a suggestion to require step argument addressed?

@claude

claude Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 3m 9s —— View job


Answer: No — and the last commit moved in the opposite direction

  • Read the trigger question
  • Inspect RangeUtils.h, RangeFactories.cpp, TensorFactories.cpp, torch/_refs/__init__.py at HEAD (7466636f)
  • Trace what torch.arange(1+1j, 5+5j) does with the current code
  • Report findings

Short answer: the suggestion from @rgommers / @albanD to require an explicit step for complex was not implemented. There is no check anywhere in the diff that rejects a defaulted step, and the last commit (7466636f, "remove imaginary check for step.imag() == 0") actually made arange reproduce the exact NumPy behavior that was agreed to be wrong.

Details

1. Defaulted step is now silently accepted (regression vs. earlier in this PR)

aten/src/ATen/native/RangeUtils.h:23-27 (added by 7466636f) skips the imaginary-part bound check whenever step.imag() == 0:

if(stepc.imag() != 0) {
TORCH_CHECK(((stepc.imag() > 0) && (endc.imag() >= startc.imag())) || ...

With the default step = 1 (1+0j), torch.arange(1+1j, 5+5j) therefore:

  1. passes arange_check_bounds (imag check skipped),
  2. takes the xstepc.imag() == 0 branch in compute_arange_size and sizes the output from the real part only -> 4,
  3. dispatches linspace_stub from 1+1j to 4+1j.

Result: [1+1j, 2+1j, 3+1j, 4+1j] — i.e. end.imag is silently discarded. That is numpy/numpy#10332 behavior verbatim, the thing NumPy documented away and JAX deprecated. Before 7466636f this same call raised, which was closer to the agreed outcome.

To require step, the natural place is the no-step entry points, since the 2-arg / 1-arg forms are distinct overloads (arange.start, arange.out) and so "not passed" is distinguishable from "passed as 1":

  • aten/src/ATen/native/TensorFactories.cpp:136-154 (arange(end, ...) and arange(start, end, ...))
  • aten/src/ATen/native/RangeFactories.cpp range_out_no_step / arange_out(end, result)
  • and the mirror in torch/_refs/__init__.py:5534 (where step defaults to 1, so a sentinel or an explicit step == 1 and has_complex rejection is needed to stay in sync).

Fix this →

2. Two other things I noticed while tracing this (worth fixing regardless of the step decision)

a. Complex size formula uses the integer arange formula, so it over-counts by one and can include end.
RangeUtils.h:98-100 uses the int64 (distance + step - sgn) / step form for float-valued complex:

arange(0.,   4.,   2.)     -> ceil(4/2)             = 2  -> [0., 2.]
arange(0.j, 4+0j, 2+0j)    -> ceil((4 + 2 - 1)/2)   = 3  -> [0, 2, 4]   # end included

The complex path should use ceil(distance/step) per component like the float path at RangeUtils.h:111, not the -sgn integer variant.

b. The python ref and the C++ impl disagree on mixed complex steps, so test_python_ref* can diverge from eager: RangeUtils.h:106 errors when the real- and imaginary-derived sizes differ, while torch/_refs/__init__.py:5646 takes max(real_length, imag_length). Since the stated requirement in this PR is that refs and C++ stay in sync, one of these needs to change.

c. Minor: RangeUtils.h:35-40 — the imaginary-part finiteness check reuses the message "unsupported range for real part: ".

I have not pushed any code changes; this is analysis only. Happy to implement the "require explicit step" restriction (plus a test) if you want it in this PR.
| Branch: complex-arange-support

@ngimel

ngimel commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 2, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 6 checks: docs-build / linux-docs / build-docs-python-false, docs-build / linux-docs / build-docs-cpp-false, pull / linux-noble-xpu-n-py3.11 / build, pull / linux-jammy-aarch64-py3.11 / build, pull / linux-jammy-cuda13.2-cudnn9-py3.11-clang20 / build, pull / linux-jammy-py3.11-gcc11 / test (docs_test, 1, 1, mt-l-x86iavx512-8-64)

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: 2 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m2-15), trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)

Details for Dev Infra team Raised by workflow job

@pytorch-bot

pytorch-bot Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@PyDevC

PyDevC commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel I have added same arange for CUDA as well and skipped mps tests since it does not support linespace as well

@ngimel

ngimel commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

@PyDevC looks like there's a related mps failure?

@PyDevC

PyDevC commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel skipping for pythonrefinfo would fix it?

@PyDevC

PyDevC commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

@ngimel test/test_nn.py::TestNNDeviceTypeMPS::test_grid_sample_large_index_2d_mps_float32 seems unrelated

@ngimel

ngimel commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

@claude are there CI failures related to this PR?

@claude

claude Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 1m 29s —— View job


No, none of the current CI failures are related to this PR.

On the latest commit (bb84e66e) no arange or linspace test fails on any platform. The earlier MPS arange failure is gone: macos-py3-arm64 / test (mps, 1, 1, macos-m2-15) now passes.

Details

I read the logs of the failing jobs in trunk run 37680852436.

Job Failing test Root cause Related?
macos-m1-stable default 1/3 test_nn.py::TestNNDeviceTypeMPS::test_grid_sample_large_index_2d_mps_float32 torch.zeros([1, 1, 32769, 65536]) raises RuntimeError: Invalid buffer size: 8.00 GiB. This is a memory limit on the M1 runner. No
macos-m1-stable default 2/3 test_ops.py::TestCommonMPS::test_dtypes_scatter_reduce_amax_mps The int64 kernel fails with Failed to created pipeline state object ... "Unsupported float atomic operation for given target." (AGXMetal13_3) No
macos-m1-stable default 3/3 test_ops.py::TestCommonMPS::test_noncontiguous_samples_scatter_reduce_amin_mps_int64 Same Metal atomic pipeline error in scatter_reduce No
dynamo-unittest 3.11 dynamo_wrapped 5/7 test_autograd.py::TestAutograd::test_saved_tensor_hooks_extra_enter_during_bw_no_leak Known flaky test, disabled by #190499. It needs a rebase to pick that up. No
  • The three M1 failures are Metal/hardware problems in torch.zeros and scatter_reduce. The PR doesn't touch either op or any MPS code, and the matching tests on the M2 MPS shard pass.
  • The pull failures are runner or credential problems in setup steps: aarch64 build, cuda13.2 build, xpu build, docs build and docs_test. These include Could not load credentials from any providers and a missing matplotlib in the stale docs image. All other Linux CPU, CUDA 13.0/13.2, ROCm, Windows and aarch64 test shards in the trunk run pass.
  • Rebasing onto current main should clear the flaky dynamo test and the docs-image failure.

@ngimel

ngimel commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

@pytorchbot merge -i

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 module: complex Related to complex number support in PyTorch open source 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.

6 participants