SIGN IN SIGN UP

Clamp default num_threads to cpuset/affinity mask (#194605)

When no explicit thread count is given, TaskThreadPoolBase::defaultNumThreads() derived the default from cpuinfo, which reports the host's topology (physical cores / processors) and ignores the calling process' CPU affinity mask. In a cpuset/taskset-restricted environment (e.g. a Kubernetes pod pinned to a subset
of cores) this makes PyTorch spawn as many threads as the host has cores, which is inefficient and under a tight ulimit on processes this fails at import with:
```
    libgomp: Thread creation failed: Resource temporarily unavailable
```

Fixes #193859

Test Plan:
Added test_cpuset_num_threads() to .ci/pytorch/test.sh (wired into the default
Linux test branch), which pins the process to a single CPU and asserts the
default thread count collapses to 1:

```
env -u OMP_NUM_THREADS -u MKL_NUM_THREADS taskset -c 0 python -c \
  'import torch; n = torch.get_num_threads(); assert n == 1, n'
```

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Pull Request resolved: https://github.com/pytorch/pytorch/pull/194605
Approved by: https://github.com/atalman, https://github.com/janeyx99
N
Nikita Shulga committed
7059aa341923e8d50a67679f971e0e12efca374d
Parent: e6f4d79
Committed by PyTorch MergeBot <pytorchmergebot@users.noreply.github.com> on 8/24/2026, 9:07:15 PM