Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion examples/stable_baselines3_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions godot_rl/core/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import importlib
import re
from typing import Optional

import gymnasium as gym
import numpy as np
Expand Down Expand Up @@ -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)

Expand Down
25 changes: 25 additions & 0 deletions tests/test_torch_threads.py
Original file line number Diff line number Diff line change
@@ -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)