Accelerate documentation
完全分片数据并行工具
完全分片数据并行工具
enable_fsdp_ram_efficient_loading
启用在当前环境中以节省 RAM 的方式加载 Hugging Face 模型,用于 FSDP。
disable_fsdp_ram_efficient_loading
在环境中禁用 Hugging Face 模型在 FSDP 中的 RAM 高效加载。
merge_fsdp_weights
accelerate.utils.merge_fsdp_weights
< source >( checkpoint_dir: stroutput_path: strsafe_serialization: bool = Trueremove_checkpoint_dir: bool = False )
将分片 FSDP 模型检查点中的权重合并为单个组合检查点。如果模型使用了 SHARDED_STATE_DICT,则应使用此功能。如果 safe_serialization 为真,权重将保存到 {output_path}/model.safetensors,否则保存到 pytorch_model.bin。
注意:这是一个 CPU 密集型进程。
FullyShardedDataParallelPlugin
类 accelerate.FullyShardedDataParallelPlugin
< source >( 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 toNO_WRAP) -- A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one oftransformer_based_wrap,size_based_wrap, orno_wrap. Seetorch.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时适用。
此插件用于启用完全分片数据并行。
给定 model,根据传入的策略创建 auto_wrap_policy,并判断是否可以使用 transformer_cls_to_wrap
设置 FSDP 的混合精度策略
根据 StateDictType 设置状态字典配置。
验证混合精度策略,将其抽象化,以便在不需要时避免引入相关导入。
fsdp2_load_full_state_dict
accelerate.utils.fsdp2_load_full_state_dict
< source >( acceleratormodel: Modulefull_sd: dictcpu_offload: bool = False )
将完整的 state dict(可能仅存在于 rank 0 上)加载到分片模型中。此操作通过从 rank 0 向所有其他 rank 广播参数来完成。该函数会就地修改模型。
fsdp2_switch_optimizer_parameters
accelerate.utils.fsdp2_switch_optimizer_parameters
< source >( optimizer: Optimizermapping: dict )
将优化器的参数切换为新的参数(通常为分片参数)。此函数会就地修改优化器。
fsdp2_prepare_model
accelerate.utils.fsdp2_prepare_model
< source >( acceleratormodel: Module ) → torch.nn.Module
为模型就地准备 FSDP2。同时返回模型,以避免误用原始模型。