Stateful Classes
Below are variations of a singleton class in the sense that all instances share the same state, which is initialized on the first instantiation.
These classes are immutable and store information about certain configurations or states.
class accelerate.PartialState
< source >( cpu: bool = False **kwargs )
Parameters
- cpu (
bool
, optional) — Whether or not to force the script to execute on CPU. Will ignore any accelerators available if set toTrue
and force the execution on the CPU. - kwargs (additional keyword arguments, optional) —
Additional keyword arguments to pass to the relevent
init_process_group
function. Validkwargs
can be found in utils.InitProcessGroupKwargs. See the example section for detailed usage.
Singleton class that has information about the current training environment and functions to help with process
control. Designed to be used when only process control and device execution states are needed. Does not need to
be initialized from Accelerator
.
Available attributes:
- device (
torch.device
) β The device to use. - distributed_type (DistributedType) β The type of distributed environment currently in use.
- local_process_index (
int
) β The index of the current process on the current server. - mixed_precision (
str
) β Whether or not the current script will use mixed precision, and if so the type of mixed precision being performed. (Choose from βnoβ,βfp16β,βbf16 or βfp8β). - num_processes (
int
) β The number of processes currently launched in parallel. - process_index (
int
) β The index of the current process. - is_last_process (
bool
) β Whether or not the current process is the last one. - is_main_process (
bool
) β Whether or not the current process is the main one. - is_local_main_process (
bool
) β Whether or not the current process is the main one on the local node. - debug (
bool
) β Whether or not the current script is being run in debug mode.
Example:
from accelerate.utils import InitProcessGroupKwargs
# To include `InitProcessGroupKwargs`, init then call `.to_kwargs()`
kwargs = InitProcessGroupKwargs(...).to_kwargs()
state = PartialState(**kwargs)
Destroys the process group. If one is not specified, the default process group is destroyed.
Lets the local main process go inside a with block.
The other processes will enter the with block after the main process exits.
Example:
>>> from accelerate.state import PartialState
>>> state = PartialState()
>>> with state.local_main_process_first():
... # This will be printed first by local process 0 then in a seemingly
... # random order by the other processes.
... print(f"This will be printed by process {state.local_process_index}")
Lets the main process go first inside a with block.
The other processes will enter the with block after the main process exits.
Example:
>>> from accelerate import Accelerator
>>> accelerator = Accelerator()
>>> with accelerator.main_process_first():
... # This will be printed first by process 0 then in a seemingly
... # random order by the other processes.
... print(f"This will be printed by process {accelerator.process_index}")
on_last_process
< source >( function: Callable[..., Any] )
Decorator that only runs the decorated function on the last process.
on_local_main_process
< source >( function: Callable[..., Any] = None )
Decorator that only runs the decorated function on the local main process.
Example:
# Assume we have 2 servers with 4 processes each.
from accelerate.state import PartialState
state = PartialState()
@state.on_local_main_process
def print_something():
print("This will be printed by process 0 only on each server.")
print_something()
# On server 1:
"This will be printed by process 0 only"
# On server 2:
"This will be printed by process 0 only"
on_local_process
< source >( function: Callable[..., Any] = None local_process_index: int = None )
Decorator that only runs the decorated function on the process with the given index on the current node.
Example:
# Assume we have 2 servers with 4 processes each.
from accelerate import Accelerator
accelerator = Accelerator()
@accelerator.on_local_process(local_process_index=2)
def print_something():
print(f"Printed on process {accelerator.local_process_index}")
print_something()
# On server 1:
"Printed on process 2"
# On server 2:
"Printed on process 2"
on_main_process
< source >( function: Callable[..., Any] = None )
Decorator that only runs the decorated function on the main process.
on_process
< source >( function: Callable[..., Any] = None process_index: int = None )
Decorator that only runs the decorated function on the process with the given index.
Sets the device in self.device
to the current distributed environment.
split_between_processes
< source >( inputs: list | tuple | dict | torch.Tensor apply_padding: bool = False )
Parameters
- inputs (
list
,tuple
,torch.Tensor
,dict
oflist
/tuple
/torch.Tensor
, ordatasets.Dataset
) — The input to split between processes. - apply_padding (
bool
,optional
, defaults toFalse
) — Whether to apply padding by repeating the last element of the input so that all processes have the same number of elements. Useful when trying to perform actions such asgather()
on the outputs or passing in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
Splits input
between self.num_processes
quickly and can be then used on that process. Useful when doing
distributed inference, such as with different prompts.
Note that when using a dict
, all keys need to have the same number of elements.
Example:
# Assume there are two processes
from accelerate import PartialState
state = PartialState()
with state.split_between_processes(["A", "B", "C"]) as inputs:
print(inputs)
# Process 0
["A", "B"]
# Process 1
["C"]
with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
print(inputs)
# Process 0
["A", "B"]
# Process 1
["C", "C"]
Will stop the execution of the current process until every other process has reached that point (so this does nothing when the script is only run in one process). Useful to do before saving a model.
Example:
>>> # Assuming two GPU processes
>>> import time
>>> from accelerate.state import PartialState
>>> state = PartialState()
>>> if state.is_main_process:
... time.sleep(2)
>>> else:
... print("I'm waiting for the main process to finish its sleep...")
>>> state.wait_for_everyone()
>>> # Should print on every process at the same time
>>> print("Everyone is here")
class accelerate.state.AcceleratorState
< source >( mixed_precision: str = None cpu: bool = False dynamo_plugin = None deepspeed_plugin = None fsdp_plugin = None megatron_lm_plugin = None _from_accelerator: bool = False **kwargs )
Singleton class that has information about the current training environment.
Available attributes:
- device (
torch.device
) β The device to use. - distributed_type (DistributedType) β The type of distributed environment currently in use.
- initialized (
bool
) β Whether or not theAcceleratorState
has been initialized fromAccelerator
. - local_process_index (
int
) β The index of the current process on the current server. - mixed_precision (
str
) β Whether or not the current script will use mixed precision, and if so the type of mixed precision being performed. (Choose from βnoβ,βfp16β,βbf16 or βfp8β). - num_processes (
int
) β The number of processes currently launched in parallel. - process_index (
int
) β The index of the current process. - is_last_process (
bool
) β Whether or not the current process is the last one. - is_main_process (
bool
) β Whether or not the current process is the main one. - is_local_main_process (
bool
) β Whether or not the current process is the main one on the local node. - debug (
bool
) β Whether or not the current script is being run in debug mode.
Destroys the process group. If one is not specified, the default process group is destroyed.
If self.fork_lauched
is True
and group
is None
, nothing happens.
Lets the local main process go inside a with block.
The other processes will enter the with block after the main process exits.
Lets the main process go first inside a with block.
The other processes will enter the with block after the main process exits.
split_between_processes
< source >( inputs: list | tuple | dict | torch.Tensor apply_padding: bool = False )
Parameters
- inputs (
list
,tuple
,torch.Tensor
, ordict
oflist
/tuple
/torch.Tensor
) — The input to split between processes. - apply_padding (
bool
,optional
, defaults toFalse
) — Whether to apply padding by repeating the last element of the input so that all processes have the same number of elements. Useful when trying to perform actions such asgather()
on the outputs or passing in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.
Splits input
between self.num_processes
quickly and can be then used on that process. Useful when doing
distributed inference, such as with different prompts.
Note that when using a dict
, all keys need to have the same number of elements.
Example:
# Assume there are two processes
from accelerate.state import AcceleratorState
state = AcceleratorState()
with state.split_between_processes(["A", "B", "C"]) as inputs:
print(inputs)
# Process 0
["A", "B"]
# Process 1
["C"]
with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
print(inputs)
# Process 0
["A", "B"]
# Process 1
["C", "C"]
class accelerate.state.GradientState
< source >( gradient_accumulation_plugin: Optional[GradientAccumulationPlugin] = None )
Singleton class that has information related to gradient synchronization for gradient accumulation
Available attributes:
- end_of_dataloader (
bool
) β Whether we have reached the end the current dataloader - remainder (
int
) β The number of extra samples that were added from padding the dataloader - sync_gradients (
bool
) β Whether the gradients should be synced across all devices - active_dataloader (
Optional[DataLoader]
) β The dataloader that is currently being iterated over - dataloader_references (
List[Optional[DataLoader]]
) β A list of references to the dataloaders that are being iterated over - num_steps (
int
) β The number of steps to accumulate over - adjust_scheduler (
bool
) β Whether the scheduler should be adjusted to account for the gradient accumulation - sync_with_dataloader (
bool
) β Whether the gradients should be synced at the end of the dataloader iteration and the number of total steps reset - is_xla_gradients_synced (
bool
) β Whether the XLA gradients have been synchronized. It is initialized as false. Once gradients have been reduced before the optimizer step, this flag is set to true. Subsequently, after each step, the flag is reset to false. FSDP will always synchronize the gradients, hence is_xla_gradients_synced is always true.