Skip to content

fix(threadx): give every device-pool worker its own intra-op team (#4356) - #4390

Merged
Qubitium merged 1 commit into
mainfrom
fix/4356-cpu-worker-openmp-teams
Nov 16, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/4356-cpu-worker-openmp-teams

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

TL;DR

DeviceThreadPool now assigns each worker thread its own Torch intra-op pool
size, taken from KernelConfig.pool_intraop_threads (None = split the
process budget across the pool's workers). libgomp gives every pthread that
enters a parallel region its own OpenMP team, so without this the pool
multiplied the process-wide team by its worker count.

Net change: 9 files, +276/-1. One new DeviceThreadPool keyword argument, one
new KernelConfig field, one regression test file extension, one reference page.

Measured on the same host and workload, before → after:

Workload Threads before Threads after
Default pool, 64 submitted CPU tasks (repro from the issue) 2622 308
2-layer GPTQ quantize() 2943 833

torch.get_num_threads() on the caller stays 206 in both cases.

Fixes #4356.

1. The problem

_default_cpu_workers() capped only the number of CPU workers
(gptqmodel/__init__.py:391). Nothing capped the team size, and worker
threads inherited the spawning thread's intra-op count.

flowchart TD
    A["main thread: torch.get_num_threads() = 206<br/>on a 320-CPU host"] --> B["_build_device_thread_pool()<br/>gptqmodel/__init__.py:420"]
    B --> C["DeviceThreadPool.__init__<br/>workers = {'cpu': 12, 'cuda:per': 4, ...}"]
    C --> D["12 x _DeviceWorker threads<br/>gptqmodel/utils/threadx.py"]
    D --> E["worker runs matmul"]
    E --> F["libgomp creates a team of 206<br/>for that pthread"]
    F --> G["12 x 206 + caller = 2622 OS threads"]
    style G fill:#fdd,stroke:#900
Loading

Mechanisms being removed:

Old mechanism Where it lived Why it was wrong
Worker count cap treated as the thread cap gptqmodel/__init__.py:399-405 (_default_cpu_workers) The comment says "cap CPU workers to avoid OpenMP team explosion", but team size is per-thread and untouched.
Worker inherits the spawning thread's intra-op count gptqmodel/utils/threadx.py:398 (_DeviceWorker), no set_num_threads anywhere in the pool Team size is materialized per pthread at the first parallel region, so inheritance multiplies.
Free-threading cap skipped when triton re-enables the GIL gptqmodel/__init__.py:401 (has_gil_disabled() guard) Orthogonal to team size; does not bound the pool either way.

A single torch.set_num_threads at import is not an option: import gptqmodel
deliberately does not change a user's global pool
(gptqmodel/utils/threads.py:79-99, docs/thread-caps.md).

2. The new flow

flowchart TD
    A["KernelConfig.pool_intraop_threads<br/>gptqmodel/utils/kernel.py:248"] --> B["_build_device_thread_pool()<br/>gptqmodel/__init__.py:419"]
    B --> C["DeviceThreadPool(intraop_threads_per_worker=...)<br/>gptqmodel/utils/threadx.py:739"]
    C --> D{"request is None?"}
    D -- yes --> E["count pool workers from the worker table<br/>threadx.py:906-920"]
    E --> F["split_intraop_threads(pool_workers, torch.get_num_threads())<br/>threadx.py:398"]
    D -- no --> G["use the explicit value<br/>(0 keeps the inherited pool)"]
    F --> H["self._intraop_threads_per_worker"]
    G --> H
    H --> I["_spawn_worker(intraop_threads=...)<br/>threadx.py:1243"]
    I --> J["_DeviceWorker thread start<br/>threadx.py:584 _apply_intraop_threads()"]
    J --> K{"torch.get_num_threads() == target?"}
    K -- yes --> L["no call"]
    K -- no --> M["torch.set_num_threads(target)<br/>before queue loop, warmup, first task"]
    M --> N["this pthread's team is `target`"]
    L --> N
    N --> O["caller pool unchanged<br/>(thread-local)"]
    style O fill:#dfd,stroke:#060
    style F fill:#dfd,stroke:#060
    style M fill:#dfd,stroke:#060
Loading

The order matters: _apply_intraop_threads() runs at threadx.py:584, above
the queue loop, so it precedes both the worker's warmup (_run_warmup()) and
its first task. The team is created on the first parallel region, so setting it
later would be a no-op.

split_intraop_threads() returns max(1, total // worker_count): a pool with
more workers than the process budget still gives each worker a valid team.

3. Contract

Situation Behaviour
intraop_threads_per_worker=None (default, and KernelConfig.pool_intraop_threads=None) split torch.get_num_threads() across this pool's workers
intraop_threads_per_worker=n, n > 0 every worker uses exactly n
intraop_threads_per_worker=0 (KernelConfig.pool_intraop_threads=0) workers keep the pool inherited from the spawning thread (pre-fix behaviour, explicit opt-in)
torch.set_num_threads raises logged once per worker, worker keeps the inherited value and keeps serving tasks
Caller's own pool never modified; the value is thread-local for the intra-op pool

The value is resolved once when the pool is built. A worker restart does not
re-resolve it, and a later torch.set_num_threads by the caller does not
propagate into existing workers.

4. Failure and ambiguity contract

stateDiagram-v2
    [*] --> Request: pool built
    Request --> Split: request is None
    Request --> Explicit: request > 0
    Request --> Inherit: request == 0
    Split --> Applied: split_intraop_threads >= 1
    Explicit --> Applied: set_num_threads(target)
    Inherit --> Inherit: no call (documented opt-out)
    Applied --> Applied: team bounded by target
    Applied --> InheritWarn: set_num_threads raised
    InheritWarn --> InheritWarn: warn once, tasks still run
    style InheritWarn fill:#fdd,stroke:#900
    style Inherit fill:#ffd,stroke:#990
Loading

5. Change inventory

Area File Purpose
Pool gptqmodel/utils/threadx.py split_intraop_threads(), intraop_threads_per_worker, _DeviceWorker._apply_intraop_threads()
Policy gptqmodel/utils/kernel.py KernelConfig.pool_intraop_threads (Optional[int], minimum 0)
Wiring gptqmodel/__init__.py default pool passes get_kernel_config().pool_intraop_threads
Tests tests/test_thread_caps.py split arithmetic, worker value, explicit override, 0 pass-through, KernelConfig wiring
Ledger pytorch_gil_0_compat.md torch.set_num_threads / get_num_threads row with measured result
Probe scripts/gil0_api_probe.py torch.set_num_threads (per worker) probe
Docs docs/device-thread-pool-intraop-budget.md (new), docs/thread-caps.md, docs/kernel-config.md, docs/README.md, README.md reference page + links

No environment variable is involved: the policy is a KernelConfig field, per
AGENTS.md and the direction of #4180.

6. Tests

Test Invariant
test_pool_workers_get_split_intraop_budget split_intraop_threads arithmetic, including the workers > budget floor of 1
test_device_thread_pool_workers_cap_their_own_intraop_team 4 workers on a budget of 8 all observe 2, and the caller still observes 8
test_device_thread_pool_explicit_worker_intraop_override intraop_threads_per_worker=1 is applied
test_device_thread_pool_can_keep_the_caller_intraop_pool 0 means "do not touch the worker's pool"
test_kernel_config_pool_intraop_threads_drives_the_default_pool _build_device_thread_pool() reads the policy for both 3 and 0
scripts/gil0_api_probe.py --only 'torch.set_num_threads (per worker)' GIL=0: the value is thread-local, inherited by threads the worker spawns, and never leaks to the caller

7. Validation

Run Result
Thread/telemetry/stream suites on CUDA: test_thread_caps, test_threadx, test_threadx_cpu, test_threadx_cpu_locks, test_threadx_shutdown, test_threadx_error_propagation, test_threadx_warmup_accounting, test_threadpoolctl, test_cpu_pin, test_excluded_device_warmup, test_linalg_warmup, test_quant_telemetry, test_stream, test_thread_pool_exit 103 passed, 3 skipped, 1 xpassed
Same suites on ROCm 70 passed, 2 skipped, 1 xpassed
GIL=0 probe, 3 subprocesses per backend PASS on CUDA and ROCm
tests/test_thread_caps.py with OMP_NUM_THREADS=8 9 passed (the file's own cap contract still holds)
ruff check on changed files clean
End-to-end 2-layer GPTQ quantize() + pool repro numbers in the TL;DR table

8. Reviewer notes

  • The residual growth in a real quantize() run (833) is dominated by the HF
    tokenizers rayon pool, which sizes itself independently of
    torch.set_num_threads. It is out of scope here and called out in the new
    docs page so the next reader does not attribute it to this pool.
  • _SyncWorker (the inline fallback used when threads are unsafe) is
    intentionally untouched: it runs on the caller's thread, so changing the
    intra-op count there would leak into the caller's own pool.
  • The value is resolved at pool construction, not per task. Re-resolving per
    task would let a quantize() that changes the caller's pool silently change
    worker teams mid-run, which is a larger behavioural change than this fix.

)

libgomp creates one OpenMP team per pthread that enters a parallel region,
sized from that thread's intra-op count. Device pool workers inherited the
spawning thread's count, so the pool multiplied the process-wide team: the
default pool on a 320-CPU host held 2622 OS threads for 64 submitted CPU
tasks, and a 2-layer GPTQ quantize() run held 2943. Capping the number of
workers does not bound the team size.

DeviceThreadPool now takes intraop_threads_per_worker and applies it once at
worker start, before the worker's first task or warmup, because that is when
the team is materialized. The default (None) splits torch.get_num_threads()
across the pool's worker count via split_intraop_threads(), which never
returns less than 1; 0 keeps the inherited pool. The value comes from
KernelConfig.pool_intraop_threads, not an environment variable.

Measured on the same host and workload: the isolated repro goes from 2622 to
308 threads and the quantize() run from 2943 to 833. The residual growth is
the tokenizer rayon pool, which torch.set_num_threads does not control.

torch.set_num_threads is thread-local for the intra-op pool, so the caller's
pool is untouched; the GIL=0 ledger row and probe
(scripts/gil0_api_probe.py --only 'torch.set_num_threads (per worker)') pin
that on CUDA and ROCm.

Fixes #4356
@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator Author

Note on the ruff-check job: it is already failing on the base commit
9b11fb3b0 with the same 13 findings (the code_quality.yml gate runs
format/check.sh over all of gptqmodel, docs/eora, tests and
setup.py). Comparing the --output-format=concise results of the base
checkout and this branch produces an identical set, so this PR introduces no
new lint finding.

The findings are in gptqmodel/looper/module_looper.py,
gptqmodel/looper/weight_only_looper.py, gptqmodel/models/loader.py,
gptqmodel/nn_modules/qlinear/paroquant_triton.py (F821
resolve_kernel_config), gptqmodel/quantization/qqq.py (unused import) and
seven import-order findings under tests/. They are outside this change and
are left for a separate fix so this PR stays reviewable on its own.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[PERF] Each DEVICE_THREAD_POOL CPU worker gets its own full-size OpenMP team: ~2.5k OS threads on a 320-CPU host

2 participants