lightning¶
HydraDDP ¶
DDP Strategy that supports Hydra run and multirun jobs.
This strategy assumes a PyTorch Lightning Trainer.fit or Trainer.test has been configured
to execute via Hydra. It requires that Hydra saves a config.yaml in the job's
output directory (hydra.runtime.output_dir, under hydra.output_subdir)
with the following keys/properties set::
├── Config
│ ├── trainer: A pytorch_lightning.Trainer configuration
│ ├── module: A pytorch_lightning.LightningModule configuration
│ ├── datamodule: [OPTIONAL] A pytorch_lightning.LightningDataModule configuration
This strategy will launch a child subprocesses for additional GPU beyond the first using the following base command::
python -m mushin.lightning._pl_main -cp
Examples:
First define a Hydra configuration using hydra-zen:
>>> import pytorch_lightning as pl
... from hydra_zen import builds, make_config
... from mushin import HydraDDP
... from mushin.testing.lightning import SimpleLightningModule
...
... TrainerConfig = builds(
... pl.Trainer,
... accelerator="gpu",
... devices=2,
... max_epochs=1,
... fast_dev_run=True,
... strategy=builds(HydraDDP),
... populate_full_signature=True
... )
...
... ModuleConfig = builds(SimpleLightningModule)
...
... Config = make_config(
... trainer=TrainerConfig,
... module=ModuleConfig
... )
Next, define a task function to execute the Hydra job:
>>> from hydra_zen import instantiate
>>> def task_function(cfg):
... obj = instantiate(cfg)
... obj.trainer.fit(obj.module)
Launch the Hydra+Lightning DDP job
HydraDDP also supports LightningDataModule configuration.
>>> DataModuleConfig = ... # A LightningDataModule config
>>> Config = make_config(
... trainer=TrainerConfig,
... module=ModuleConfig
... datamodule=DataModuleconfig
... )
Next define a task function to execute the Hydra job:
>>> from hydra_zen import instantiate
>>> def task_function(cfg):
... obj = instantiate(cfg)
... obj.trainer.fit(obj.module, datamodule=obj.datamodule)
Launch the Hydra+Lightning DDP job:
HydraFSDP ¶
Fully-Sharded Data Parallel strategy that works under Hydra --multirun.
Like HydraDDP, but for sharded training: it replaces Lightning's
stock FSDPStrategy subprocess launcher (which re-execs the script with
sys.argv and, in a sweep, spawns the wrong job) with mushin's launcher,
which reattaches each rank via the job's saved config.yaml. FSDP shards
parameters/gradients/optimizer state across ranks; mushin's results and
significance analysis are unchanged from a single-GPU run.
Requires Hydra to save a config.yaml (with trainer and module
keys) in the job's output dir: the same contract as HydraDDP.
Configure it with hydra-zen, e.g. strategy=builds(HydraFSDP) on a
builds(pl.Trainer, ...) config.
MetricsCallback ¶
Bases: Callback
Saves validation and test metrics stored in trainer.callback_metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_dir
|
(str, optional(default='.'))
|
|
'.'
|
filename
|
(str, optional(default=pt))
|
The base filename used to store metrics. For |
'metrics.pt'
|
Notes
No metrics will be saved during FITTING if no validation metrics are calculated.
This is a limitation of PyTorch Lightning. Future versions will save the training
step metrics when no validation metrics are calculated.
Examples:
Clusters and GPUs¶
Helpers for multi-process runs: seeding per rank, a SLURM launcher config for multi-node jobs, and pinning small jobs to one GPU each. The multi-node and packing guides show when to use them.
seed_everything_per_rank ¶
Seed each process with base + global_rank so a multi-GPU/-node run is as
reproducible as a single-GPU run (each rank gets a distinct but deterministic
seed). Reads the global rank from RANK (preferred), SLURM_PROCID,
LOCAL_RANK (single-node), or SUBMITIT_LOCAL_GLOBALID (a task of a
submitit_local job of several), defaulting to 0. Returns the seed
used.
submitit_slurm_config ¶
submitit_slurm_config(
*,
nodes,
gpus_per_node,
cpus_per_task=1,
partition=None,
timeout_min=60,
mem_gb=None,
**extra,
)
Build a hydra-submitit-launcher SLURM config for multi-node DDP.
tasks_per_node is derived as gpus_per_node so the two can never desync
(DDP needs one SLURM task per GPU). Returns a plain dict. Pass it to
run(launcher="submitit_slurm", launcher_config=...) (see the multi-node
guide); it submits nothing. Extra keyword args (e.g. account, qos,
constraint) pass through verbatim, including preemption knobs such as
signal_delay_s (grace signal before the kill, time to checkpoint) and
additional_parameters={"requeue": True} for SLURM auto-requeue.
pin_gpu_round_robin ¶
Pin this process to a single GPU (round-robin) via CUDA_VISIBLE_DEVICES.
Call this at the TOP of your task function, before any CUDA use (importing
torch is fine; the first CUDA op is not). It maps a job to one physical GPU
with job_index % num_gpus and returns that round-robin slot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_gpus
|
int
|
Number of physical GPUs to spread jobs across (must be >= 1). If
|
required |
job_index
|
int or None
|
The job's index. Defaults to the current Hydra sweep index
( |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The round-robin slot |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If |
Notes
This only maps a job to a device. Running num_gpus * jobs_per_gpu jobs
concurrently (so jobs_per_gpu land on each GPU) is set by your launcher,
e.g. hydra.launcher.n_jobs. Placement does not change results, only
scheduling.
Each job must run in a fresh process: once CUDA is initialized, its visible devices are fixed, so a reused worker keeps the first job's GPU. If your launcher reuses workers across jobs this raises rather than silently mispin; see the GPU-packing guide (Ray handles fractional-GPU packing without this constraint).