| 1 |
# Copyright 2022 The HuggingFace Team. All rights reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
|
| 16 |
import functools |
| 17 |
import os |
| 18 |
from contextlib import nullcontext |
| 19 |
|
| 20 |
import torch |
| 21 |
from transformers import AutoModel |
| 22 |
|
| 23 |
from accelerate.accelerator import Accelerator |
| 24 |
from accelerate.state import AcceleratorState, DistributedType |
| 25 |
from accelerate.test_utils.testing import ( |
| 26 |
AccelerateTestCase, |
| 27 |
TempDirTestCase, |
| 28 |
execute_subprocess_async, |
| 29 |
get_launch_command, |
| 30 |
path_in_accelerate_package, |
| 31 |
require_fp16, |
| 32 |
require_fsdp2, |
| 33 |
require_multi_device, |
| 34 |
require_non_cpu, |
| 35 |
require_non_torch_xla, |
| 36 |
run_first, |
| 37 |
slow, |
| 38 |
) |
| 39 |
from accelerate.utils import is_bf16_available, is_fp16_available, is_hpu_available, patch_environment, set_seed |
| 40 |
from accelerate.utils.constants import ( |
| 41 |
FSDP2_STATE_DICT_TYPE, |
| 42 |
FSDP_AUTO_WRAP_POLICY, |
| 43 |
FSDP_BACKWARD_PREFETCH, |
| 44 |
FSDP_SHARDING_STRATEGY, |
| 45 |
FSDP_STATE_DICT_TYPE, |
| 46 |
) |
| 47 |
from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin |
| 48 |
from accelerate.utils.fsdp_utils import disable_fsdp_ram_efficient_loading, enable_fsdp_ram_efficient_loading |
| 49 |
|
| 50 |
|
| 51 |
set_seed(42) |
| 52 |
|
| 53 |
|
| 54 |
BERT_BASE_CASED = "bert-base-cased" |
| 55 |
LLAMA_TESTING = "hf-internal-testing/tiny-random-LlamaForCausalLM" |
| 56 |
FP16 = "fp16" |
| 57 |
BF16 = "bf16" |
| 58 |
|
| 59 |
dtypes = [] |
| 60 |
if is_fp16_available(): |
| 61 |
dtypes.append(FP16) |
| 62 |
if is_bf16_available(): |
| 63 |
dtypes.append(BF16) |
| 64 |
|
| 65 |
|
| 66 |
@require_non_cpu |
| 67 |
@require_non_torch_xla |
| 68 |
class FSDPPluginIntegration(AccelerateTestCase): |
| 69 |
def setUp(self): |
| 70 |
super().setUp() |
| 71 |
|
| 72 |
self.dist_env = dict( |
| 73 |
MASTER_ADDR="localhost", |
| 74 |
MASTER_PORT="10999", |
| 75 |
RANK="0", |
| 76 |
LOCAL_RANK="0", |
| 77 |
WORLD_SIZE="1", |
| 78 |
) |
| 79 |
|
| 80 |
self.fsdp1_env = dict(ACCELERATE_USE_FSDP="true", **self.dist_env) |
| 81 |
self.fsdp2_env = dict(ACCELERATE_USE_FSDP="true", **self.dist_env, FSDP_VERSION="2") |
| 82 |
|
| 83 |
self.fsdp_envs = { |
| 84 |
1: self.fsdp1_env, |
| 85 |
2: self.fsdp2_env, |
| 86 |
} |
| 87 |
|
| 88 |
self.current_fsdp_version = 1 |
| 89 |
|
| 90 |
def test_sharding_strategy(self): |
| 91 |
from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy |
| 92 |
|
| 93 |
SHARDING_STRATEGIES = { |
| 94 |
1: FSDP_SHARDING_STRATEGY, |
| 95 |
2: [True, False], |
| 96 |
} |
| 97 |
|
| 98 |
SHARDING_STRATEGY_NAMES = { |
| 99 |
1: "FSDP_SHARDING_STRATEGY", |
| 100 |
2: "FSDP_RESHARD_AFTER_FORWARD", |
| 101 |
} |
| 102 |
|
| 103 |
# check that giving enums works fine |
| 104 |
# Only supported in FSDP1 |
| 105 |
for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): |
| 106 |
env = self.fsdp_envs[1].copy() |
| 107 |
env["FSDP_SHARDING_STRATEGY"] = f"{i + 1}" |
| 108 |
with patch_environment(**env): |
| 109 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 110 |
assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) |
| 111 |
fsdp_plugin = FullyShardedDataParallelPlugin(sharding_strategy=ShardingStrategy(i + 1)) |
| 112 |
assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) |
| 113 |
|
| 114 |
# check that giving names works fine, also needed for FSDP2 |
| 115 |
fsdp_version = self.current_fsdp_version |
| 116 |
for i, strategy in enumerate(SHARDING_STRATEGIES[fsdp_version]): |
| 117 |
env = self.fsdp_envs[fsdp_version].copy() |
| 118 |
env[SHARDING_STRATEGY_NAMES[fsdp_version]] = strategy |
| 119 |
with patch_environment(**env): |
| 120 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 121 |
if fsdp_version == 1: |
| 122 |
assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) |
| 123 |
assert fsdp_plugin.reshard_after_forward is None |
| 124 |
else: |
| 125 |
assert fsdp_plugin.reshard_after_forward == strategy |
| 126 |
assert fsdp_plugin.sharding_strategy is None |
| 127 |
|
| 128 |
env = self.fsdp_envs[fsdp_version].copy() |
| 129 |
with patch_environment(**env): |
| 130 |
if fsdp_version == 1: |
| 131 |
fsdp_plugin = FullyShardedDataParallelPlugin(sharding_strategy=ShardingStrategy(i + 1)) |
| 132 |
assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) |
| 133 |
assert fsdp_plugin.reshard_after_forward is None |
| 134 |
else: |
| 135 |
fsdp_plugin = FullyShardedDataParallelPlugin(reshard_after_forward=strategy) |
| 136 |
assert fsdp_plugin.reshard_after_forward == strategy |
| 137 |
assert fsdp_plugin.sharding_strategy is None |
| 138 |
|
| 139 |
def test_backward_prefetch(self): |
| 140 |
from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch |
| 141 |
|
| 142 |
_warning_message_fsdp2 = "backward_prefetch is not supported in FSDP2. Setting backward prefetch to None." |
| 143 |
|
| 144 |
fsdp_version = self.current_fsdp_version |
| 145 |
for i, prefetch_policy in enumerate(FSDP_BACKWARD_PREFETCH): |
| 146 |
# FSDP2 warns about backward prefetch and sets to None |
| 147 |
ctx = ( |
| 148 |
self.assertLogs("accelerate.utils.dataclasses", level="WARNING") |
| 149 |
if fsdp_version == 2 and prefetch_policy != "NO_PREFETCH" |
| 150 |
else nullcontext() |
| 151 |
) |
| 152 |
expected_value = ( |
| 153 |
None if (prefetch_policy == "NO_PREFETCH" or fsdp_version == 2) else BackwardPrefetch(i + 1) |
| 154 |
) |
| 155 |
env = self.fsdp_envs[fsdp_version].copy() |
| 156 |
env["FSDP_BACKWARD_PREFETCH"] = prefetch_policy |
| 157 |
with patch_environment(**env), ctx as cm: |
| 158 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 159 |
assert fsdp_plugin.backward_prefetch == expected_value, ( |
| 160 |
f"Actual: {fsdp_plugin.backward_prefetch} != Expected: {expected_value}" |
| 161 |
) |
| 162 |
if cm: |
| 163 |
self.assertTrue(any(_warning_message_fsdp2 in out for out in cm.output)) |
| 164 |
|
| 165 |
# Check if torch enum works |
| 166 |
env = self.fsdp_envs[fsdp_version].copy() |
| 167 |
with patch_environment(**env), ctx as cm: |
| 168 |
if prefetch_policy != "NO_PREFETCH": |
| 169 |
fsdp_plugin = FullyShardedDataParallelPlugin(backward_prefetch=BackwardPrefetch(i + 1)) |
| 170 |
assert fsdp_plugin.backward_prefetch == expected_value |
| 171 |
if cm: |
| 172 |
self.assertTrue(any(_warning_message_fsdp2 in out for out in cm.output)) |
| 173 |
|
| 174 |
# Check if name works |
| 175 |
with patch_environment(**env), ctx as cm: |
| 176 |
fsdp_plugin = FullyShardedDataParallelPlugin(backward_prefetch=prefetch_policy) |
| 177 |
assert fsdp_plugin.backward_prefetch == expected_value |
| 178 |
if cm: |
| 179 |
self.assertTrue(any(_warning_message_fsdp2 in out for out in cm.output)) |
| 180 |
|
| 181 |
def test_state_dict_type(self): |
| 182 |
from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType |
| 183 |
|
| 184 |
fsdp_version = self.current_fsdp_version |
| 185 |
for i, state_dict_type in enumerate(FSDP_STATE_DICT_TYPE): |
| 186 |
cm = ( |
| 187 |
self.assertRaises(ValueError) |
| 188 |
if (fsdp_version == 2 and state_dict_type not in FSDP2_STATE_DICT_TYPE) |
| 189 |
else nullcontext() |
| 190 |
) |
| 191 |
env = self.fsdp_envs[fsdp_version].copy() |
| 192 |
env["FSDP_STATE_DICT_TYPE"] = state_dict_type |
| 193 |
with patch_environment(**env), cm: |
| 194 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 195 |
assert fsdp_plugin.state_dict_type == StateDictType(i + 1) |
| 196 |
if state_dict_type == "FULL_STATE_DICT": |
| 197 |
assert fsdp_plugin.state_dict_config.offload_to_cpu |
| 198 |
assert fsdp_plugin.state_dict_config.rank0_only |
| 199 |
|
| 200 |
env = self.fsdp_envs[fsdp_version].copy() |
| 201 |
with patch_environment(**env), cm: |
| 202 |
fsdp_plugin = FullyShardedDataParallelPlugin(state_dict_type=StateDictType(i + 1)) |
| 203 |
assert fsdp_plugin.state_dict_type == StateDictType(i + 1) |
| 204 |
if state_dict_type == "FULL_STATE_DICT": |
| 205 |
assert fsdp_plugin.state_dict_config.offload_to_cpu |
| 206 |
assert fsdp_plugin.state_dict_config.rank0_only |
| 207 |
|
| 208 |
# We can also override the state_dict_type, |
| 209 |
# typical case: user trains with sharded, but final save is with full |
| 210 |
fsdp_plugin = FullyShardedDataParallelPlugin(state_dict_type="FULL_STATE_DICT") |
| 211 |
fsdp_plugin.set_state_dict_type("SHARDED_STATE_DICT") |
| 212 |
assert fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT |
| 213 |
|
| 214 |
def test_auto_wrap_policy(self): |
| 215 |
fsdp_version = self.current_fsdp_version |
| 216 |
for model_name in [LLAMA_TESTING, BERT_BASE_CASED]: |
| 217 |
model = AutoModel.from_pretrained(model_name) |
| 218 |
layer_to_wrap = "LlamaDecoderLayer" if model_name == LLAMA_TESTING else "BertLayer" |
| 219 |
for policy in FSDP_AUTO_WRAP_POLICY: |
| 220 |
env = self.fsdp_envs[fsdp_version].copy() |
| 221 |
env["FSDP_AUTO_WRAP_POLICY"] = policy |
| 222 |
transformer_cls_to_wrap = None |
| 223 |
min_num_params = None |
| 224 |
env.pop("FSDP_TRANSFORMER_CLS_TO_WRAP", None) |
| 225 |
env.pop("FSDP_MIN_NUM_PARAMS", None) |
| 226 |
if policy == "TRANSFORMER_BASED_WRAP": |
| 227 |
env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = layer_to_wrap |
| 228 |
transformer_cls_to_wrap = layer_to_wrap |
| 229 |
elif policy == "SIZE_BASED_WRAP": |
| 230 |
env["FSDP_MIN_NUM_PARAMS"] = "2000" |
| 231 |
min_num_params = 2000 |
| 232 |
# First test via env |
| 233 |
with patch_environment(**env): |
| 234 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 235 |
fsdp_plugin.set_auto_wrap_policy(model) |
| 236 |
if policy == "NO_WRAP": |
| 237 |
assert fsdp_plugin.auto_wrap_policy is None |
| 238 |
else: |
| 239 |
assert isinstance(fsdp_plugin.auto_wrap_policy, functools.partial) |
| 240 |
|
| 241 |
# Then manually set the policy |
| 242 |
env = self.fsdp_envs[fsdp_version].copy() |
| 243 |
with patch_environment(**env): |
| 244 |
fsdp_plugin = FullyShardedDataParallelPlugin( |
| 245 |
auto_wrap_policy=policy, |
| 246 |
transformer_cls_names_to_wrap=transformer_cls_to_wrap, |
| 247 |
min_num_params=min_num_params, |
| 248 |
) |
| 249 |
fsdp_plugin.set_auto_wrap_policy(model) |
| 250 |
if policy == "NO_WRAP": |
| 251 |
assert fsdp_plugin.auto_wrap_policy is None |
| 252 |
else: |
| 253 |
assert isinstance(fsdp_plugin.auto_wrap_policy, functools.partial) |
| 254 |
|
| 255 |
env = self.fsdp_envs[fsdp_version].copy() |
| 256 |
env["FSDP_AUTO_WRAP_POLICY"] = "TRANSFORMER_BASED_WRAP" |
| 257 |
env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = "T5Layer" |
| 258 |
with patch_environment(**env): |
| 259 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 260 |
with self.assertRaises(Exception) as cm: |
| 261 |
fsdp_plugin.set_auto_wrap_policy(model) |
| 262 |
assert "Could not find the transformer layer class T5Layer in the model." in str(cm.exception) |
| 263 |
|
| 264 |
env = self.fsdp_envs[fsdp_version].copy() |
| 265 |
with patch_environment(**env): |
| 266 |
fsdp_plugin = FullyShardedDataParallelPlugin( |
| 267 |
auto_wrap_policy="TRANSFORMER_BASED_WRAP", |
| 268 |
transformer_cls_names_to_wrap="T5Layer", |
| 269 |
) |
| 270 |
with self.assertRaises(Exception) as cm: |
| 271 |
fsdp_plugin.set_auto_wrap_policy(model) |
| 272 |
assert "Could not find the transformer layer class T5Layer in the model." in str(cm.exception) |
| 273 |
|
| 274 |
env = self.fsdp_envs[fsdp_version].copy() |
| 275 |
env["FSDP_AUTO_WRAP_POLICY"] = "SIZE_BASED_WRAP" |
| 276 |
env["FSDP_MIN_NUM_PARAMS"] = "0" |
| 277 |
with patch_environment(**env): |
| 278 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 279 |
fsdp_plugin.set_auto_wrap_policy(model) |
| 280 |
assert fsdp_plugin.auto_wrap_policy is None |
| 281 |
|
| 282 |
env = self.fsdp_envs[fsdp_version].copy() |
| 283 |
with patch_environment(**env): |
| 284 |
fsdp_plugin = FullyShardedDataParallelPlugin( |
| 285 |
auto_wrap_policy="SIZE_BASED_WRAP", |
| 286 |
min_num_params=0, |
| 287 |
) |
| 288 |
fsdp_plugin.set_auto_wrap_policy(model) |
| 289 |
assert fsdp_plugin.auto_wrap_policy is None |
| 290 |
|
| 291 |
def test_mixed_precision(self): |
| 292 |
fsdp_version = self.current_fsdp_version |
| 293 |
if fsdp_version == 2: |
| 294 |
from torch.amp.grad_scaler import GradScaler as Scaler |
| 295 |
from torch.distributed.fsdp import MixedPrecisionPolicy as MP |
| 296 |
else: |
| 297 |
from torch.distributed.fsdp import MixedPrecision as MP |
| 298 |
from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler as Scaler |
| 299 |
|
| 300 |
for mp_dtype in dtypes: |
| 301 |
env = self.fsdp_envs[fsdp_version].copy() |
| 302 |
env["ACCELERATE_MIXED_PRECISION"] = mp_dtype |
| 303 |
extra_arg = "buffer_dtype" if fsdp_version == 1 else "output_dtype" |
| 304 |
with patch_environment(**env): |
| 305 |
accelerator = Accelerator() |
| 306 |
if mp_dtype == "fp16": |
| 307 |
dtype = torch.float16 |
| 308 |
elif mp_dtype == "bf16": |
| 309 |
dtype = torch.bfloat16 |
| 310 |
mp_policy = MP(param_dtype=dtype, reduce_dtype=dtype, **{extra_arg: dtype}) |
| 311 |
assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy |
| 312 |
if mp_dtype == FP16: |
| 313 |
assert isinstance(accelerator.scaler, Scaler) |
| 314 |
elif mp_dtype == BF16: |
| 315 |
assert accelerator.scaler is None |
| 316 |
AcceleratorState._reset_state(True) |
| 317 |
|
| 318 |
env = self.fsdp_envs[fsdp_version].copy() |
| 319 |
with patch_environment(**env): |
| 320 |
plugin = FullyShardedDataParallelPlugin(mixed_precision_policy=mp_dtype) |
| 321 |
assert plugin.mixed_precision_policy == mp_policy |
| 322 |
with patch_environment(**env): |
| 323 |
plugin = FullyShardedDataParallelPlugin( |
| 324 |
mixed_precision_policy={"param_dtype": dtype, "reduce_dtype": dtype, extra_arg: dtype} |
| 325 |
) |
| 326 |
assert plugin.mixed_precision_policy == mp_policy |
| 327 |
with patch_environment(**env): |
| 328 |
accelerator = Accelerator(fsdp_plugin=plugin) |
| 329 |
assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy |
| 330 |
AcceleratorState._reset_state(True) |
| 331 |
|
| 332 |
def test_mixed_precision_buffer_autocast_override(self): |
| 333 |
from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision |
| 334 |
from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler |
| 335 |
|
| 336 |
if self.current_fsdp_version == 2: |
| 337 |
return |
| 338 |
|
| 339 |
# We're not testing this for FSDP2 because FSDP2 doesn't support `buffer_dtype` rather only `output_dtype` |
| 340 |
# TODO(s1ro1): what should we do if `buffer_autocast` is set to True in FSDP2? |
| 341 |
|
| 342 |
for mp_dtype in dtypes: |
| 343 |
if mp_dtype == "fp16": |
| 344 |
dtype = torch.float16 |
| 345 |
elif mp_dtype == "bf16": |
| 346 |
dtype = torch.bfloat16 |
| 347 |
mp_policy = MixedPrecision(param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=torch.float32) |
| 348 |
|
| 349 |
env = self.fsdp_envs[1].copy() |
| 350 |
env["ACCELERATE_MIXED_PRECISION"] = mp_dtype |
| 351 |
with patch_environment(**env): |
| 352 |
accelerator = Accelerator() |
| 353 |
accelerator.state.fsdp_plugin.set_mixed_precision(dtype, buffer_autocast=True, override=True) |
| 354 |
assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy |
| 355 |
if mp_dtype == FP16: |
| 356 |
assert isinstance(accelerator.scaler, ShardedGradScaler) |
| 357 |
elif mp_dtype == BF16: |
| 358 |
assert accelerator.scaler is None |
| 359 |
AcceleratorState._reset_state(True) |
| 360 |
|
| 361 |
def test_cpu_offload(self): |
| 362 |
fsdp_version = self.current_fsdp_version |
| 363 |
if fsdp_version == 2: |
| 364 |
from torch.distributed.fsdp import CPUOffloadPolicy, OffloadPolicy |
| 365 |
else: |
| 366 |
from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload |
| 367 |
|
| 368 |
for flag in [True, False]: |
| 369 |
env = self.fsdp_envs[fsdp_version].copy() |
| 370 |
env["FSDP_OFFLOAD_PARAMS"] = str(flag).lower() |
| 371 |
|
| 372 |
# FSDP2 has a different class for not offloading, therefore we need to check for both cases |
| 373 |
if fsdp_version == 2 and flag: |
| 374 |
expected_value = CPUOffloadPolicy() |
| 375 |
elif fsdp_version == 2 and not flag: |
| 376 |
expected_value = OffloadPolicy() |
| 377 |
else: |
| 378 |
expected_value = CPUOffload(offload_params=flag) |
| 379 |
with patch_environment(**env): |
| 380 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 381 |
assert fsdp_plugin.cpu_offload == expected_value |
| 382 |
|
| 383 |
env = self.fsdp_envs[fsdp_version].copy() |
| 384 |
with patch_environment(**env): |
| 385 |
fsdp_plugin = FullyShardedDataParallelPlugin(cpu_offload=flag) |
| 386 |
assert fsdp_plugin.cpu_offload == expected_value |
| 387 |
|
| 388 |
def test_cpu_ram_efficient_loading(self): |
| 389 |
fsdp_version = self.current_fsdp_version |
| 390 |
env = self.fsdp_envs[fsdp_version].copy() |
| 391 |
enable_fsdp_ram_efficient_loading() |
| 392 |
with patch_environment(**env): |
| 393 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 394 |
assert fsdp_plugin.cpu_ram_efficient_loading is True |
| 395 |
assert os.environ.get("FSDP_CPU_RAM_EFFICIENT_LOADING") == "True" |
| 396 |
|
| 397 |
disable_fsdp_ram_efficient_loading() |
| 398 |
env = self.fsdp_envs[fsdp_version].copy() |
| 399 |
with patch_environment(**env): |
| 400 |
fsdp_plugin = FullyShardedDataParallelPlugin() |
| 401 |
assert fsdp_plugin.cpu_ram_efficient_loading is False |
| 402 |
assert os.environ.get("FSDP_CPU_RAM_EFFICIENT_LOADING") == "False" |
| 403 |
|
| 404 |
def test_ignored_modules_regex(self): |
| 405 |
# Check that FSDP's ignored_modules can be a string, in which case it is treated as a regex |
| 406 |
env = self.fsdp_envs[1].copy() |
| 407 |
env["FSDP_IGNORED_MODULES"] = ".*\\.q_proj$" |
| 408 |
with patch_environment(**env): |
| 409 |
accelerator = Accelerator() |
| 410 |
model = AutoModel.from_pretrained(LLAMA_TESTING) |
| 411 |
model = accelerator.prepare(model) |
| 412 |
if self.current_fsdp_version == 1: |
| 413 |
# model has 2 layers |
| 414 |
layers_to_ignore = {model.layers[0].self_attn.q_proj, model.layers[1].self_attn.q_proj} |
| 415 |
assert model._ignored_modules == layers_to_ignore |
| 416 |
else: |
| 417 |
params_to_ignore = {model.layers[0].self_attn.q_proj.weight, model.layers[1].self_attn.q_proj.weight} |
| 418 |
assert model._ignored_params == params_to_ignore |
| 419 |
|
| 420 |
|
| 421 |
@require_fsdp2 |
| 422 |
@require_non_cpu |
| 423 |
@require_non_torch_xla |
| 424 |
class FSDP2PluginIntegration(FSDPPluginIntegration): |
| 425 |
def setUp(self): |
| 426 |
super().setUp() |
| 427 |
self.current_fsdp_version = 2 |
| 428 |
|
| 429 |
def test_param_mapping_error_handling(self): |
| 430 |
"""Test FSDP2's defensive error handling for parameter mapping failures in tied/non-tied cases.""" |
| 431 |
from unittest.mock import Mock, patch |
| 432 |
|
| 433 |
fsdp_plugin = FullyShardedDataParallelPlugin(fsdp_version=2) |
| 434 |
accelerator = Accelerator() |
| 435 |
accelerator.state.distributed_type = DistributedType.FSDP |
| 436 |
accelerator.state.fsdp_plugin = fsdp_plugin |
| 437 |
|
| 438 |
mock_model = Mock(spec=torch.nn.Module) |
| 439 |
mock_model.config = Mock(tie_word_embeddings=True) |
| 440 |
mock_optimizer = Mock(spec=torch.optim.Optimizer) |
| 441 |
mock_optimizer.param_groups = [] |
| 442 |
result = [mock_model, mock_optimizer] |
| 443 |
|
| 444 |
# Tied case |
| 445 |
old_named_params = {"model.embed_tokens.weight": 12345, "lm_head.weight": 67890, "other.weight": 11111} |
| 446 |
new_named_params = {"model.embed_tokens.weight": 12345, "other.weight": 11111} |
| 447 |
with patch.object(accelerator, "_get_named_parameters", side_effect=[old_named_params, new_named_params]): |
| 448 |
with patch("accelerate.accelerator.fsdp2_canonicalize_names", side_effect=lambda x: x): |
| 449 |
with patch("accelerate.accelerator.fsdp2_prepare_model", return_value=mock_model): |
| 450 |
with patch.object(accelerator.state.fsdp_plugin, "set_auto_wrap_policy"): |
| 451 |
with self.assertRaises(ValueError) as cm: |
| 452 |
accelerator._prepare_fsdp2(*result) |
| 453 |
error_msg = str(cm.exception) |
| 454 |
self.assertIn("FSDP2 mapping failed", error_msg) |
| 455 |
self.assertIn("tied embeddings", error_msg) |
| 456 |
self.assertIn("lm_head.weight", error_msg) |
| 457 |
self.assertIn("tie_word_embeddings = False", error_msg) |
| 458 |
|
| 459 |
# Non-tied case |
| 460 |
old_named_params = {"layer1.weight": 12345, "some_other.weight": 67890} |
| 461 |
new_named_params = {"layer1.weight": 12345} |
| 462 |
with patch.object(accelerator, "_get_named_parameters", side_effect=[old_named_params, new_named_params]): |
| 463 |
with patch("accelerate.accelerator.fsdp2_canonicalize_names", side_effect=lambda x: x): |
| 464 |
with patch("accelerate.accelerator.fsdp2_prepare_model", return_value=mock_model): |
| 465 |
with patch.object(accelerator.state.fsdp_plugin, "set_auto_wrap_policy"): |
| 466 |
with self.assertRaises(KeyError) as cm: |
| 467 |
accelerator._prepare_fsdp2(*result) |
| 468 |
error_msg = str(cm.exception) |
| 469 |
self.assertIn("Parameters missing after FSDP2 wrapping", error_msg) |
| 470 |
self.assertIn("some_other.weight", error_msg) |
| 471 |
|
| 472 |
AcceleratorState._reset_state(True) |
| 473 |
|
| 474 |
def test_fsdp2_uniform_dtype_upcast_bf16(self): |
| 475 |
"""Test that fsdp2_prepare_model upcasts mixed-dtype trainable params to fp32 master weights |
| 476 |
when mixed_precision='bf16'. Many HF models (Llama, Mistral) store norm weights in fp32, |
| 477 |
and FSDP2 requires uniform orig_dtype among trainable params within each FSDP group.""" |
| 478 |
from unittest.mock import Mock, patch |
| 479 |
|
| 480 |
from accelerate.utils.fsdp_utils import fsdp2_prepare_model |
| 481 |
|
| 482 |
# Create model with mixed dtypes: linear=bf16, norm=fp32 (simulates HF Llama) |
| 483 |
model = torch.nn.Sequential( |
| 484 |
torch.nn.Linear(4, 4), |
| 485 |
torch.nn.LayerNorm(4), |
| 486 |
) |
| 487 |
model[0].to(torch.bfloat16) |
| 488 |
dtypes_before = {p.dtype for p in model.parameters()} |
| 489 |
assert dtypes_before == {torch.bfloat16, torch.float32} |
| 490 |
|
| 491 |
mock_accelerator = Mock() |
| 492 |
mock_accelerator.mixed_precision = "bf16" |
| 493 |
mock_accelerator.torch_device_mesh = None |
| 494 |
mock_accelerator.device = torch.device("cpu") |
| 495 |
mock_accelerator.is_main_process = True |
| 496 |
|
| 497 |
mock_mp_policy = Mock() |
| 498 |
mock_mp_policy.param_dtype = torch.bfloat16 |
| 499 |
mock_plugin = Mock() |
| 500 |
mock_plugin.mixed_precision_policy = mock_mp_policy |
| 501 |
mock_plugin.reshard_after_forward = True |
| 502 |
mock_plugin.cpu_offload = None |
| 503 |
mock_plugin.cpu_ram_efficient_loading = False |
| 504 |
mock_plugin.ignored_modules = None |
| 505 |
mock_accelerator.state.fsdp_plugin = mock_plugin |
| 506 |
|
| 507 |
with ( |
| 508 |
patch("torch.distributed.fsdp.fully_shard"), |
| 509 |
patch("accelerate.utils.fsdp_utils.is_compiled_module", return_value=False), |
| 510 |
patch("accelerate.utils.fsdp_utils.fsdp2_prepare_auto_wrap_policy", return_value=None), |
| 511 |
patch("accelerate.utils.fsdp_utils.logger"), |
| 512 |
): |
| 513 |
result = fsdp2_prepare_model(mock_accelerator, model) |
| 514 |
|
| 515 |
dtypes_after = {p.dtype for p in result.parameters()} |
| 516 |
assert dtypes_after == {torch.float32}, f"Expected all fp32 master weights, got {dtypes_after}" |
| 517 |
|
| 518 |
def test_fsdp2_uniform_dtype_upcast_fp16(self): |
| 519 |
"""Test that fsdp2_prepare_model upcasts mixed-dtype trainable params to fp32 master weights |
| 520 |
when mixed_precision='fp16'.""" |
| 521 |
from unittest.mock import Mock, patch |
| 522 |
|
| 523 |
from accelerate.utils.fsdp_utils import fsdp2_prepare_model |
| 524 |
|
| 525 |
model = torch.nn.Sequential( |
| 526 |
torch.nn.Linear(4, 4), |
| 527 |
torch.nn.LayerNorm(4), |
| 528 |
) |
| 529 |
model[0].to(torch.float16) |
| 530 |
dtypes_before = {p.dtype for p in model.parameters()} |
| 531 |
assert dtypes_before == {torch.float16, torch.float32} |
| 532 |
|
| 533 |
mock_accelerator = Mock() |
| 534 |
mock_accelerator.mixed_precision = "fp16" |
| 535 |
mock_accelerator.torch_device_mesh = None |
| 536 |
mock_accelerator.device = torch.device("cpu") |
| 537 |
mock_accelerator.is_main_process = True |
| 538 |
|
| 539 |
mock_mp_policy = Mock() |
| 540 |
mock_mp_policy.param_dtype = torch.float16 |
| 541 |
mock_plugin = Mock() |
| 542 |
mock_plugin.mixed_precision_policy = mock_mp_policy |
| 543 |
mock_plugin.reshard_after_forward = True |
| 544 |
mock_plugin.cpu_offload = None |
| 545 |
mock_plugin.cpu_ram_efficient_loading = False |
| 546 |
mock_plugin.ignored_modules = None |
| 547 |
mock_accelerator.state.fsdp_plugin = mock_plugin |
| 548 |
|
| 549 |
with ( |
| 550 |
patch("torch.distributed.fsdp.fully_shard"), |
| 551 |
patch("accelerate.utils.fsdp_utils.is_compiled_module", return_value=False), |
| 552 |
patch("accelerate.utils.fsdp_utils.fsdp2_prepare_auto_wrap_policy", return_value=None), |
| 553 |
patch("accelerate.utils.fsdp_utils.logger"), |
| 554 |
): |
| 555 |
result = fsdp2_prepare_model(mock_accelerator, model) |
| 556 |
|
| 557 |
dtypes_after = {p.dtype for p in result.parameters()} |
| 558 |
assert dtypes_after == {torch.float32}, f"Expected all fp32 master weights, got {dtypes_after}" |
| 559 |
|
| 560 |
def test_fsdp2_no_dtype_cast_when_no_mixed_precision(self): |
| 561 |
"""Test that no dtype cast happens when mixed_precision='no', preserving original model dtypes.""" |
| 562 |
from unittest.mock import Mock, patch |
| 563 |
|
| 564 |
from accelerate.utils.fsdp_utils import fsdp2_prepare_model |
| 565 |
|
| 566 |
model = torch.nn.Sequential( |
| 567 |
torch.nn.Linear(4, 4), |
| 568 |
torch.nn.LayerNorm(4), |
| 569 |
) |
| 570 |
model[0].to(torch.bfloat16) |
| 571 |
dtypes_before = {p.dtype for p in model.parameters()} |
| 572 |
assert dtypes_before == {torch.bfloat16, torch.float32} |
| 573 |
|
| 574 |
mock_accelerator = Mock() |
| 575 |
mock_accelerator.mixed_precision = "no" |
| 576 |
mock_accelerator.torch_device_mesh = None |
| 577 |
mock_accelerator.device = torch.device("cpu") |
| 578 |
mock_accelerator.is_main_process = True |
| 579 |
|
| 580 |
mock_plugin = Mock() |
| 581 |
mock_plugin.mixed_precision_policy = None |
| 582 |
mock_plugin.reshard_after_forward = True |
| 583 |
mock_plugin.cpu_offload = None |
| 584 |
mock_plugin.cpu_ram_efficient_loading = False |
| 585 |
mock_plugin.ignored_modules = None |
| 586 |
mock_accelerator.state.fsdp_plugin = mock_plugin |
| 587 |
|
| 588 |
with ( |
| 589 |
patch("torch.distributed.fsdp.fully_shard"), |
| 590 |
patch("accelerate.utils.fsdp_utils.is_compiled_module", return_value=False), |
| 591 |
patch("accelerate.utils.fsdp_utils.fsdp2_prepare_auto_wrap_policy", return_value=None), |
| 592 |
patch("accelerate.utils.fsdp_utils.logger"), |
| 593 |
): |
| 594 |
result = fsdp2_prepare_model(mock_accelerator, model) |
| 595 |
|
| 596 |
dtypes_after = {p.dtype for p in result.parameters()} |
| 597 |
assert dtypes_after == {torch.bfloat16, torch.float32}, f"Expected mixed dtypes preserved, got {dtypes_after}" |
| 598 |
|
| 599 |
def test_fsdp2_no_dtype_cast_with_params4bit(self): |
| 600 |
"""Test that dtype cast is skipped when model has Params4bit (QLoRA), |
| 601 |
to avoid destroying quantized weights.""" |
| 602 |
from unittest.mock import Mock, patch |
| 603 |
|
| 604 |
from accelerate.utils.fsdp_utils import fsdp2_prepare_model |
| 605 |
|
| 606 |
model = torch.nn.Sequential( |
| 607 |
torch.nn.Linear(4, 4), |
| 608 |
torch.nn.LayerNorm(4), |
| 609 |
) |
| 610 |
model[0].to(torch.bfloat16) |
| 611 |
dtypes_before = {p.dtype for p in model.parameters()} |
| 612 |
assert dtypes_before == {torch.bfloat16, torch.float32} |
| 613 |
|
| 614 |
# Simulate Params4bit by renaming one parameter's class |
| 615 |
original_class = model[0].weight.__class__ |
| 616 |
model[0].weight.__class__ = type("Params4bit", (torch.nn.Parameter,), {}) |
| 617 |
|
| 618 |
mock_accelerator = Mock() |
| 619 |
mock_accelerator.mixed_precision = "bf16" |
| 620 |
mock_accelerator.torch_device_mesh = None |
| 621 |
mock_accelerator.device = torch.device("cpu") |
| 622 |
mock_accelerator.is_main_process = True |
| 623 |
|
| 624 |
mock_mp_policy = Mock() |
| 625 |
mock_mp_policy.param_dtype = torch.bfloat16 |
| 626 |
mock_plugin = Mock() |
| 627 |
mock_plugin.mixed_precision_policy = mock_mp_policy |
| 628 |
mock_plugin.reshard_after_forward = True |
| 629 |
mock_plugin.cpu_offload = None |
| 630 |
mock_plugin.cpu_ram_efficient_loading = False |
| 631 |
mock_plugin.ignored_modules = None |
| 632 |
mock_accelerator.state.fsdp_plugin = mock_plugin |
| 633 |
|
| 634 |
try: |
| 635 |
with ( |
| 636 |
patch("torch.distributed.fsdp.fully_shard"), |
| 637 |
patch("accelerate.utils.fsdp_utils.is_compiled_module", return_value=False), |
| 638 |
patch("accelerate.utils.fsdp_utils.fsdp2_prepare_auto_wrap_policy", return_value=None), |
| 639 |
): |
| 640 |
result = fsdp2_prepare_model(mock_accelerator, model) |
| 641 |
|
| 642 |
dtypes_after = {p.dtype for p in result.parameters()} |
| 643 |
assert dtypes_after == {torch.bfloat16, torch.float32}, ( |
| 644 |
f"Expected mixed dtypes preserved (Params4bit skip), got {dtypes_after}" |
| 645 |
) |
| 646 |
finally: |
| 647 |
model[0].weight.__class__ = original_class |
| 648 |
|
| 649 |
def test_compile_regions_fsdp2_preserves_block_class(self): |
| 650 |
"""`compile_regions_fsdp2` must use in-place `module.compile()` so module classes are preserved. |
| 651 |
|
| 652 |
`fsdp2_prepare_model`'s auto_wrap_policy uses `isinstance(module, transformer_cls_to_wrap)`. If |
| 653 |
`OptimizedModule`-wrapped blocks were used (as `compile_regions` does), the isinstance check would |
| 654 |
miss them and only the root model would get FSDP-sharded — losing per-layer all-gather/compute overlap. |
| 655 |
""" |
| 656 |
from accelerate.utils import compile_regions_fsdp2 |
| 657 |
|
| 658 |
class Block(torch.nn.Module): |
| 659 |
def __init__(self, dim): |
| 660 |
super().__init__() |
| 661 |
self.linear = torch.nn.Linear(dim, dim) |
| 662 |
|
| 663 |
def forward(self, x): |
| 664 |
return self.linear(x) |
| 665 |
|
| 666 |
class Model(torch.nn.Module): |
| 667 |
def __init__(self, dim, n_blocks): |
| 668 |
super().__init__() |
| 669 |
self.layers = torch.nn.ModuleList([Block(dim) for _ in range(n_blocks)]) |
| 670 |
self.head = torch.nn.Linear(dim, dim) |
| 671 |
|
| 672 |
def forward(self, x): |
| 673 |
for layer in self.layers: |
| 674 |
x = layer(x) |
| 675 |
return self.head(x) |
| 676 |
|
| 677 |
model = Model(dim=8, n_blocks=4) |
| 678 |
block_cls_before = type(model.layers[0]) |
| 679 |
|
| 680 |
result = compile_regions_fsdp2(model, backend="inductor") |
| 681 |
|
| 682 |
# In-place: same Python object returned, no wrapper |
| 683 |
assert result is model |
| 684 |
# Class identity preserved on each repeated block (the FSDP2 auto_wrap invariant) |
| 685 |
assert all(type(b) is block_cls_before for b in model.layers) |
| 686 |
assert all(isinstance(b, Block) for b in model.layers) |
| 687 |
assert not any(isinstance(b, torch._dynamo.eval_frame.OptimizedModule) for b in model.layers) |
| 688 |
# And each block + non-repeated leaf is compiled in-place |
| 689 |
assert all(getattr(b, "_compiled_call_impl", None) is not None for b in model.layers) |
| 690 |
assert getattr(model.head, "_compiled_call_impl", None) is not None |
| 691 |
|
| 692 |
|
| 693 |
@run_first |
| 694 |
# Skip this test when TorchXLA is available because accelerate.launch does not support TorchXLA FSDP. |
| 695 |
@require_non_torch_xla |
| 696 |
@require_multi_device |
| 697 |
@slow |
| 698 |
class FSDPIntegrationTest(TempDirTestCase): |
| 699 |
test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps") |
| 700 |
|
| 701 |
def setUp(self): |
| 702 |
super().setUp() |
| 703 |
self.performance_lower_bound = 0.70 if is_hpu_available() else 0.82 |
| 704 |
self.fsdp1_performance_configs = [ |
| 705 |
"fsdp_shard_grad_op_transformer_based_wrap", |
| 706 |
"fsdp_full_shard_transformer_based_wrap", |
| 707 |
] |
| 708 |
# FSDP2 doesn't currently support other than full_shard/no_shard equivalents |
| 709 |
self.fsdp2_performance_configs = ["fsdp_full_shard_transformer_based_wrap"] |
| 710 |
self.performance_configs = { |
| 711 |
1: self.fsdp1_performance_configs, |
| 712 |
2: self.fsdp2_performance_configs, |
| 713 |
} |
| 714 |
|
| 715 |
self.fsdp1_peak_memory_usage_upper_bound = { |
| 716 |
"multi_gpu_fp16": 3200, |
| 717 |
"fsdp_shard_grad_op_transformer_based_wrap_fp16": 2000, |
| 718 |
"fsdp_full_shard_transformer_based_wrap_fp16": 1900, |
| 719 |
# Disabling below test as it overwhelms the RAM memory usage |
| 720 |
# on CI self-hosted runner leading to tests getting killed. |
| 721 |
# "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang |
| 722 |
} |
| 723 |
self.fsdp2_peak_memory_usage_upper_bound = { |
| 724 |
"multi_gpu_fp16": 3200, |
| 725 |
"fsdp_full_shard_transformer_based_wrap_fp16": 1900, |
| 726 |
} |
| 727 |
self.peak_memory_usage_upper_bound = { |
| 728 |
1: self.fsdp1_peak_memory_usage_upper_bound, |
| 729 |
2: self.fsdp2_peak_memory_usage_upper_bound, |
| 730 |
} |
| 731 |
self.n_train = 160 |
| 732 |
self.n_val = 160 |
| 733 |
|
| 734 |
self.current_fsdp_version = 1 |
| 735 |
|
| 736 |
@require_fsdp2 |
| 737 |
def test_fsdp2_mixed_precision_bf16_with_bf16_model_loaded(self): |
| 738 |
"""FSDP2 + `mixed_precision=bf16` with the model loaded in bf16.""" |
| 739 |
cmd = get_launch_command( |
| 740 |
num_processes=2, |
| 741 |
num_machines=1, |
| 742 |
machine_rank=0, |
| 743 |
use_fsdp=True, |
| 744 |
fsdp_version=2, |
| 745 |
mixed_precision="bf16", |
| 746 |
) |
| 747 |
cmd.extend( |
| 748 |
[ |
| 749 |
"--fsdp_reshard_after_forward=true", |
| 750 |
"--fsdp_auto_wrap_policy=TRANSFORMER_BASED_WRAP", |
| 751 |
"--fsdp_transformer_layer_cls_to_wrap=BertLayer", |
| 752 |
"--fsdp_cpu_ram_efficient_loading=true", |
| 753 |
str(self.test_scripts_folder / "test_performance.py"), |
| 754 |
f"--output_dir={self.tmpdir}", |
| 755 |
"--num_epochs=1", |
| 756 |
"--model_dtype=bfloat16", |
| 757 |
] |
| 758 |
) |
| 759 |
# If the regression returns, this hangs forever — keep the test bounded. |
| 760 |
execute_subprocess_async(cmd, timeout=180) |
| 761 |
|
| 762 |
@require_fp16 |
| 763 |
def test_performance(self): |
| 764 |
self.test_file_path = self.test_scripts_folder / "test_performance.py" |
| 765 |
fsdp_version = self.current_fsdp_version |
| 766 |
cmd = get_launch_command( |
| 767 |
num_processes=2, num_machines=1, machine_rank=0, use_fsdp=True, fsdp_version=self.current_fsdp_version |
| 768 |
) |
| 769 |
for config in self.performance_configs[fsdp_version]: |
| 770 |
cmd_config = cmd.copy() |
| 771 |
cmd_config.append(f"--fsdp_version={fsdp_version}") |
| 772 |
for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): |
| 773 |
if fsdp_version == 2 and strategy != "FULL_SHARD": |
| 774 |
continue |
| 775 |
if strategy.lower() in config: |
| 776 |
if fsdp_version == 1: |
| 777 |
cmd_config.append(f"--fsdp_sharding_strategy={strategy}") |
| 778 |
else: |
| 779 |
# FSDP2 uses `reshard_after_forward` instead of `sharding_strategy` and is true unless we test `NO_SHARD` (we don't) |
| 780 |
cmd_config.append("--fsdp_reshard_after_forward=true") |
| 781 |
break |
| 782 |
|
| 783 |
if "fp32" in config: |
| 784 |
cmd_config.append("--mixed_precision=no") |
| 785 |
else: |
| 786 |
cmd_config.append("--mixed_precision=fp16") |
| 787 |
|
| 788 |
if "cpu_offload" in config: |
| 789 |
cmd_config.append("--fsdp_offload_params=True") |
| 790 |
|
| 791 |
for policy in FSDP_AUTO_WRAP_POLICY: |
| 792 |
if policy.lower() in config: |
| 793 |
cmd_config.append(f"--fsdp_auto_wrap_policy={policy}") |
| 794 |
break |
| 795 |
|
| 796 |
if policy == "TRANSFORMER_BASED_WRAP": |
| 797 |
cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer") |
| 798 |
elif policy == "SIZE_BASED_WRAP": |
| 799 |
cmd_config.append("--fsdp_min_num_params=2000") |
| 800 |
|
| 801 |
cmd_config.extend( |
| 802 |
[ |
| 803 |
self.test_file_path, |
| 804 |
f"--output_dir={self.tmpdir}", |
| 805 |
f"--performance_lower_bound={self.performance_lower_bound}", |
| 806 |
] |
| 807 |
) |
| 808 |
|
| 809 |
with patch_environment(omp_num_threads=1): |
| 810 |
execute_subprocess_async(cmd_config) |
| 811 |
|
| 812 |
@require_fp16 |
| 813 |
def test_checkpointing(self): |
| 814 |
self.test_file_path = self.test_scripts_folder / "test_checkpointing.py" |
| 815 |
fsdp_version = self.current_fsdp_version |
| 816 |
cmd = get_launch_command( |
| 817 |
num_processes=2, |
| 818 |
num_machines=1, |
| 819 |
machine_rank=0, |
| 820 |
use_fsdp=True, |
| 821 |
mixed_precision="fp16", |
| 822 |
fsdp_transformer_layer_cls_to_wrap="BertLayer", |
| 823 |
fsdp_version=fsdp_version, |
| 824 |
) |
| 825 |
|
| 826 |
for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): |
| 827 |
fsdp_state_dict_types = FSDP_STATE_DICT_TYPE if fsdp_version == 1 else FSDP2_STATE_DICT_TYPE |
| 828 |
cmd_config = cmd.copy() |
| 829 |
if fsdp_version == 1: |
| 830 |
cmd_config.append(f"--fsdp_sharding_strategy={strategy}") |
| 831 |
else: |
| 832 |
cmd_config.append("--fsdp_reshard_after_forward=true") |
| 833 |
if strategy != "FULL_SHARD": |
| 834 |
continue |
| 835 |
state_dict_config_index = len(cmd_config) |
| 836 |
for state_dict_type in fsdp_state_dict_types: |
| 837 |
# Todo: Currently failing for `LOCAL_STATE_DICT` with error |
| 838 |
# Unexpected key(s) in state_dict: "_fsdp_wrapped_module._flat_param". |
| 839 |
if state_dict_type == "LOCAL_STATE_DICT": |
| 840 |
continue |
| 841 |
|
| 842 |
cmd_config = cmd_config[:state_dict_config_index] |
| 843 |
cmd_config.append(f"--fsdp_state_dict_type={state_dict_type}") |
| 844 |
cmd_config.extend( |
| 845 |
[ |
| 846 |
self.test_file_path, |
| 847 |
f"--output_dir={self.tmpdir}", |
| 848 |
"--partial_train_epoch=1", |
| 849 |
] |
| 850 |
) |
| 851 |
with patch_environment(omp_num_threads=1): |
| 852 |
execute_subprocess_async(cmd_config) |
| 853 |
|
| 854 |
cmd_config = cmd_config[:-1] |
| 855 |
resume_from_checkpoint = os.path.join(self.tmpdir, "epoch_0") |
| 856 |
cmd_config.extend( |
| 857 |
[ |
| 858 |
f"--resume_from_checkpoint={resume_from_checkpoint}", |
| 859 |
] |
| 860 |
) |
| 861 |
with patch_environment(omp_num_threads=1): |
| 862 |
execute_subprocess_async(cmd_config) |
| 863 |
|
| 864 |
@require_fp16 |
| 865 |
def test_peak_memory_usage(self): |
| 866 |
self.test_file_path = self.test_scripts_folder / "test_peak_memory_usage.py" |
| 867 |
fsdp_version = self.current_fsdp_version |
| 868 |
cmd = get_launch_command(num_processes=2, num_machines=1, machine_rank=0, fsdp_version=fsdp_version) |
| 869 |
for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound[fsdp_version].items(): |
| 870 |
cmd_config = cmd.copy() |
| 871 |
if "fp16" in spec: |
| 872 |
cmd_config.extend(["--mixed_precision=fp16"]) |
| 873 |
else: |
| 874 |
cmd_config.extend(["--mixed_precision=no"]) |
| 875 |
|
| 876 |
if "multi_gpu" in spec: |
| 877 |
continue |
| 878 |
else: |
| 879 |
cmd_config.extend(["--use_fsdp"]) |
| 880 |
for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): |
| 881 |
if fsdp_version == 2 and strategy != "FULL_SHARD": |
| 882 |
continue |
| 883 |
if strategy.lower() in spec: |
| 884 |
if fsdp_version == 1: |
| 885 |
cmd_config.append(f"--fsdp_sharding_strategy={strategy}") |
| 886 |
else: |
| 887 |
cmd_config.append("--fsdp_reshard_after_forward=true") |
| 888 |
break |
| 889 |
|
| 890 |
if "cpu_offload" in spec: |
| 891 |
cmd_config.append("--fsdp_offload_params=True") |
| 892 |
|
| 893 |
for policy in FSDP_AUTO_WRAP_POLICY: |
| 894 |
if policy.lower() in spec: |
| 895 |
cmd_config.append(f"--fsdp_auto_wrap_policy={policy}") |
| 896 |
break |
| 897 |
|
| 898 |
if policy == "TRANSFORMER_BASED_WRAP": |
| 899 |
cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer") |
| 900 |
elif policy == "SIZE_BASED_WRAP": |
| 901 |
cmd_config.append("--fsdp_min_num_params=2000") |
| 902 |
|
| 903 |
cmd_config.extend( |
| 904 |
[ |
| 905 |
self.test_file_path, |
| 906 |
f"--output_dir={self.tmpdir}", |
| 907 |
f"--peak_memory_upper_bound={peak_mem_upper_bound}", |
| 908 |
f"--n_train={self.n_train}", |
| 909 |
f"--n_val={self.n_val}", |
| 910 |
] |
| 911 |
) |
| 912 |
with patch_environment(omp_num_threads=1): |
| 913 |
execute_subprocess_async(cmd_config) |
| 914 |
|
| 915 |
|
| 916 |
@require_fsdp2 |
| 917 |
@run_first |
| 918 |
# Skip this test when TorchXLA is available because accelerate.launch does not support TorchXLA FSDP. |
| 919 |
@require_non_torch_xla |
| 920 |
@require_multi_device |
| 921 |
@slow |
| 922 |
class FSDP2IntegrationTest(FSDPIntegrationTest): |
| 923 |
def setUp(self): |
| 924 |
super().setUp() |
| 925 |
self.current_fsdp_version = 2 |