Skip to content

Fix call to fork_rng by by specifying device type - #180512

Closed
frost-intel wants to merge 8 commits into
pytorch:mainfrom
frost-intel:fork_rng_device_type
Closed

frost-intel wants to merge 8 commits into
pytorch:mainfrom
frost-intel:fork_rng_device_type

Conversation

@frost-intel

Copy link
Copy Markdown
Collaborator

Fixes a bug for non-CUDA devices introduced by #177728 due to a misused call to fork_rng

  • Since the call to fork_rng should specify the device type, I specify this in schedules.py
  • The design of fork_rng seems outdated since the adoption of non-CUDA devices. I change the signature so the device_type default argument is None, and is inferred from the passed devices. If it can't be inferred from the device list (because it's a list of ints, for example) we still fallback to the previous value of "cuda".

@pytorch-bot

pytorch-bot Bot commented Apr 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit f10754f with merge base f97c056 (image):

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

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

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

@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Apr 15, 2026
@pytorch-bot

pytorch-bot Bot commented Apr 15, 2026 •

Copy link
Copy Markdown

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

@guangyey guangyey 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.

Could you please help me understand what will happen if without this fix.

Comment thread torch/random.py Outdated
devices = list(devices)
if devices:
try:
device_type = torch.device(devices[0]).type

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 could move this to line 203/218 such as:

    if devices is None:
        num_devices = device_mod.device_count()
        devices = list(range(num_devices))
        if num_devices > 1 and not _fork_rng_warned_already:
            device_type = devices[0].type
            message = (
                f"{device_type.upper()} reports that you have {num_devices} available devices, and "
                f"you have used {_caller} without explicitly specifying which devices are being used. "
                f"For safety, we initialize *every* {device_type.upper()} device by default, which can "
                f"be quite slow if you have a lot of {device_type.upper()}s. If you know that you are only"
                f" making use of a few {device_type.upper()} devices, set the environment variable "
                f"{device_type.upper()}_VISIBLE_DEVICES or the '{_devices_kw}' keyword argument of {_caller} "
                "with the set of devices you are actually using. For example, if you are using CPU only, "
                "set device.upper()_VISIBLE_DEVICES= or devices=[]; if you are using device 0 only, "
                f"set {device_type.upper()}_VISIBLE_DEVICES=0 or devices=[0].  To initialize all devices "
                f"and suppress this warning, set the '{_devices_kw}' keyword argument to "
                f"`range(torch.{device_type}.device_count())`."
            )
            warnings.warn(message, stacklevel=2)
            _fork_rng_warned_already = True
        

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.

This doesn't solve any problems because device_mod is set by device_type on line 186/201.

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.

You are right! I think we could use torch.get_device_module to avoid these if statements.

}
)
with torch.random.fork_rng(devices=devices):
device_type = stages[0].device if stages else "cuda"

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.

Suggested change
device_type = stages[0].device if stages else "cuda"
device_type = devices[0].type if devices else None

stages[0] may be a cpu.

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.

stages will not contain cpu based on the logic immediately above but I have no objection to changing this to None.

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 notice stages is filtered by cpu in line 423. Doesn't it mean it may contain cpu.

@frost-intel

Copy link
Copy Markdown
Collaborator Author

Could you please help me understand what will happen if without this fix.

@guangyey The call in schedules.py was not correct, so it sends a list of xpu devices while using the default device type of "cuda", which results in an error:
AssertionError: Torch not compiled with CUDA enabled which is occurs in device_mod.get_rng_state(device).

Technically, the fix for the specific error we are seeing could be fixed in either schedules.py or random.py, and we don't require both. But I thought that the design of fork_rng isn't very intuitive, where you can pass devices and the default device type results in errors, so I thought I would fix in both places.

Comment thread torch/random.py Outdated
Comment on lines 200 to 201

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.

Suggested change
device_mod = torch.get_device_module(device_type)

Comment thread torch/random.py
if devices is None:
num_devices = device_mod.device_count()
if num_devices > 1 and not _fork_rng_warned_already:
message = (

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.

device_type = device_type or torch.accelerator.current_accelerator().type

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.

num_devices > 1 already means that current accelerator is available.

@frost-intel
frost-intel requested a review from guangyey April 20, 2026 13:15
@frost-intel

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

guangyey
guangyey previously approved these changes Apr 30, 2026

@guangyey guangyey 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.

Thanks for your update!

@guangyey
guangyey marked this pull request as ready for review April 30, 2026 02:04
@guangyey
guangyey requested a review from albanD April 30, 2026 02:04
}
)
with torch.random.fork_rng(devices=devices):
device_type = devices[0] if devices else None

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'm confused by this?
How was this code working before?

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.

This code was erroneously added recently in #177728. Other existing calls to fork_rng specify device_type, which this new call didn't do.

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.

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.

Thanks for the pointer!
And the fix!

@frost-intel

Copy link
Copy Markdown
Collaborator Author

@kwen2501 Could you review this to unblock? Since @albanD has been unreachable.

@guangyey
guangyey requested a review from janeyx99 May 14, 2026 01:52
@guangyey

Copy link
Copy Markdown
Collaborator

Hi @janeyx99 could you please help take a look when you have a chance? Alban seems to be OOO.

@guangyey

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@guangyey guangyey added the ciflow/trunk Trigger trunk jobs on your pull request label May 19, 2026
@frost-intel frost-intel added the topic: not user facing topic category label Jun 2, 2026
@frost-intel

Copy link
Copy Markdown
Collaborator Author

@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 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@frost-intel

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -i

@pytorch-bot

pytorch-bot Bot commented Jun 2, 2026

Copy link
Copy Markdown

-i flag is only allowed for users with write permissions

@frost-intel

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@frost-intel

Copy link
Copy Markdown
Collaborator Author

@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

gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Fixes a bug for non-CUDA devices introduced by pytorch#177728 due to a misused call to fork_rng

* Since the call to fork_rng should specify the device type, I specify this in `schedules.py`
* The design of fork_rng seems outdated since the adoption of non-CUDA devices. I change the signature so the device_type default argument is `None`, and is inferred from the passed devices. If it can't be inferred from the device list (because it's a list of ints, for example) we still fallback to the previous value of "cuda".

Pull Request resolved: pytorch#180512
Approved by: https://github.com/guangyey, https://github.com/albanD

Co-authored-by: Yu, Guangye <[email protected]>
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Fixes a bug for non-CUDA devices introduced by pytorch#177728 due to a misused call to fork_rng

* Since the call to fork_rng should specify the device type, I specify this in `schedules.py`
* The design of fork_rng seems outdated since the adoption of non-CUDA devices. I change the signature so the device_type default argument is `None`, and is inferred from the passed devices. If it can't be inferred from the device list (because it's a list of ints, for example) we still fallback to the previous value of "cuda".

Pull Request resolved: pytorch#180512
Approved by: https://github.com/guangyey, https://github.com/albanD

Co-authored-by: Yu, Guangye <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged open source topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants