Skip to content

Fix _find_device host overhead in tuple/dict recursion - #3283

Open
mengluy0125 wants to merge 1 commit into
pytorch:mainfrom
mengluy0125:export-D114780871
Open

Fix _find_device host overhead in tuple/dict recursion#3283
mengluy0125 wants to merge 1 commit into
pytorch:mainfrom
mengluy0125:export-D114780871

Conversation

@mengluy0125

Copy link
Copy Markdown
Contributor

Summary:
_find_device scans kernel arguments for a torch.device/torch.Tensor to determine the launch device, recursing into nested tuple/list/dict containers. The recursion passed each element directly as _find_device(item).

_find_device treats its argument as a tuple of args and iterates it (for arg in args). Passing a bare item that is itself a torch.Tensor made the recursive call iterate over the tensor (for arg in tensor), materializing the rows of the tensor on the host before the first row matched the isinstance(arg, torch.Tensor) check -- a real per-call host overhead on the hot argument-processing path. A 0-dim scalar tensor also fails to iterate at all.

Wrap the recursed element in a single-element tuple, _find_device((item,)), so the recursion sees exactly one arg and hits the torch.Tensor fast path directly. Behavior is unchanged for every previously-working case; the tensor is no longer iterated.

Differential Revision: D114780871

Summary:
`_find_device` scans kernel arguments for a `torch.device`/`torch.Tensor` to determine the launch device, recursing into nested `tuple`/`list`/`dict` containers. The recursion passed each element directly as `_find_device(item)`.

`_find_device` treats its argument as a tuple of args and iterates it (`for arg in args`). Passing a bare `item` that is itself a `torch.Tensor` made the recursive call iterate over the tensor (`for arg in tensor`), materializing the rows of the tensor on the host before the first row matched the `isinstance(arg, torch.Tensor)` check -- a real per-call host overhead on the hot argument-processing path. A 0-dim scalar tensor also fails to iterate at all.

Wrap the recursed element in a single-element tuple, `_find_device((item,))`, so the recursion sees exactly one arg and hits the `torch.Tensor` fast path directly. Behavior is unchanged for every previously-working case; the tensor is no longer iterated.

Differential Revision: D114780871
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 4, 2026
@meta-codesync

meta-codesync Bot commented Aug 4, 2026

Copy link
Copy Markdown

@mengluy0125 has exported this pull request. If you are a Meta employee, you can view the originating Diff in D114780871.

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

Labels

CLA Signed This label is managed by the Meta Open Source bot. meta-exported

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants