Skip to content

Commit 37ca86c

Browse files
committed
docs: update for Fabric
1 parent e55650d commit 37ca86c

File tree

1 file changed

+193
-48
lines changed

1 file changed

+193
-48
lines changed

src/lightning/fabric/fabric.py

Lines changed: 193 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -86,29 +86,49 @@ def _do_nothing(*_: Any) -> None:
8686
class Fabric:
8787
r"""Fabric accelerates your PyTorch training or inference code with minimal changes required.
8888
89-
- Automatic placement of models and data onto the device.
90-
- Automatic support for mixed and double precision (smaller memory footprint).
91-
- Seamless switching between hardware (CPU, GPU, TPU) and distributed training strategies
92-
(data-parallel training, sharded training, etc.).
93-
- Automated spawning of processes, no launch utilities required.
94-
- Multi-node support.
89+
Features:
90+
- Automatic placement of models and data onto the device.
91+
- Automatic support for mixed and double precision (smaller memory footprint).
92+
- Seamless switching between hardware (CPU, GPU, TPU) and distributed training strategies
93+
(data-parallel training, sharded training, etc.).
94+
- Automated spawning of processes, no launch utilities required.
95+
- Multi-node support.
9596
9697
Args:
9798
accelerator: The hardware to run on. Possible choices are:
9899
``"cpu"``, ``"cuda"``, ``"mps"``, ``"gpu"``, ``"tpu"``, ``"auto"``.
100+
Defaults to ``"auto"``.
99101
strategy: Strategy for how to run across multiple devices. Possible choices are:
100-
``"dp"``, ``"ddp"``, ``"ddp_spawn"``, ``"deepspeed"``, ``"fsdp"``.
102+
``"dp"``, ``"ddp"``, ``"ddp_spawn"``, ``"deepspeed"``, ``"fsdp"``, ``"auto"``.
103+
Defaults to ``"auto"``.
101104
devices: Number of devices to train on (``int``), which GPUs to train on (``list`` or ``str``), or ``"auto"``.
102-
The value applies per node.
103-
num_nodes: Number of GPU nodes for distributed training.
105+
The value applies per node. Defaults to ``"auto"``.
106+
num_nodes: Number of GPU nodes for distributed training. Defaults to ``1``.
104107
precision: Double precision (``"64"``), full precision (``"32"``), half precision AMP (``"16-mixed"``),
105-
or bfloat16 precision AMP (``"bf16-mixed"``).
106-
plugins: One or several custom plugins
108+
or bfloat16 precision AMP (``"bf16-mixed"``). If ``None``, defaults will be used based on the device.
109+
plugins: One or several custom plugins as a single plugin or list of plugins.
107110
callbacks: A single callback or a list of callbacks. A callback can contain any arbitrary methods that
108111
can be invoked through :meth:`~lightning.fabric.fabric.Fabric.call` by the user.
109112
loggers: A single logger or a list of loggers. See :meth:`~lightning.fabric.fabric.Fabric.log` for more
110113
information.
111114
115+
Example::
116+
117+
# Basic usage
118+
fabric = Fabric(accelerator="gpu", devices=2)
119+
120+
# Set up model and optimizer
121+
model = MyModel()
122+
optimizer = torch.optim.Adam(model.parameters())
123+
model, optimizer = fabric.setup(model, optimizer)
124+
125+
# Training loop
126+
for batch in dataloader:
127+
optimizer.zero_grad()
128+
loss = model(batch)
129+
fabric.backward(loss)
130+
optimizer.step()
131+
112132
"""
113133

114134
def __init__(
@@ -217,9 +237,9 @@ def setup(
217237
r"""Set up a model and its optimizers for accelerated training.
218238
219239
Args:
220-
module: A :class:`torch.nn.Module` to set up
221-
*optimizers: The optimizer(s) to set up (no optimizers is also possible)
222-
scheduler: The learning rate scheduler to set up (no learning rate scheduler is also possible)
240+
module: A :class:`torch.nn.Module` to set up.
241+
*optimizers: The optimizer(s) to set up. Can be zero or more optimizers.
242+
scheduler: An optional learning rate scheduler to set up. Must be provided after optimizers if used.
223243
move_to_device: If set ``True`` (default), moves the model to the correct device. Set this to ``False``
224244
and alternatively use :meth:`to_device` manually.
225245
_reapply_compile: If ``True`` (default), and the model was ``torch.compile``d before, the
@@ -228,8 +248,24 @@ def setup(
228248
FSDP etc.). Set it to ``False`` if compiling DDP/FSDP is causing issues.
229249
230250
Returns:
231-
The tuple containing wrapped module, optimizers, and an optional learning rate scheduler,
232-
in the same order they were passed in.
251+
If no optimizers are passed, returns the wrapped module. If optimizers are passed, returns a tuple
252+
containing the wrapped module and optimizers, and optionally the scheduler if provided, in the same
253+
order they were passed in.
254+
255+
Note:
256+
For certain strategies like FSDP, you may need to set up the model first using :meth:`setup_module`,
257+
then create the optimizer, and finally set up the optimizer using :meth:`setup_optimizers`.
258+
259+
Example::
260+
261+
# Basic usage
262+
model, optimizer = fabric.setup(model, optimizer)
263+
264+
# With multiple optimizers and scheduler
265+
model, opt1, opt2, scheduler = fabric.setup(model, opt1, opt2, scheduler=scheduler)
266+
267+
# Model only
268+
model = fabric.setup(model)
233269
234270
"""
235271
self._validate_setup(module, optimizers)
@@ -286,15 +322,25 @@ def setup_module(
286322
See also :meth:`setup_optimizers`.
287323
288324
Args:
289-
module: A :class:`torch.nn.Module` to set up
325+
module: A :class:`torch.nn.Module` to set up.
290326
move_to_device: If set ``True`` (default), moves the model to the correct device. Set this to ``False``
291327
and alternatively use :meth:`to_device` manually.
292328
_reapply_compile: If ``True`` (default), and the model was ``torch.compile``d before, the
293329
corresponding :class:`~torch._dynamo.OptimizedModule` wrapper will be removed and reapplied with the
294330
same settings after the model was set up by the strategy (e.g., after the model was wrapped by DDP,
295331
FSDP etc.). Set it to ``False`` if compiling DDP/FSDP is causing issues.
332+
296333
Returns:
297-
The wrapped model.
334+
The wrapped model as a :class:`~lightning.fabric.wrappers._FabricModule`.
335+
336+
Example::
337+
338+
# Set up model first (useful for FSDP)
339+
model = fabric.setup_module(model)
340+
341+
# Then create and set up optimizer
342+
optimizer = torch.optim.Adam(model.parameters())
343+
optimizer = fabric.setup_optimizers(optimizer)
298344
299345
"""
300346
self._validate_setup_module(module)
@@ -334,10 +380,26 @@ def setup_optimizers(self, *optimizers: Optimizer) -> Union[_FabricOptimizer, tu
334380
``.setup(model, optimizer, ...)`` instead to jointly set them up.
335381
336382
Args:
337-
*optimizers: One or more optimizers to set up.
383+
*optimizers: One or more optimizers to set up. Must provide at least one optimizer.
338384
339385
Returns:
340-
The wrapped optimizer(s).
386+
If a single optimizer is passed, returns the wrapped optimizer. If multiple optimizers are passed,
387+
returns a tuple of wrapped optimizers in the same order they were passed in.
388+
389+
Raises:
390+
RuntimeError: If using DeepSpeed or XLA strategies, which require joint model-optimizer setup.
391+
ValueError: If no optimizers are provided.
392+
393+
Note:
394+
This method cannot be used with DeepSpeed or XLA strategies. Use :meth:`setup` instead for those strategies.
395+
396+
Example::
397+
398+
# Single optimizer
399+
optimizer = fabric.setup_optimizers(optimizer)
400+
401+
# Multiple optimizers
402+
opt1, opt2 = fabric.setup_optimizers(opt1, opt2)
341403
342404
"""
343405
self._validate_setup_optimizers(optimizers)
@@ -355,7 +417,8 @@ def setup_dataloaders(
355417
dataloader, call this method individually for each one.
356418
357419
Args:
358-
*dataloaders: A single dataloader or a sequence of dataloaders.
420+
*dataloaders: One or more PyTorch :class:`~torch.utils.data.DataLoader` instances to set up.
421+
Must provide at least one dataloader.
359422
use_distributed_sampler: If set ``True`` (default), automatically wraps or replaces the sampler on the
360423
dataloader(s) for distributed training. If you have a custom sampler defined, set this argument
361424
to ``False``.
@@ -364,7 +427,16 @@ def setup_dataloaders(
364427
returned data.
365428
366429
Returns:
367-
The wrapped dataloaders, in the same order they were passed in.
430+
If a single dataloader is passed, returns the wrapped dataloader. If multiple dataloaders are passed,
431+
returns a list of wrapped dataloaders in the same order they were passed in.
432+
433+
Example::
434+
435+
# Single dataloader
436+
train_loader = fabric.setup_dataloaders(train_loader)
437+
438+
# Multiple dataloaders
439+
train_loader, val_loader = fabric.setup_dataloaders(train_loader, val_loader)
368440
369441
"""
370442
self._validate_setup_dataloaders(dataloaders)
@@ -410,18 +482,27 @@ def _setup_dataloader(
410482
return fabric_dataloader
411483

412484
def backward(self, tensor: Tensor, *args: Any, model: Optional[_FabricModule] = None, **kwargs: Any) -> None:
413-
r"""Replaces ``loss.backward()`` in your training loop. Handles precision and automatically for you.
485+
r"""Replaces ``loss.backward()`` in your training loop. Handles precision automatically for you.
414486
415487
Args:
416488
tensor: The tensor (loss) to back-propagate gradients from.
417489
*args: Optional positional arguments passed to the underlying backward function.
418-
model: Optional model instance for plugins that require the model for backward().
490+
model: Optional model instance for plugins that require the model for backward(). Required when using
491+
DeepSpeed strategy with multiple models.
419492
**kwargs: Optional named keyword arguments passed to the underlying backward function.
420493
421494
Note:
422495
When using ``strategy="deepspeed"`` and multiple models were set up, it is required to pass in the
423496
model as argument here.
424497
498+
Example::
499+
500+
loss = criterion(output, target)
501+
fabric.backward(loss)
502+
503+
# With DeepSpeed and multiple models
504+
fabric.backward(loss, model=model)
505+
425506
"""
426507
module = model._forward_module if model is not None else model
427508
module, _ = _unwrap_compiled(module)
@@ -459,17 +540,29 @@ def clip_gradients(
459540
Args:
460541
module: The module whose parameters should be clipped.
461542
optimizer: The optimizer referencing the parameters to be clipped.
462-
clip_val: If passed, gradients will be clipped to this value.
543+
clip_val: If passed, gradients will be clipped to this value. Cannot be used together with ``max_norm``.
463544
max_norm: If passed, clips the gradients in such a way that the p-norm of the resulting parameters is
464-
no larger than the given value.
465-
norm_type: The type of norm if `max_norm` was passed. Can be ``'inf'`` for infinity norm.
466-
Default is the 2-norm.
545+
no larger than the given value. Cannot be used together with ``clip_val``.
546+
norm_type: The type of norm if ``max_norm`` was passed. Can be ``'inf'`` for infinity norm.
547+
Defaults to 2-norm.
467548
error_if_nonfinite: An error is raised if the total norm of the gradients is NaN or infinite.
549+
Only applies when ``max_norm`` is used.
468550
469-
Return:
551+
Returns:
470552
The total norm of the gradients (before clipping was applied) as a scalar tensor if ``max_norm`` was
471553
passed, otherwise ``None``.
472554
555+
Raises:
556+
ValueError: If both ``clip_val`` and ``max_norm`` are provided, or if neither is provided.
557+
558+
Example::
559+
560+
# Clip by value
561+
fabric.clip_gradients(model, optimizer, clip_val=1.0)
562+
563+
# Clip by norm
564+
total_norm = fabric.clip_gradients(model, optimizer, max_norm=1.0)
565+
473566
"""
474567
if clip_val is not None and max_norm is not None:
475568
raise ValueError(
@@ -643,24 +736,37 @@ def no_backward_sync(self, module: _FabricModule, enabled: bool = True) -> Abstr
643736
r"""Skip gradient synchronization during backward to avoid redundant communication overhead.
644737
645738
Use this context manager when performing gradient accumulation to speed up training with multiple devices.
646-
647-
Example::
648-
649-
# Accumulate gradient 8 batches at a time
650-
with fabric.no_backward_sync(model, enabled=(batch_idx % 8 != 0)):
651-
output = model(input)
652-
loss = ...
653-
fabric.backward(loss)
654-
...
655-
656-
For those strategies that don't support it, a warning is emitted. For single-device strategies, it is a no-op.
657739
Both the model's ``.forward()`` and the ``fabric.backward()`` call need to run under this context.
658740
659741
Args:
660-
module: The module for which to control the gradient synchronization.
742+
module: The module for which to control the gradient synchronization. Must be a module that was
743+
set up with :meth:`setup` or :meth:`setup_module`.
661744
enabled: Whether the context manager is enabled or not. ``True`` means skip the sync, ``False`` means do not
662745
skip.
663746
747+
Returns:
748+
A context manager that controls gradient synchronization.
749+
750+
Raises:
751+
TypeError: If the module was not set up with Fabric first.
752+
753+
Note:
754+
For strategies that don't support gradient sync control, a warning is emitted and the context manager
755+
becomes a no-op. For single-device strategies, it is always a no-op.
756+
757+
Example::
758+
759+
# Accumulate gradients over 8 batches
760+
for batch_idx, batch in enumerate(dataloader):
761+
with fabric.no_backward_sync(model, enabled=(batch_idx % 8 != 0)):
762+
output = model(batch)
763+
loss = criterion(output, target)
764+
fabric.backward(loss)
765+
766+
if batch_idx % 8 == 0:
767+
optimizer.step()
768+
optimizer.zero_grad()
769+
664770
"""
665771
module, _ = _unwrap_compiled(module)
666772
if not isinstance(module, _FabricModule):
@@ -726,13 +832,28 @@ def save(
726832
This method must be called on all processes!
727833
728834
Args:
729-
path: A path to where the file(s) should be saved
835+
path: A path to where the file(s) should be saved.
730836
state: A dictionary with contents to be saved. If the dict contains modules or optimizers, their
731837
state-dict will be retrieved and converted automatically.
732838
filter: An optional dictionary containing filter callables that return a boolean indicating whether the
733839
given item should be saved (``True``) or filtered out (``False``). Each filter key should match a
734840
state key, where its filter will be applied to the ``state_dict`` generated.
735841
842+
Raises:
843+
TypeError: If filter is not a dictionary or contains non-callable values.
844+
ValueError: If filter keys don't match state keys.
845+
846+
Example::
847+
848+
state = {"model": model, "optimizer": optimizer, "epoch": epoch}
849+
fabric.save("checkpoint.pth", state)
850+
851+
# With filter
852+
def param_filter(name, param):
853+
return "bias" not in name # Save only non-bias parameters
854+
855+
fabric.save("checkpoint.pth", state, filter={"model": param_filter})
856+
736857
"""
737858
if filter is not None:
738859
if not isinstance(filter, dict):
@@ -759,7 +880,7 @@ def load(
759880
This method must be called on all processes!
760881
761882
Args:
762-
path: A path to where the file is located
883+
path: A path to where the file is located.
763884
state: A dictionary of objects whose state will be restored in-place from the checkpoint path.
764885
If no state is given, then the checkpoint will be returned in full.
765886
strict: Whether to enforce that the keys in `state` match the keys in the checkpoint.
@@ -768,6 +889,16 @@ def load(
768889
The remaining items that were not restored into the given state dictionary. If no state dictionary is
769890
given, the full checkpoint will be returned.
770891
892+
Example::
893+
894+
# Load full checkpoint
895+
checkpoint = fabric.load("checkpoint.pth")
896+
897+
# Load into existing objects
898+
state = {"model": model, "optimizer": optimizer}
899+
remainder = fabric.load("checkpoint.pth", state)
900+
epoch = remainder.get("epoch", 0)
901+
771902
"""
772903
unwrapped_state = _unwrap_objects(state)
773904
remainder = self._strategy.load_checkpoint(path=path, state=unwrapped_state, strict=strict)
@@ -805,18 +936,32 @@ def launch(self, function: Callable[["Fabric"], Any] = _do_nothing, *args: Any,
805936
Args:
806937
function: Optional function to launch when using a spawn/fork-based strategy, for example, when using the
807938
XLA strategy (``accelerator="tpu"``). The function must accept at least one argument, to which
808-
the Fabric object itself will be passed.
939+
the Fabric object itself will be passed. If not provided, only process initialization will be performed.
809940
*args: Optional positional arguments to be passed to the function.
810941
**kwargs: Optional keyword arguments to be passed to the function.
811942
812943
Returns:
813944
Returns the output of the function that ran in worker process with rank 0.
814945
815-
The ``launch()`` method should only be used if you intend to specify accelerator, devices, and so on in
816-
the code (programmatically). If you are launching with the Lightning CLI, ``fabric run ...``, remove
817-
``launch()`` from your code.
946+
Raises:
947+
RuntimeError: If called when script was launched through the CLI.
948+
TypeError: If function is provided but not callable, or if function doesn't accept required arguments.
949+
950+
Note:
951+
The ``launch()`` method should only be used if you intend to specify accelerator, devices, and so on in
952+
the code (programmatically). If you are launching with the Lightning CLI, ``fabric run ...``, remove
953+
``launch()`` from your code.
954+
955+
The ``launch()`` is a no-op when called multiple times and no function is passed in.
956+
957+
Example::
958+
959+
def train_function(fabric):
960+
model, optimizer = fabric.setup(model, optimizer)
961+
# ... training code ...
818962
819-
The ``launch()`` is a no-op when called multiple times and no function is passed in.
963+
fabric = Fabric(accelerator="tpu", devices=8)
964+
fabric.launch(train_function)
820965
821966
"""
822967
if _is_using_cli():

0 commit comments

Comments
 (0)