Skip to content
Merged
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
6 changes: 4 additions & 2 deletions docs/source/api/configs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion tests/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
111 changes: 111 additions & 0 deletions tests/test_resources.py
Original file line number Diff line number Diff line change
@@ -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
10 changes: 8 additions & 2 deletions torchTextClassifiers/dataset/dataset.py
Original file line number Diff line number Diff line change
@@ -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__)
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion torchTextClassifiers/torchTextClassifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
83 changes: 83 additions & 0 deletions torchTextClassifiers/utilities/resources.py
Original file line number Diff line number Diff line change
@@ -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: "<quota> <period>" or "max <period>"
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))