From 838881c51f4cf2704fbd31a95152ab198e508918 Mon Sep 17 00:00:00 2001 From: meilame-tayebjee Date: Mon, 23 Nov 2026 18:28:31 +0000 Subject: [PATCH] fix(dataset): size default num_workers from available CPUs, not os.cpu_count() os.cpu_count() reports every CPU of the host, ignoring cgroup quotas and CPU affinity. In containers (Kubernetes/Onyxia, Docker, SLURM) the old default `os.cpu_count() - 1` could spawn >100 DataLoader worker processes and exhaust the container memory. - add utilities/resources.py: available_cpu_count() (min of host count, sched_getaffinity, cgroup v2 cpu.max / v1 cfs quota) and default_num_workers() = available - 1, capped at 8 - create_dataloader() and TrainingConfig now default to num_workers=None, resolved at call time (previously evaluated at import / hardcoded 12) - test_pipeline uses num_workers=0 - unit tests fake cgroup files; they never start worker processes Co-Authored-By: Claude Opus 5.5 --- docs/source/api/configs.rst | 6 +- tests/test_pipeline.py | 3 +- tests/test_resources.py | 111 +++++++++++++++++++ torchTextClassifiers/dataset/dataset.py | 10 +- torchTextClassifiers/torchTextClassifiers.py | 3 +- torchTextClassifiers/utilities/resources.py | 83 ++++++++++++++ 6 files changed, 210 insertions(+), 6 deletions(-) create mode 100644 tests/test_resources.py create mode 100644 torchTextClassifiers/utilities/resources.py diff --git a/docs/source/api/configs.rst b/docs/source/api/configs.rst index 0e8b5a4..b0812d9 100644 --- a/docs/source/api/configs.rst +++ b/docs/source/api/configs.rst @@ -125,9 +125,11 @@ Configuration for training process. Accelerator type: "auto", "cpu", "gpu", or "mps" (default: "auto"). .. attribute:: num_workers - :type: int + :type: Optional[int] - Number of data loading workers (default: 12). + Number of data loading workers. Default (``None``): number of CPUs actually + available to the process minus one (taking cgroup CPU quotas and CPU affinity + into account, so containers are sized correctly), capped at 8. .. attribute:: patience_early_stopping :type: int diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 810fbaa..eca3831 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -118,7 +118,7 @@ def run_full_pipeline( labels=None, ) - dataloader = dataset.create_dataloader(batch_size=4) + dataloader = dataset.create_dataloader(batch_size=4, num_workers=0) batch = next(iter(dataloader)) # Get tokenizer parameters @@ -215,6 +215,7 @@ def run_full_pipeline( lr=1e-3, batch_size=4, num_epochs=1, + num_workers=0, ) # Create classifier — pass the fitted value encoder diff --git a/tests/test_resources.py b/tests/test_resources.py new file mode 100644 index 0000000..5815c79 --- /dev/null +++ b/tests/test_resources.py @@ -0,0 +1,111 @@ +"""Tests for CPU-quota-aware sizing of DataLoader workers. + +These tests only fake cgroup files and monkeypatch CPU counts: they never spawn +DataLoader worker processes. +""" + +import os + +import numpy as np +import pytest + +from torchTextClassifiers.utilities import resources +from torchTextClassifiers.utilities.resources import ( + _cgroup_cpu_limit, + available_cpu_count, + default_num_workers, +) + + +@pytest.fixture +def big_host(monkeypatch): + """Simulate a 128-CPU host with no affinity restriction.""" + monkeypatch.setattr(os, "cpu_count", lambda: 128) + monkeypatch.setattr(os, "sched_getaffinity", lambda pid: set(range(128)), raising=False) + + +def test_cgroup_v2_quota(tmp_path): + (tmp_path / "cpu.max").write_text("1500000 100000\n") + assert _cgroup_cpu_limit(tmp_path) == 15 + + +def test_cgroup_v2_fractional_quota_rounds_up(tmp_path): + (tmp_path / "cpu.max").write_text("50000 100000\n") + assert _cgroup_cpu_limit(tmp_path) == 1 + + +def test_cgroup_v2_unlimited(tmp_path): + (tmp_path / "cpu.max").write_text("max 100000\n") + assert _cgroup_cpu_limit(tmp_path) is None + + +def test_cgroup_v1_quota(tmp_path): + cpu = tmp_path / "cpu,cpuacct" + cpu.mkdir() + (cpu / "cpu.cfs_quota_us").write_text("400000\n") + (cpu / "cpu.cfs_period_us").write_text("100000\n") + assert _cgroup_cpu_limit(tmp_path) == 4 + + +def test_cgroup_v1_unlimited(tmp_path): + cpu = tmp_path / "cpu" + cpu.mkdir() + (cpu / "cpu.cfs_quota_us").write_text("-1\n") + (cpu / "cpu.cfs_period_us").write_text("100000\n") + assert _cgroup_cpu_limit(tmp_path) is None + + +def test_no_cgroup_files(tmp_path): + assert _cgroup_cpu_limit(tmp_path) is None + + +def test_available_cpu_count_uses_cgroup_quota(tmp_path, big_host): + (tmp_path / "cpu.max").write_text("1500000 100000\n") + assert available_cpu_count(tmp_path) == 15 + + +def test_available_cpu_count_uses_affinity(tmp_path, big_host, monkeypatch): + monkeypatch.setattr(os, "sched_getaffinity", lambda pid: {0, 1, 2}, raising=False) + assert available_cpu_count(tmp_path) == 3 + + +def test_available_cpu_count_falls_back_to_cpu_count(tmp_path, monkeypatch): + monkeypatch.setattr(os, "cpu_count", lambda: None) + monkeypatch.delattr(os, "sched_getaffinity", raising=False) + assert available_cpu_count(tmp_path) == 1 + + +@pytest.mark.parametrize("cpus, expected", [(1, 0), (2, 1), (4, 3), (15, 8), (128, 8)]) +def test_default_num_workers(monkeypatch, cpus, expected): + monkeypatch.setattr(resources, "available_cpu_count", lambda: cpus) + assert default_num_workers() == expected + + +def test_create_dataloader_default_is_quota_aware(monkeypatch, sample_text_data): + """The DataLoader default no longer derives from os.cpu_count().""" + from torchTextClassifiers.dataset import dataset as dataset_module + from torchTextClassifiers.dataset.dataset import TextClassificationDataset + from torchTextClassifiers.tokenizers import NGramTokenizer + + monkeypatch.setattr(os, "cpu_count", lambda: 128) + monkeypatch.setattr(dataset_module, "default_num_workers", lambda: 0) + + tokenizer = NGramTokenizer( + min_count=1, min_n=2, max_n=4, num_tokens=50, len_word_ngrams=2, output_dim=20 + ) + tokenizer.train(list(sample_text_data)) + ds = TextClassificationDataset( + texts=list(sample_text_data), + categorical_variables=None, + tokenizer=tokenizer, + labels=np.zeros(len(sample_text_data), dtype=int).tolist(), + ) + loader = ds.create_dataloader(batch_size=2) # not iterated: no worker is started + assert loader.num_workers == 0 + assert loader.persistent_workers is False + + +def test_training_config_default_num_workers_is_none(): + from torchTextClassifiers import TrainingConfig + + assert TrainingConfig(num_epochs=1, batch_size=2, lr=1e-3).num_workers is None diff --git a/torchTextClassifiers/dataset/dataset.py b/torchTextClassifiers/dataset/dataset.py index 44a1254..a521403 100644 --- a/torchTextClassifiers/dataset/dataset.py +++ b/torchTextClassifiers/dataset/dataset.py @@ -1,12 +1,13 @@ import logging import os -from typing import List, Union +from typing import List, Optional, Union import numpy as np import torch from torch.utils.data import DataLoader, Dataset from torchTextClassifiers.tokenizers import BaseTokenizer +from torchTextClassifiers.utilities.resources import default_num_workers os.environ["TOKENIZERS_PARALLELISM"] = "false" logger = logging.getLogger(__name__) @@ -145,11 +146,16 @@ def create_dataloader( batch_size: int, shuffle: bool = False, drop_last: bool = False, - num_workers: int = os.cpu_count() - 1, + num_workers: Optional[int] = None, pin_memory: bool = False, persistent_workers: bool = True, **kwargs, ): + # None -> sized from the CPUs actually available (cgroup quota / affinity), + # not os.cpu_count(), which reports all host CPUs inside containers. + if num_workers is None: + num_workers = default_num_workers() + # persistent_workers requires num_workers > 0 if num_workers == 0: persistent_workers = False diff --git a/torchTextClassifiers/torchTextClassifiers.py b/torchTextClassifiers/torchTextClassifiers.py index cc0fdc4..a850338 100644 --- a/torchTextClassifiers/torchTextClassifiers.py +++ b/torchTextClassifiers/torchTextClassifiers.py @@ -80,7 +80,8 @@ class TrainingConfig: optimizer: Type[torch.optim.Optimizer] = torch.optim.Adam scheduler: Optional[Type[torch.optim.lr_scheduler._LRScheduler]] = None accelerator: str = "auto" - num_workers: int = 12 + # None: available CPUs (cgroup quota / affinity aware) - 1, capped at 8 + num_workers: Optional[int] = None patience_early_stopping: int = 3 dataloader_params: Optional[dict] = None trainer_params: Optional[dict] = None diff --git a/torchTextClassifiers/utilities/resources.py b/torchTextClassifiers/utilities/resources.py new file mode 100644 index 0000000..f6eeb52 --- /dev/null +++ b/torchTextClassifiers/utilities/resources.py @@ -0,0 +1,83 @@ +"""Helpers to size parallelism from the CPUs actually available to the process. + +``os.cpu_count()`` reports the CPUs of the whole host. In containers (Kubernetes, +Docker, Onyxia, SLURM jobs...) the process is usually restricted by a cgroup CPU +quota or a CPU affinity mask, so using ``os.cpu_count()`` to size DataLoader +workers can spawn far more processes than the container can afford (each worker +being a full Python process, this can exhaust the container memory). +""" + +import math +import os +from pathlib import Path +from typing import Optional, Union + +# Each DataLoader worker is a separate process holding its own copy of the +# dataset/tokenizer: keep the default bounded, even on large machines. +MAX_DEFAULT_NUM_WORKERS = 8 + +_CGROUP_ROOT = Path("/sys/fs/cgroup") + + +def _read(path: Path) -> Optional[str]: + try: + return path.read_text().strip() + except (OSError, ValueError): + return None + + +def _cgroup_cpu_limit(cgroup_root: Union[str, Path] = _CGROUP_ROOT) -> Optional[int]: + """CPU limit from the cgroup quota (v2 then v1), or None if unlimited/unknown.""" + root = Path(cgroup_root) + + # cgroup v2: " " or "max " + content = _read(root / "cpu.max") + if content: + parts = content.split() + if len(parts) == 2 and parts[0] != "max": + try: + quota, period = int(parts[0]), int(parts[1]) + if quota > 0 and period > 0: + return max(1, math.ceil(quota / period)) + except ValueError: + pass + + # cgroup v1: quota is -1 when unlimited + for cpu_dir in ("cpu", "cpu,cpuacct"): + quota = _read(root / cpu_dir / "cpu.cfs_quota_us") + period = _read(root / cpu_dir / "cpu.cfs_period_us") + if quota and period: + try: + q, p = int(quota), int(period) + except ValueError: + continue + if q > 0 and p > 0: + return max(1, math.ceil(q / p)) + + return None + + +def available_cpu_count(cgroup_root: Union[str, Path] = _CGROUP_ROOT) -> int: + """Number of CPUs this process can actually use. + + Takes the minimum of the host CPU count, the CPU affinity mask and the cgroup + CPU quota (v1 or v2). Always returns at least 1. + """ + counts = [os.cpu_count() or 1] + + if hasattr(os, "sched_getaffinity"): + try: + counts.append(len(os.sched_getaffinity(0))) + except OSError: + pass + + cgroup_limit = _cgroup_cpu_limit(cgroup_root) + if cgroup_limit is not None: + counts.append(cgroup_limit) + + return max(1, min(counts)) + + +def default_num_workers(max_workers: int = MAX_DEFAULT_NUM_WORKERS) -> int: + """Default number of DataLoader workers: available CPUs - 1, capped at ``max_workers``.""" + return max(0, min(available_cpu_count() - 1, max_workers))