Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

fix(device): keep PyTorch's default CPU thread count

FareedKhan-dev61b9fc9372c1
diff --git a/scripts/train_transformer.py b/scripts/train_transformer.py
index d224e47..f3c4b93 100644
--- a/scripts/train_transformer.py
+++ b/scripts/train_transformer.py
@@ -421,6 +421,8 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--lr", type=float, default=None, help="Learning rate (decayed 10x for the last 20%% of steps).")
parser.add_argument("--eval-every", type=int, default=None, help="Evaluate every N steps.")
parser.add_argument("--seed", type=int, default=None, help="Random seed for reproducible runs.")
+ parser.add_argument("--threads", type=int, default=None,
+ help="CPU threads (default: one per physical core). Fewer can be faster on hybrid CPUs.")
parser.add_argument("--sample", default=None,
help="Prompt to continue after training (the CPU presets use 'Once upon a time').")
parser.add_argument(
@@ -527,7 +529,7 @@ def main() -> None:
torch.manual_seed(args.seed)
np.random.seed(args.seed)
if train_config["device"] == "cpu":
- configure_cpu_threads()
+ configure_cpu_threads(args.threads)
if not args.preset and train_config["n_embed"] >= 2048:
print("Note: config/config.py describes a ~3B parameter model, far too big for a CPU. "
"Try --preset tiny (see config/presets.py).")
diff --git a/src/device.py b/src/device.py
index 04526d7..181988b 100644
--- a/src/device.py
+++ b/src/device.py
@@ -90,9 +90,15 @@ def sync_step(device: str) -> None:
def configure_cpu_threads(num_threads: int | None = None) -> int:
- """Use every physical core for CPU training unless the user set ``OMP_NUM_THREADS``."""
- if num_threads is None and "OMP_NUM_THREADS" not in os.environ:
- num_threads = os.cpu_count() or 1
+ """
+ Set how many CPU threads PyTorch uses, and return the number in use.
+
+ By default PyTorch's own choice is kept (one thread per physical core), which is usually
+ right: ``os.cpu_count()`` counts hyper-threads too, and running one thread per logical
+ core oversubscribes the cores and slows matrix multiplies down. On hybrid CPUs
+ (performance + efficiency cores) fewer threads, such as the number of performance cores,
+ can be faster; try a few values with ``scripts/benchmark.py --threads N``.
+ """
if num_threads:
torch.set_num_threads(num_threads)
return torch.get_num_threads()