# Fully Sharded Data Parallel 유틸리티

## enable_fsdp_ram_efficient_loading[[accelerate.utils.enable_fsdp_ram_efficient_loading]]

#### accelerate.utils.enable_fsdp_ram_efficient_loading[[accelerate.utils.enable_fsdp_ram_efficient_loading]]

```python
accelerate.utils.enable_fsdp_ram_efficient_loading()
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/fsdp_utils.py#L40)

환경에서 FSDP를 위한 Hugging Face 모델의 RAM 효율적 로딩을 활성화합니다.

## disable_fsdp_ram_efficient_loading[[accelerate.utils.disable_fsdp_ram_efficient_loading]]

#### accelerate.utils.disable_fsdp_ram_efficient_loading[[accelerate.utils.disable_fsdp_ram_efficient_loading]]

```python
accelerate.utils.disable_fsdp_ram_efficient_loading()
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/fsdp_utils.py#L50)

환경에서 FSDP를 위한 Hugging Face 모델의 RAM 효율적 로딩을 비활성화합니다.

## merge_fsdp_weights[[accelerate.utils.merge_fsdp_weights]]

#### accelerate.utils.merge_fsdp_weights[[accelerate.utils.merge_fsdp_weights]]

```python
accelerate.utils.merge_fsdp_weights(checkpoint_dir: str, output_path: str, safe_serialization: bool = True, remove_checkpoint_dir: bool = False)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/fsdp_utils.py#L486)

**매개변수:**

checkpoint_dir (`str`) : FSDP 체크포인트를 포함하는 디렉터리(모델 또는 옵티마이저일 수 있음).

output_path (`str`) : 병합된 체크포인트를 저장할 경로.

safe_serialization (`bool`, *선택 사항*, 기본값 `True`) : safetensors로 병합된 가중치를 저장할지 여부(권장).

remove_checkpoint_dir (`bool`, *선택 사항*, 기본값 `False`) : 병합 후 체크포인트 디렉토리를 제거할지 여부.

`SHARDED_STATE_DICT`을 사용하여 모델을 저장한 경우, 샤드된 FSDP 모델 체크포인트의 가중치를 하나의 통합 체크포인트로 병합합니다. `safe_serialization`가 True이면 가중치는 `{output_path}/model.safetensors`에, 그렇지 않으면 `pytorch_model.bin`에 저장됩니다.

참고: 이는 CPU-bound 프로세스입니다.

## FullyShardedDataParallelPlugin[[accelerate.FullyShardedDataParallelPlugin]]

#### accelerate.FullyShardedDataParallelPlugin[[accelerate.FullyShardedDataParallelPlugin]]

```python
accelerate.FullyShardedDataParallelPlugin(fsdp_version: int = None, sharding_strategy: str | ForwardRef('torch.distributed.fsdp.ShardingStrategy') = None, reshard_after_forward: str | ForwardRef('torch.distributed.fsdp.ShardingStrategy') | bool = None, backward_prefetch: str | ForwardRef('torch.distributed.fsdp.BackwardPrefetch') | None = None, mixed_precision_policy: dict | str | ForwardRef('torch.distributed.fsdp.MixedPrecision') | ForwardRef('torch.distributed.fsdp.MixedPrecisionPolicy') | None = None, auto_wrap_policy: typing.Callable | typing.Literal['transformer_based_wrap', 'size_based_wrap', 'no_wrap'] | None = None, cpu_offload: bool | ForwardRef('torch.distributed.fsdp.CPUOffload') | ForwardRef('torch.distributed.fsdp.CPUOffloadPolicy') = None, ignored_modules: collections.abc.Iterable[torch.nn.Module] | str | None = None, state_dict_type: str | ForwardRef('torch.distributed.fsdp.StateDictType') = None, state_dict_config: ForwardRef('torch.distributed.fsdp.FullStateDictConfig') | ForwardRef('torch.distributed.fsdp.ShardedStateDictConfig') | None = None, optim_state_dict_config: ForwardRef('torch.distributed.fsdp.FullOptimStateDictConfig') | ForwardRef('torch.distributed.fsdp.ShardedOptimStateDictConfig') | None = None, limit_all_gathers: bool = True, use_orig_params: bool | None = None, param_init_fn: typing.Callable[[torch.nn.Module], NoneType] | None = None, sync_module_states: bool | None = None, forward_prefetch: bool = None, activation_checkpointing: bool = None, activation_checkpointing_offload: bool = None, cpu_ram_efficient_loading: bool = None, transformer_cls_names_to_wrap: list[str] | None = None, min_num_params: int | None = None)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/dataclasses.py#L1465)

**매개변수:**

fsdp_version (`int`, 기본값 `1`) : 사용할 FSDP 버전입니다. 기본값은 1입니다. 2로 설정하면, launcher는 설정이 FSDP2 형식으로 변환되었기를 기대합니다.

sharding_strategy (`Union[str, torch.distributed.fsdp.ShardingStrategy]`, 기본값은 `'FULL_SHARD'`) : 사용할 Sharding 전략입니다. `str` 또는 `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy` 인스턴스여야 합니다. `reshard_after_forward` 사용을 권장하며 비권장(deprecated)되었습니다.

reshard_after_forward (`Union[str, torch.distributed.fsdp.ShardingStrategy, bool]`, `fsdp_version=1`의 경우 기본값은 `'FULL_SHARD'`, `fsdp_version=2`의 경우 기본값은 `True`) : 사용할 Sharding 전략입니다. `fsdp_version`이 2로 설정된 경우 bool이어야 하며, 그렇지 않은 경우 `str` 또는 `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`의 인스턴스여야 합니다.

backward_prefetch (`Union[str, torch.distributed.fsdp.BackwardPrefetch]`, 기본값은 `'NO_PREFETCH'`) : 사용할 Backward prefetch 전략입니다. `str` 또는 `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch` 인스턴스여야 합니다.

mixed_precision_policy (`Optional[Union[dict, str, torch.distributed.fsdp.MixedPrecision, torch.distributed.fsdp.MixedPrecisionPolicy]]`, 기본값은 `None`) : FullyShardedDataParallel을 사용하여 혼합 정밀도 훈련을 활성화하기 위한 설정입니다. `dict`를 전달하는 경우, 다음 키를 가져야 합니다: `param_dtype`, `reduce_dtype`, `buffer_dtype`. `fsdp_version`이 2로 설정된 경우 `torch.distributed.fsdp.MixedPrecisionPolicy`의 인스턴스일 수 있습니다. `str`을 전달하는 경우, 다음 값 중 하나여야 합니다: fp8, fp16, bf16, fp32. 이 값은 `param_dtype`, `reduce_dtype`, `buffer_dtype`을 설정하는 데 사용됩니다.

auto_wrap_policy (`Optional(Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]]), defaults to `NO_WRAP`) : A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. See `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like.

cpu_offload (`Union[bool, torch.distributed.fsdp.CPUOffload, torch.distributed.fsdp.CPUOffloadPolicy]`, 기본값은 `False`) : 매개변수를 CPU로 오프로드할지 여부입니다. `fsdp_version`이 2로 설정된 경우 `bool` 또는 `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload` 또는 `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffloadPolicy`의 인스턴스여야 합니다.

ignored_modules (`Optional[Union[Iterable[torch.nn.Module], str]]`, 기본값 `None`) : FSDP로 래핑할 때 무시할 모듈 목록입니다. 문자열을 전달하면 정규식 fullmatch를 사용하여 모듈 이름을 기준으로 일치시킵니다. `fsdp_version`이 2로 설정된 경우, 모듈은 파라미터로 변환되어 사용됩니다.

state_dict_type (`Union[str, torch.distributed.fsdp.StateDictType]`, 기본값은 `'FULL_STATE_DICT'`) : 사용할 state dict 유형입니다. 문자열인 경우 `full_state_dict`, `local_state_dict`, 또는 `sharded_state_dict` 중 하나여야 합니다.

state_dict_config (`Optional[Union[torch.distributed.fsdp.FullStateDictConfig, torch.distributed.fsdp.ShardedStateDictConfig]`, 기본값은 `None`) : 사용할 state dict config입니다. 전달되지 않으면 `state_dict_type`에 따라 결정됩니다.

optim_state_dict_config (`Optional[Union[torch.distributed.fsdp.FullOptimStateDictConfig, torch.distributed.fsdp.ShardedOptimStateDictConfig]`, 기본값은 `None`) : 사용할 Optim state dict config입니다. 전달되지 않으면 `state_dict_type`에 따라 결정됩니다.

limit_all_gathers (`bool`, 기본값은 `True`) : FSDP가 CPU 스레드를 명시적으로 동기화하여 과도한 in-flight all-gather를 방지할지 여부입니다. 이 bool은 all-gather를 스케줄링하는 sharded 전략에만 영향을 미칩니다. 이 옵션을 활성화하면 CUDA malloc 재시도 횟수를 줄이는 데 도움이 될 수 있습니다.

use_orig_params (`bool`, 기본값 `False`) : 옵티마이저에 원래 매개변수를 사용할지 여부.

param_init_fn (`Optional[Callable[[torch.nn.Module], None]`, 기본값은 `None`) : 현재 meta device에 있는 모듈이 실제 device로 초기화되는 방식을 지정하는 `Callable[torch.nn.Module] -> None`입니다. `sync_module_states`가 `True`인 경우에만 적용됩니다. 기본적으로 모듈에 `to_empty`를 호출하는 `lambda`입니다.

sync_module_states (`bool`, 기본값 `False`) : 초기화 후 모든 rank에서 모듈 파라미터가 동일하도록 보장하기 위해 개별적으로 래핑된 각 FSDP 유닛이 rank 0에서 모듈 파라미터를 브로드캐스트해야 하는지 여부입니다. `cpu_ram_efficient_loading`이 `True`가 아닌 한 기본값은 `False`이며, `cpu_ram_efficient_loading`이 `True`인 경우 강제로 활성화됩니다.

forward_prefetch (`bool`, 기본값 `False`) : FSDP가 forward pass 실행 중에 다음 all-gather를 명시적으로 미리 가져오도록 할지 여부입니다. Static graphs와 함께만 사용하세요.

activation_checkpointing (`bool`, 기본값은 `False`) : 특정 레이어의 activations를 해제하고 backward pass 중에 다시 계산하여 메모리 사용량을 줄이는 기법입니다. 실질적으로 추가적인 계산 시간을 희생하여 메모리 사용량을 줄이는 방식입니다.

cpu_ram_efficient_loading (`bool`, 기본값은 `None`) : True인 경우, 첫 번째 프로세스만 사전 학습된 모델 체크포인트를 로드하고 모든 다른 프로세스는 빈 가중치를 가집니다. Transformers에만 적용됩니다. 이 옵션을 사용할 때 `sync_module_states`는 `True`여야 합니다.

transformer_cls_names_to_wrap (`Optional[List[str]]`, 기본값 `None`) : 래핑할 transformer 레이어 클래스 이름 목록. `auto_wrap_policy`가 `transformer_based_wrap`인 경우에만 적용됩니다.

min_num_params (`Optional[int]`, 기본값 `None`) : 모듈이 래핑되려면 가져야 하는 최소 매개변수 수입니다. `auto_wrap_policy`가 `size_based_wrap`인 경우에만 적용됩니다.

이 플러그인은 완전 샤딩 데이터 병렬성을 활성화하는 데 사용됩니다.

#### set_auto_wrap_policy[[accelerate.FullyShardedDataParallelPlugin.set_auto_wrap_policy]]

```python
set_auto_wrap_policy(model)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/dataclasses.py#L1941)

`model`을 기반으로 전달된 정책에 따라 `auto_wrap_policy`를 생성하고, `transformer_cls_to_wrap`를 사용할 수 있는지 확인합니다.

#### set_mixed_precision[[accelerate.FullyShardedDataParallelPlugin.set_mixed_precision]]

```python
set_mixed_precision(mixed_precision, buffer_autocast = False, override = False)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/dataclasses.py#L1981)

FSDP의 혼합 정밀도 정책을 설정합니다

#### set_state_dict_type[[accelerate.FullyShardedDataParallelPlugin.set_state_dict_type]]

```python
set_state_dict_type(state_dict_type = None)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/dataclasses.py#L1896)

`StateDictType`에 따라 state dict 구성을 설정합니다.

#### validate_mixed_precision_policy[[accelerate.FullyShardedDataParallelPlugin.validate_mixed_precision_policy]]

```python
validate_mixed_precision_policy()
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/dataclasses.py#L2029)

필요하지 않을 경우 가져오기를 피하기 위해 추상화되어 있는 혼합 정밀도 정책을 검증합니다.

## fsdp2_load_full_state_dict[[accelerate.utils.fsdp2_load_full_state_dict]]

#### accelerate.utils.fsdp2_load_full_state_dict[[accelerate.utils.fsdp2_load_full_state_dict]]

```python
accelerate.utils.fsdp2_load_full_state_dict(accelerator, model: Module, full_sd: dict, cpu_offload: bool = False)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/fsdp_utils.py#L584)

**매개변수:**

accelerator (`Accelerator`) : 가속기 인스턴스

model (`torch.nn.Module`) : state dict를 로드할 모델입니다. meta device에 있어야 하며, 그렇지 않으면 VRAM 스파이크가 발생할 수 있습니다

full_sd (`dict`) : 로드할 전체 state dict입니다. rank 0에서만 사용할 수 있습니다.

cpu_offload (`bool`, 기본값은 `False`) : True인 경우, 분산 후 샤드된 파라미터를 CPU로 이동합니다. FSDP CPU 오프로딩이 활성화된 경우 필수입니다. 버퍼와 무시된 파라미터는 가속기 디바이스에 유지됩니다.

전체 state dict(0번 rank에만 있을 수 있음)를 sharded model에 로드합니다. 이는 0번 rank에서 모든 다른 rank로 매개변수를 브로드캐스트하는 방식으로 수행됩니다. 이 함수는 모델을 in-place로 수정합니다.

## fsdp2_switch_optimizer_parameters[[accelerate.utils.fsdp2_switch_optimizer_parameters]]

#### accelerate.utils.fsdp2_switch_optimizer_parameters[[accelerate.utils.fsdp2_switch_optimizer_parameters]]

```python
accelerate.utils.fsdp2_switch_optimizer_parameters(optimizer: Optimizer, mapping: dict)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/fsdp_utils.py#L658)

**매개변수:**

optimizer (`torch.optim.Optimizer`) : 원래 모델 파라미터를 포함하는 Optimizer 인스턴스

mapping (`dict`) : 원래 파라미터의 데이터 포인터(또는 메타 파라미터의 경우 identity)를 샤드된 파라미터로 매핑합니다.

**예외:** ``KeyError``

- ``KeyError`` -- 옵티마이저의 매개변수를 샤드된 버전으로 전환할 수 없는 경우 발생합니다. 이는 절대 발생해서는 안 되며 버그를 나타냅니다. 예외를 발생시키지 않고 원래 매개변수를 유지하는 경우, 학습이 수치적으로 정확하지 않고 가중치가 업데이트되지 않습니다.

optimizer의 매개변수를 새로운 매개변수(일반적인 경우 샤드된 매개변수)로 전환합니다. 이 함수는 optimizer를 인플레이스(in-place)로 수정합니다.

## fsdp2_prepare_model[[accelerate.utils.fsdp2_prepare_model]]

#### accelerate.utils.fsdp2_prepare_model[[accelerate.utils.fsdp2_prepare_model]]

```python
accelerate.utils.fsdp2_prepare_model(accelerator, model: Module)
```

[소스](https://github.com/huggingface/accelerate/blob/v1.16.0/src/accelerate/utils/fsdp_utils.py#L740)

**매개변수:**

accelerator (`Accelerator`) : 가속기 인스턴스

model (`torch.nn.Module`) : 준비할 모델

**반환값:** `torch.nn.Module`

준비된 모델

모델을 FSDP2를 위해 인플레이스로 준비합니다. 원본 모델의 오용을 방지하기 위해 모델도 반환합니다.

## fsdp2_prepare_auto_wrap_policy

