Accelerate documentation

完全分片数据并行工具

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v1.15.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

完全分片数据并行工具

enable_fsdp_ram_efficient_loading

accelerate.utils.enable_fsdp_ram_efficient_loading

< >

( )

启用在当前环境中以节省 RAM 的方式加载 Hugging Face 模型,用于 FSDP。

disable_fsdp_ram_efficient_loading

accelerate.utils.disable_fsdp_ram_efficient_loading

< >

( )

在环境中禁用 Hugging Face 模型在 FSDP 中的 RAM 高效加载。

merge_fsdp_weights

accelerate.utils.merge_fsdp_weights

< >

( checkpoint_dir: stroutput_path: strsafe_serialization: bool = Trueremove_checkpoint_dir: bool = False )

参数

  • checkpoint_dir (str) — 包含 FSDP 检查点(可以是模型或优化器)的目录。
  • output_path (str) — 用于保存合并后检查点的路径。
  • safe_serialization (bool,可选,默认为 True) — 是否使用 safetensors 保存合并后的权重(推荐)。
  • remove_checkpoint_dir (bool,可选,默认为 False) — 是否在合并后删除检查点目录。

将分片 FSDP 模型检查点中的权重合并为单个组合检查点。如果模型使用了 SHARDED_STATE_DICT,则应使用此功能。如果 safe_serialization 为真,权重将保存到 {output_path}/model.safetensors,否则保存到 pytorch_model.bin。

注意:这是一个 CPU 密集型进程。

FullyShardedDataParallelPlugin

类 accelerate.FullyShardedDataParallelPlugin

< >

( fsdp_version: int = Nonesharding_strategy: str | ForwardRef('torch.distributed.fsdp.ShardingStrategy') = Nonereshard_after_forward: str | ForwardRef('torch.distributed.fsdp.ShardingStrategy') | bool = Nonebackward_prefetch: str | ForwardRef('torch.distributed.fsdp.BackwardPrefetch') | None = Nonemixed_precision_policy: dict | str | ForwardRef('torch.distributed.fsdp.MixedPrecision') | ForwardRef('torch.distributed.fsdp.MixedPrecisionPolicy') | None = Noneauto_wrap_policy: typing.Callable | typing.Literal['transformer_based_wrap', 'size_based_wrap', 'no_wrap'] | None = Nonecpu_offload: bool | ForwardRef('torch.distributed.fsdp.CPUOffload') | ForwardRef('torch.distributed.fsdp.CPUOffloadPolicy') = Noneignored_modules: collections.abc.Iterable[torch.nn.Module] | str | None = Nonestate_dict_type: str | ForwardRef('torch.distributed.fsdp.StateDictType') = Nonestate_dict_config: ForwardRef('torch.distributed.fsdp.FullStateDictConfig') | ForwardRef('torch.distributed.fsdp.ShardedStateDictConfig') | None = Noneoptim_state_dict_config: ForwardRef('torch.distributed.fsdp.FullOptimStateDictConfig') | ForwardRef('torch.distributed.fsdp.ShardedOptimStateDictConfig') | None = Nonelimit_all_gathers: bool = Trueuse_orig_params: bool | None = Noneparam_init_fn: typing.Callable[[torch.nn.Module], NoneType] | None = Nonesync_module_states: bool | None = Noneforward_prefetch: bool = Noneactivation_checkpointing: bool = Noneactivation_checkpointing_offload: bool = Nonecpu_ram_efficient_loading: bool = Nonetransformer_cls_names_to_wrap: list[str] | None = Nonemin_num_params: int | None = None )

参数

  • fsdp_version (int,默认为 1) — 要使用的 FSDP 版本。默认为 1。如果设置为 2,启动器会期望配置已转换为 FSDP2 格式。
  • sharding_strategy (Union[str, torch.distributed.fsdp.ShardingStrategy],默认为 'FULL_SHARD') — 要使用的分片策略。应为 str 或 torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy 的实例。已弃用,建议使用 reshard_after_forward。
  • reshard_after_forward (Union[str, torch.distributed.fsdp.ShardingStrategy, bool],当 fsdp_version=1 时默认为 'FULL_SHARD',当 fsdp_version=2 时默认为 True) — 要使用的分片策略。如果 fsdp_version 设置为 2,则应为 bool 类型;否则应为 str 或 torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy 的实例。
  • backward_prefetch (Union[str, torch.distributed.fsdp.BackwardPrefetch],默认为 'NO_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。应为 bool 类型,或者当 fsdp_version 设置为 2 时,应为 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 配置。如果未传入,则根据 state_dict_type 确定。
  • optim_state_dict_config (Optional[Union[torch.distributed.fsdp.FullOptimStateDictConfig, torch.distributed.fsdp.ShardedOptimStateDictConfig],默认为 None) — 要使用的 Optim state dict 配置。如果未传入,则根据 state_dict_type 确定。
  • limit_all_gathers (bool,默认为 True) — 是否让 FSDP 显式同步 CPU 线程,以防止过多的 in-flight all-gathers。此 bool 仅影响调度 all-gathers 的分片策略。启用此选项有助于减少 CUDA malloc 重试次数。
  • use_orig_params (bool,默认为 False) — 是否使用原始参数作为优化器的参数。
  • param_init_fn (Optional[Callable[[torch.nn.Module], None],默认为 None) — 一个 Callable[torch.nn.Module] -> None,用于指定当前位于 meta 设备上的模块应如何初始化到实际设备上。仅当 sync_module_states 为 True 时适用。默认是一个 lambda,它会对模块调用 to_empty。
  • sync_module_states (bool,默认为 False) — 是否应让每个单独包装的 FSDP 单元从 rank 0 广播模块参数,以确保初始化后所有 rank 上的参数一致。除非 cpu_ram_efficient_loading 为 True,否则默认为 False;若为 True,则会强制启用。
  • forward_prefetch (bool,默认为 False) — 是否让 FSDP 在前向传播执行期间显式预取下一次即将进行的 all-gather。仅适用于静态图。
  • activation_checkpointing (bool, 默认为 False) — 一种通过清除特定层的激活值并在反向传播期间重新计算它们来降低内存使用量的技术。实际上,这是以额外的计算时间换取更低的内存占用。
  • 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

< >

( model )

给定 model,根据传入的策略创建 auto_wrap_policy,并判断是否可以使用 transformer_cls_to_wrap

set_mixed_precision

< >

( mixed_precisionbuffer_autocast = Falseoverride = False )

设置 FSDP 的混合精度策略

set_state_dict_type

< >

( state_dict_type = None )

根据 StateDictType 设置状态字典配置。

validate_mixed_precision_policy

< >

( )

验证混合精度策略,将其抽象化,以便在不需要时避免引入相关导入。

fsdp2_load_full_state_dict

accelerate.utils.fsdp2_load_full_state_dict

< >

( acceleratormodel: Modulefull_sd: dictcpu_offload: bool = False )

参数

  • accelerator (Accelerator) — 加速器实例
  • model (torch.nn.Module) — 要加载状态字典的模型,预期位于 meta 设备上,否则可能会发生 VRAM 峰值
  • full_sd (dict) — 要加载的完整状态字典,只能位于 rank 0
  • cpu_offload (bool,默认为 False) — 如果为 True,则在分发后将分片参数移至 CPU。启用 FSDP CPU offloading 时必需。

将完整的 state dict(可能仅存在于 rank 0 上)加载到分片模型中。此操作通过从 rank 0 向所有其他 rank 广播参数来完成。该函数会就地修改模型。

fsdp2_switch_optimizer_parameters

accelerate.utils.fsdp2_switch_optimizer_parameters

< >

( optimizer: Optimizermapping: dict )

参数

  • optimizer (torch.optim.Optimizer) — 包含原始模型参数的优化器实例
  • mapping (dict) — 从原始参数(由 data_ptr 指定)到分片参数的映射

引发

KeyError

  • KeyError — 如果优化器中的某个参数无法切换到其分片版本。这种情况不应发生,表明存在 bug。如果我们保留原始参数而不抛出异常,训练在数值上将不正确,且权重不会被更新。

将优化器的参数切换为新的参数(通常为分片参数)。此函数会就地修改优化器。

fsdp2_prepare_model

accelerate.utils.fsdp2_prepare_model

< >

( acceleratormodel: Module ) → torch.nn.Module

参数

  • accelerator (Accelerator) — 加速器实例
  • model (torch.nn.Module) — 要准备的模型

返回值

torch.nn.Module

已准备好的模型

为模型就地准备 FSDP2。同时返回模型,以避免误用原始模型。

fsdp2_prepare_auto_wrap_policy

Update on GitHub