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)