# 有状态类

以下是[单例类](https://en.wikipedia.org/wiki/Singleton_pattern)的几种变体，其含义是所有实例共享同一状态，该状态在首次实例化时进行初始化。

这些类是不可变的，用于存储有关特定配置或状态的信息。

## PartialState[[accelerate.PartialState]]

#### accelerate.PartialState[[accelerate.PartialState]]

```python
accelerate.PartialState(cpu: bool = False, **kwargs)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L121)

**参数：**

cpu (`bool`, *可选*) : 是否强制脚本在 CPU 上执行。如果设置为 `True`，将忽略所有可用的加速器并强制在 CPU 上执行。

kwargs （额外的关键字参数，*可选*）：传递给相关 `init_process_group` 函数的额外关键字参数。有效的 `kwargs` 可在 [utils.InitProcessGroupKwargs](/docs/accelerate/main/zh/package_reference/kwargs#accelerate.InitProcessGroupKwargs) 中找到。有关详细用法，请参阅示例部分。

一个单例类，包含有关当前训练环境的信息以及用于辅助进程控制的功能。设计用于仅需进程控制和设备执行状态的场景。*无需*从 `Accelerator` 进行初始化。

**可用属性：**

- **device** (`torch.device`) -- 要使用的设备。
- **distributed_type** ([DistributedType](/docs/accelerate/main/zh/package_reference/utilities#accelerate.DistributedType)) -- 当前正在使用的分布式环境类型。
- **local_process_index** (`int`) -- 当前进程在当前服务器上的索引。
- **mixed_precision** (`str`) -- 当前脚本是否使用混合精度，如果使用，则指定混合精度的类型。（可选值：'no'、'fp16'、'bf16' 或 'fp8'）。
- **num_processes** (`int`) -- 当前并行启动的进程数量。
- **process_index** (`int`) -- 当前进程的索引。
- **is_last_process** (`bool`) -- 当前进程是否为最后一个进程。
- **is_main_process** (`bool`) -- 当前进程是否为主进程。
- **is_local_main_process** (`bool`) -- 当前进程是否为本地节点上的主进程。
- **debug** (`bool`) -- 当前脚本是否以调试模式运行。

示例：
```python
from accelerate.utils import InitProcessGroupKwargs

# To include `InitProcessGroupKwargs`, init then call `.to_kwargs()`
kwargs = InitProcessGroupKwargs(...).to_kwargs()
state = PartialState(**kwargs)
```

#### destroy_process_group[[accelerate.PartialState.destroy_process_group]]

```python
destroy_process_group(group = None)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L806)

销毁进程组。如果未指定，则销毁默认进程组。

#### local_main_process_first[[accelerate.PartialState.local_main_process_first]]

```python
local_main_process_first()
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L536)

让本地主进程进入 with 块。

其他进程将在主进程退出后进入 with 代码块。

示例：

```python
>>> 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}")
```

#### main_process_first[[accelerate.PartialState.main_process_first]]

```python
main_process_first()
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L515)

让主进程在 with 块中优先执行。

其他进程将在主进程退出后进入 with 代码块。

示例：

```python
>>> 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[[accelerate.PartialState.on_last_process]]

```python
on_last_process(function: Callable[..., Any])
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L618)

**参数：**

function (`Callable`) : 要装饰的函数。

仅在最后一个进程上运行被装饰函数的装饰器。

示例：
```python
# Assume we have 4 processes.
from accelerate.state import PartialState

state = PartialState()

@state.on_last_process
def print_something():
    print(f"Printed on process {state.process_index}")

print_something()
"Printed on process 3"
```

#### on_local_main_process[[accelerate.PartialState.on_local_main_process]]

```python
on_local_main_process(function: Callable[..., Any] | None = None)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L587)

**参数：**

function (`Callable`) : 要装饰的函数。

仅在本地主进程上运行被装饰函数的装饰器。

示例：
```python
# 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[[accelerate.PartialState.on_local_process]]

```python
on_local_process(function: Callable[..., Any] | None = None, local_process_index: int | None = None)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L679)

**参数：**

function (`Callable`，*可选*)：要装饰的函数。

local_process_index (`int`, *可选*) : 用于运行该函数的本地进程的索引。

一个装饰器，仅在当前节点上具有指定索引的进程上运行被装饰的函数。

示例：
```python
# 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[[accelerate.PartialState.on_main_process]]

```python
on_main_process(function: Callable[..., Any] | None = None)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L557)

**参数：**

function (`Callable`) : 要装饰的函数。

仅在主进程上运行被装饰函数的装饰器。

示例：

```python
>>> from accelerate.state import PartialState

>>> state = PartialState()

>>> @state.on_main_process
... def print_something():
...     print("This will be printed by process 0 only.")

>>> print_something()
"This will be printed by process 0 only"
```

#### on_process[[accelerate.PartialState.on_process]]

```python
on_process(function: Callable[..., Any] | None = None, process_index: int | None = None)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L646)

**参数：**

function (`Callable`，`optional`)：要装饰的函数。

process_index (`int`, `optional`) : 用于运行该函数的进程的索引。

仅在有给定索引的进程上运行被装饰函数的装饰器。

示例：
```python
# Assume we have 4 processes.
from accelerate.state import PartialState

state = PartialState()

@state.on_process(process_index=2)
def print_something():
    print(f"Printed on process {state.process_index}")

print_something()
"Printed on process 2"
```

#### set_device[[accelerate.PartialState.set_device]]

```python
set_device()
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L778)

将 `self.device` 中的设备设置为当前分布式环境。

#### split_between_processes[[accelerate.PartialState.split_between_processes]]

```python
split_between_processes(inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L423)

**参数：**

inputs (`list`、`tuple`、`torch.Tensor`、`dict`（其值为 `list`/`tuple`/`torch.Tensor`）或 `datasets.Dataset`)：需要在进程之间进行划分的数据。

apply_padding (`bool`, `optional`, 默认为 `False`) : 是否通过重复输入中的最后一个元素来进行填充，以便所有进程拥有相同数量的元素。当尝试对输出执行诸如 `gather()` 之类的操作，或传入的输入数量少于进程数量时，此选项非常有用。如果启用，请记得在之后丢弃填充的元素。

将 `input` 快速拆分到 `self.num_processes` 个进程之间，随后可在对应进程上使用。适用于分布式推理场景，例如处理不同的提示词。

请注意，当使用 `dict` 时，所有键都需要具有相同数量的元素。

示例：

```python
# 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"]
```

#### wait_for_everyone[[accelerate.PartialState.wait_for_everyone]]

```python
wait_for_everyone()
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L371)

将在当前进程的执行暂停，直到所有其他进程都到达该点（因此，当脚本仅在单个进程中运行时，此操作不会执行任何操作）。在保存模型之前使用此操作非常有用。

示例：

```python
>>> # 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")
```

## AcceleratorState[[accelerate.state.AcceleratorState]]

#### accelerate.state.AcceleratorState[[accelerate.state.AcceleratorState]]

```python
accelerate.state.AcceleratorState(mixed_precision: str | None = None, cpu: bool = False, dynamo_plugin = None, deepspeed_plugin = None, fsdp_plugin = None, torch_tp_plugin = None, megatron_lm_plugin = None, parallelism_config = None, _from_accelerator: bool = False, **kwargs)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L829)

包含当前训练环境信息的单例类。

**可用属性：**

- **device** (`torch.device`) -- 要使用的设备。
- **distributed_type** ([DistributedType](/docs/accelerate/main/zh/package_reference/utilities#accelerate.DistributedType)) -- 当前正在使用的分布式环境类型。
- **parallelism_config** (`ParallelismConfig`) -- 当前训练环境的并行配置。用于配置分布式训练环境。
- **initialized** (`bool`) -- `AcceleratorState` 是否已从 `Accelerator` 初始化。
- **local_process_index** (`int`) -- 当前进程在当前服务器上的索引。
- **mixed_precision** (`str`) -- 当前脚本是否使用混合精度，如果使用，则指定混合精度的类型。（可选值：'no'、'fp16'、'bf16' 或 'fp8'）。
- **num_processes** (`int`) -- 当前并行启动的进程数量。
- **process_index** (`int`) -- 当前进程的索引。
- **is_last_process** (`bool`) -- 当前进程是否为最后一个进程。
- **is_main_process** (`bool`) -- 当前进程是否为主进程。
- **is_local_main_process** (`bool`) -- 当前进程是否为本地节点上的主进程。
- **debug** (`bool`) -- 当前脚本是否以调试模式运行。

#### destroy_process_group[[accelerate.state.AcceleratorState.destroy_process_group]]

```python
destroy_process_group(group = None)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L1043)

销毁进程组。如果未指定，则销毁默认进程组。

如果 `self.fork_launched` 为 `True` 且 `group` 为 `None`，则不会执行任何操作。

#### get_deepspeed_plugin[[accelerate.state.AcceleratorState.get_deepspeed_plugin]]

```python
get_deepspeed_plugin(name: str)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L1160)

返回具有给定 plugin_key 的 DeepSpeedPlugin。

#### local_main_process_first[[accelerate.state.AcceleratorState.local_main_process_first]]

```python
local_main_process_first()
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L1136)

让本地主进程进入 with 块。

其他进程将在主进程退出后进入 with 代码块。

#### main_process_first[[accelerate.state.AcceleratorState.main_process_first]]

```python
main_process_first()
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L1126)

让主进程在 with 块中优先执行。

其他进程将在主进程退出后进入 with 代码块。

#### select_deepspeed_plugin[[accelerate.state.AcceleratorState.select_deepspeed_plugin]]

```python
select_deepspeed_plugin(name: str | None = None)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L1167)

使用给定的 `name` 激活 DeepSpeedPlugin，并禁用所有其他插件。

#### split_between_processes[[accelerate.state.AcceleratorState.split_between_processes]]

```python
split_between_processes(inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L1084)

**参数：**

inputs (`list`、`tuple`、`torch.Tensor`，或 `list`/`tuple`/`torch.Tensor` 的 `dict`)：需要在进程之间拆分的数据。

apply_padding (`bool`, `optional`, 默认为 `False`) : 是否通过重复输入中的最后一个元素来进行填充，以便所有进程拥有相同数量的元素。当尝试对输出执行诸如 `gather()` 之类的操作，或传入的输入数量少于进程数量时，此选项非常有用。如果启用，请记得在之后丢弃填充的元素。

将 `input` 快速拆分到 `self.num_processes` 个进程之间，随后可在对应进程上使用。适用于分布式推理场景，例如处理不同的提示词。

请注意，当使用 `dict` 时，所有键都需要具有相同数量的元素。

示例：

```python
# 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"]
```

## GradientState[[accelerate.state.GradientState]]

#### accelerate.state.GradientState[[accelerate.state.GradientState]]

```python
accelerate.state.GradientState(gradient_accumulation_plugin: GradientAccumulationPlugin | None = None)
```

[源代码](https://github.com/huggingface/accelerate/blob/main/src/accelerate/state.py#L1193)

包含与梯度累积的梯度同步相关信息的单例类

**可用属性：**

- **end_of_dataloader** (`bool`) -- 是否已到达当前数据加载器的末尾
- **remainder** (`int`) -- 通过填充数据加载器而额外添加的样本数量
- **sync_gradients** (`bool`) -- 是否应在所有设备之间同步梯度
- **active_dataloader** (`Optional[DataLoader]`) -- 当前正在迭代的 dataloader
- **dataloader_references** (`List[Optional[DataLoader]]`) -- 正在迭代的 dataloader 的引用列表
- **num_steps** (`int`) -- 需要累积的步数
- **adjust_scheduler** (`bool`) -- 是否应调整调度器以考虑梯度累积
- **sync_with_dataloader** (`bool`) -- 是否应在数据加载器迭代结束时同步梯度并重置总步数
- **is_xla_gradients_synced** (`bool`) -- XLA 梯度是否已同步。初始值为 false。在优化器步骤之前完成梯度归约后，此标志会被设置为 true。随后，在每次步骤之后，该标志会重置为 false。FSDP 始终会同步梯度，因此 is_xla_gradients_synced 始终为 true。

