From bb3aa3d6d5b1f5075f83fe7449f75fec4d907d1d Mon Sep 17 00:00:00 2001 From: Eliasepfl Date: Wed, 5 Aug 2026 15:09:30 -0400 Subject: [PATCH] Add an option to cap the torch thread count Torch takes one intra op thread per core by default. Once several game instances run next to the learner, which is the point of --n_parallel, the machine is oversubscribed and the update step slows down badly. This is easy to miss because nothing fails, the run is just slow, and it gets worse the more cores the machine has. Adds set_torch_threads in core.utils and a --torch_num_threads flag to the sb3 example. Default is None so nothing changes unless the flag is used. The torch import stays inside the helper to keep core.utils free of it. --- examples/stable_baselines3_example.py | 12 +++++++++++- godot_rl/core/utils.py | 25 +++++++++++++++++++++++++ tests/test_torch_threads.py | 25 +++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 tests/test_torch_threads.py diff --git a/examples/stable_baselines3_example.py b/examples/stable_baselines3_example.py index 1c4e06af..ad5f8b91 100644 --- a/examples/stable_baselines3_example.py +++ b/examples/stable_baselines3_example.py @@ -7,7 +7,7 @@ from stable_baselines3.common.callbacks import CheckpointCallback from stable_baselines3.common.vec_env.vec_monitor import VecMonitor -from godot_rl.core.utils import can_import +from godot_rl.core.utils import can_import, set_torch_threads from godot_rl.wrappers.onnx.stable_baselines_export import export_model_as_onnx from godot_rl.wrappers.stable_baselines_wrapper import StableBaselinesGodotEnv @@ -134,9 +134,19 @@ type=float, help="The clipping range (default 0.2). This limits the policy changes per update", ) +parser.add_argument( + "--torch_num_threads", + default=None, + type=int, + help="Threads torch may use for intra op parallelism. Torch takes one per core by default, " + "which oversubscribes the machine once several game instances run next to the learner. " + "Try 1 when raising --n_parallel on a many core machine.", +) args, extras = parser.parse_known_args() +set_torch_threads(args.torch_num_threads) + def handle_onnx_export(): # Enforce the extension of onnx and zip when saving model to avoid potential conflicts in case of same name diff --git a/godot_rl/core/utils.py b/godot_rl/core/utils.py index f6d12afe..19926604 100644 --- a/godot_rl/core/utils.py +++ b/godot_rl/core/utils.py @@ -1,5 +1,6 @@ import importlib import re +from typing import Optional import gymnasium as gym import numpy as np @@ -133,6 +134,30 @@ def to_original_dist(self, action): return original_action +def set_torch_threads(num_threads: Optional[int]) -> Optional[int]: + """Limit the threads torch uses for intra op parallelism. + + Torch allocates one thread per core by default. With several game instances running + next to the learner this oversubscribes the machine and the learner update slows down + a lot, which is most visible on many core machines with a high --n_parallel. + + Args: + num_threads (int): thread count to apply, or None to leave torch alone. + + Returns: + int: the applied thread count, or None if nothing was changed. + """ + if num_threads is None: + return None + if num_threads < 1: + raise ValueError(f"num_threads must be 1 or more, got {num_threads}") + + import torch + + torch.set_num_threads(num_threads) + return num_threads + + def can_import(module_name): return not cant_import(module_name) diff --git a/tests/test_torch_threads.py b/tests/test_torch_threads.py new file mode 100644 index 00000000..27ebd5c0 --- /dev/null +++ b/tests/test_torch_threads.py @@ -0,0 +1,25 @@ +import pytest +import torch + +from godot_rl.core.utils import set_torch_threads + + +def test_none_leaves_torch_untouched(): + before = torch.get_num_threads() + assert set_torch_threads(None) is None + assert torch.get_num_threads() == before + + +def test_applies_the_requested_count(): + before = torch.get_num_threads() + try: + assert set_torch_threads(1) == 1 + assert torch.get_num_threads() == 1 + finally: + torch.set_num_threads(before) + + +@pytest.mark.parametrize("num_threads", [0, -1]) +def test_rejects_counts_below_one(num_threads): + with pytest.raises(ValueError): + set_torch_threads(num_threads)