library
stringclasses
1 value
test_file
stringclasses
785 values
test_function
stringlengths
1
295
before
stringlengths
0
448k
after
stringlengths
0
487k
context_before
stringclasses
947 values
context_after
stringlengths
0
16.3k
commit_before
stringclasses
1 value
commit_after
stringclasses
1 value
change_type
stringclasses
3 values
torch
test/distributed/fsdp/test_fsdp_misc.py
forward
def forward(self, x): return x
def forward(self, x, y): return self.b(self.a(x + y))
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
__init__
def __init__(self): super().__init__() self.lin = nn.Linear(100, 100)
def __init__(self) -> None: super().__init__() self.a = nn.Linear(2, 2) self.b = nn.Linear(2, 2)
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_memory.py
forward
def forward(self, x): if self.with_checkpoint: return self.head(checkpoint(self.blocks, self.stem(x))) else: return self.head(self.blocks(self.stem(x)))
def forward(self, x): if self.with_checkpoint: return self.head(checkpoint(self.blocks, self.stem(x), use_reentrant=True)) else: return self.head(self.blocks(self.stem(x)))
import sys import torch import torch.nn as nn import torch.optim as optim from torch import distributed as dist from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) from torch.utils.checkpoint import checkpoint class Model(nn.Module):
import sys import torch import torch.nn as nn import torch.optim as optim from torch import distributed as dist from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) from torch.utils.checkpoint import checkpoint class Model(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_meta.py
_reset_params_if_meta
def _reset_params_if_meta(is_meta, model): # For torchdistX init, we don't need to call reset_params, as # deferred_init(model).materialize() is equivalent to model(). if is_meta: model.reset_parameters() class MyLinear(nn.Linear): """ Linear layer with deterministic reset_parameters for testing. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def reset_parameters(self, *args, **kwargs): with torch.no_grad(): self.weight.fill_(1) class MyModel(nn.Module): def __init__(self, device): super().__init__() self.lin1 = MyLinear(2, 2, bias=False, device=device) self.lin2 = MyLinear(2, 2, bias=False, device=device) def forward(self, x): return self.lin2(self.lin1(x)) def reset_parameters(self, *args, **kwargs): for m in [self.lin1, self.lin2]: if not isinstance(m, FSDP): m.reset_parameters() class NestedModel(nn.Module): def __init__(self, device): super().__init__() self.lin1 = MyLinear(2, 2, bias=False, device=device) self.lin1 = wrap(self.lin1) self.lin2 = MyLinear(2, 2, bias=False, device=device) self.l3 = MyModel(device=device) self.l3 = wrap(self.l3) def forward(self, x): return self.l3(self.lin2(self.lin1(x))) def reset_parameters(self): for m in [self.lin1, self.lin2, self.l3]: if not isinstance(m, FSDP): m.reset_parameters()
def _reset_params_if_meta(is_meta: bool, model: nn.Module): # For torchdistX init, we don't need to call reset_params, as # deferred_init(model).materialize() is equivalent to model(). if is_meta: for module in model.modules(): # Assume that a module has `reset_parameters()` iff it has directly # managed parameters or buffers if hasattr(module, "reset_parameters"): module.reset_parameters() class MyLinear(nn.Linear): """ Linear layer with deterministic reset_parameters for testing. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def reset_parameters(self, *args, **kwargs): torch.manual_seed(42) with torch.no_grad(): # Use an initialization method that depends on shape torch.nn.init.xavier_uniform_(self.weight, 1.0) class MyBuffer(nn.Module): def __init__(self, device: torch.device): super().__init__() self.buf = torch.nn.Buffer(torch.empty((3, 3), device=device)) def reset_parameters(self, *args, **kwargs): torch.manual_seed(42) # Use an initialization method that depends on shape torch.nn.init.xavier_uniform_(self.buf, 0.5) class MyModel(nn.Module): def __init__(self, device: torch.device): super().__init__() self.lin1 = MyLinear(2, 2, bias=False, device=device) self.lin2 = MyLinear(2, 2, bias=False, device=device) self.buf_mod = MyBuffer(device) def forward(self, x): return self.lin2(self.lin1(x)) class NestedModel(nn.Module): def __init__(self, device): super().__init__() self.lin1 = MyLinear(2, 2, bias=False, device=device) self.lin1 = wrap(self.lin1) self.lin2 = MyLinear(2, 2, bias=False, device=device) self.l3 = MyModel(device=device) self.l3 = wrap(self.l3) def forward(self, x): return self.l3(self.lin2(self.lin1(x)))
import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init
import itertools import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_meta.py
reset_parameters
def reset_parameters(self, *args, **kwargs): with torch.no_grad(): self.weight.fill_(1)
def reset_parameters(self, *args, **kwargs): torch.manual_seed(42) with torch.no_grad(): # Use an initialization method that depends on shape torch.nn.init.xavier_uniform_(self.weight, 1.0)
import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init class MyLinear(nn.Linear):
import itertools import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init class MyLinear(nn.Linear):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_meta.py
reset_parameters
def reset_parameters(self, *args, **kwargs): with torch.no_grad(): self.weight.fill_(1)
def reset_parameters(self, *args, **kwargs): torch.manual_seed(42) with torch.no_grad(): # Use an initialization method that depends on shape torch.nn.init.xavier_uniform_(self.weight, 1.0)
import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init class MyLinear(nn.Linear):
import itertools import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init class MyLinear(nn.Linear):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_meta.py
reset_parameters
def reset_parameters(self, *args, **kwargs): with torch.no_grad(): self.weight.fill_(1)
def reset_parameters(self, *args, **kwargs): torch.manual_seed(42) with torch.no_grad(): # Use an initialization method that depends on shape torch.nn.init.xavier_uniform_(self.weight, 1.0)
import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init class MyLinear(nn.Linear):
import itertools import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init class MyLinear(nn.Linear):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_meta.py
reset_parameters
def reset_parameters(self, *args, **kwargs): with torch.no_grad(): self.weight.fill_(1)
def reset_parameters(self, *args, **kwargs): torch.manual_seed(42) with torch.no_grad(): # Use an initialization method that depends on shape torch.nn.init.xavier_uniform_(self.weight, 1.0)
import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init class MyLinear(nn.Linear):
import itertools import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init class MyLinear(nn.Linear):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_meta.py
_init_with_reset_params
def _init_with_reset_params(module): """ to_empty + reset_parameters() init function example for modules initailized with device="meta" """ is_meta = any(t.is_meta for t in module.parameters()) if is_meta: module.to_empty(device=torch.cuda.current_device()) with torch.no_grad(): module.reset_parameters()
def _init_with_reset_params(module: nn.Module): """ to_empty + reset_parameters() init function example for modules initialized with device="meta" """ has_meta_states = any( t.is_meta for t in itertools.chain( module.parameters(recurse=False), module.buffers(recurse=False) ) ) if has_meta_states: device = torch.device("cuda", torch.cuda.current_device()) module.to_empty(device=device, recurse=False) module.reset_parameters()
import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init
import itertools import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_meta.py
_init_with_torchdistX
def _init_with_torchdistX(module): """ torchdistX-based deferred module initialization function example using ``materialize_module``. """ assert _TORCHDISTX_AVAIL def check_fn(k): return not isinstance(k, FSDP) deferred_init.materialize_module(module, check_fn=check_fn) class TestFSDPWithMetaDevice(FSDPTest): @property def world_size(self): return 2 @property def process_group(self): return dist.distributed_c10d._get_default_group() def _compare_fsdp(self, fsdp1, fsdp2): with FSDP.summon_full_params(fsdp1): with FSDP.summon_full_params(fsdp2): for p1, p2 in zip(fsdp1.parameters(), fsdp2.parameters()): self.assertTrue(torch.allclose(p1, p2), f"{p1} vs {p2}") def _test_simple_model_with_meta_device(self, meta_module_fn, init_fn=None): # Create model on meta device and wrap with FSDP. model = meta_module_fn() is_meta = next(model.parameters()).is_meta fsdp_meta = FSDP( model, auto_wrap_policy=always_wrap, param_init_fn=init_fn, ) meta_opt = torch.optim.SGD(fsdp_meta.parameters(), lr=1e-3) # Test to make sure it is the same model parameters as regular FSDP # approach. regular = MyModel(device="cuda") _reset_params_if_meta(is_meta, regular) fsdp_regular = FSDP(regular, auto_wrap_policy=always_wrap) regular_opt = torch.optim.SGD(fsdp_regular.parameters(), lr=1e-3) self._compare_fsdp(fsdp_meta, fsdp_regular) inp = torch.randn(10, 2, device="cuda") fsdp_meta(inp).sum().backward() fsdp_regular(inp).sum().backward() meta_opt.step() regular_opt.step() self._compare_fsdp(fsdp_meta, fsdp_regular) # Test that meta init works if all submodules are contained in only a # single FSDP unit. model = meta_module_fn() fsdp_meta = FSDP(model, param_init_fn=init_fn) meta_opt = torch.optim.SGD(fsdp_meta.parameters(), lr=1e-3) regular = MyModel(device="cuda") _reset_params_if_meta(is_meta, regular) fsdp_regular = FSDP(regular, auto_wrap_policy=always_wrap) regular_opt = torch.optim.SGD(fsdp_regular.parameters(), lr=1e-3) # Run a forward + backward pass + optimizer step fsdp_meta(inp).sum().backward() fsdp_regular(inp).sum().backward() meta_opt.step() regular_opt.step() self._compare_fsdp(fsdp_meta, fsdp_regular) @skip_if_lt_x_gpu(2) def test_simple_model_with_meta_device_reset_params(self): def meta_module_fn(): return MyModel(device="meta") self._test_simple_model_with_meta_device( meta_module_fn, _init_with_reset_params ) @skip_if_lt_x_gpu(2) def test_simple_model_with_meta_device_default_init(self): def meta_module_fn(): return MyModel(device="meta") self._test_simple_model_with_meta_device(meta_module_fn) @skip_if_lt_x_gpu(2) @sandcastle_skip_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) def test_simple_model_with_torchdistX_default_init(self): def meta_module_fn(): return deferred_init.deferred_init(MyModel, device="cuda") self._test_simple_model_with_meta_device(meta_module_fn) @skip_if_lt_x_gpu(2) @sandcastle_skip_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) def test_simple_model_with_torchdistX_init_fn(self): def meta_module_fn(): return deferred_init.deferred_init(MyModel, device="cuda") self._test_simple_model_with_meta_device( meta_module_fn, init_fn=_init_with_torchdistX ) def _test_nested_model_with_meta_device( self, auto_wrap, meta_module_fn, init_fn=None ): if auto_wrap: module = meta_module_fn() is_meta = next(module.parameters()).is_meta fsdp_meta = FSDP( module, auto_wrap_policy=always_wrap, param_init_fn=init_fn, ) meta_opt = torch.optim.SGD(fsdp_meta.parameters(), lr=1e-3) module_regular = NestedModel(device="cuda") _reset_params_if_meta(is_meta, module_regular) fsdp_regular = FSDP( module_regular, auto_wrap_policy=always_wrap, ) regular_opt = torch.optim.SGD(fsdp_regular.parameters(), lr=1e-3) else: with enable_wrap( wrapper_cls=FSDP, param_init_fn=init_fn, ): module = meta_module_fn() is_meta = next(module.parameters()).is_meta # Non FSDP modules will still be initialized because they bubble up # to be part of a larger FSDP unit. fsdp_meta = wrap(module) meta_opt = torch.optim.SGD(fsdp_meta.parameters(), lr=1e-3) # Init and reset parameters before wrapping so that reset_params # matches up with meta device's initialization. module_regular = NestedModel(device="cuda") _reset_params_if_meta(is_meta, module_regular) with enable_wrap(wrapper_cls=FSDP): module_regular.lin1 = wrap(module_regular.lin1) module_regular.l3 = wrap(module_regular.l3) fsdp_regular = wrap(module_regular) regular_opt = torch.optim.SGD(fsdp_regular.parameters(), lr=1e-3) # Compare it before training self._compare_fsdp(fsdp_meta, fsdp_regular) inp = torch.randn(10, 2, device="cuda") fsdp_meta(inp).sum().backward() fsdp_regular(inp).sum().backward() meta_opt.step() regular_opt.step() self._compare_fsdp(fsdp_meta, fsdp_regular) @skip_if_lt_x_gpu(2) @parametrize("auto_wrap", [True, False]) def test_nested_model_with_meta_device_reset_params(self, auto_wrap): def meta_module_fn(): return NestedModel(device="meta") self._test_nested_model_with_meta_device( auto_wrap=auto_wrap, meta_module_fn=meta_module_fn, init_fn=_init_with_reset_params, ) @skip_if_lt_x_gpu(2) @parametrize("auto_wrap", [True, False]) def test_nested_model_with_meta_device_default_init(self, auto_wrap): def meta_module_fn(): return NestedModel(device="meta") self._test_nested_model_with_meta_device( auto_wrap=auto_wrap, meta_module_fn=meta_module_fn, ) @skip_if_lt_x_gpu(2) @sandcastle_skip_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) @parametrize("auto_wrap", [True, False]) def test_nested_model_with_torchdistX_default_init(self, auto_wrap): def meta_module_fn(): return deferred_init.deferred_init(NestedModel, device="cuda") self._test_nested_model_with_meta_device( auto_wrap=auto_wrap, meta_module_fn=meta_module_fn ) @skip_if_lt_x_gpu(2) @sandcastle_skip_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) @parametrize("auto_wrap", [True, False]) def test_nested_model_with_torchdistX_init_fn(self, auto_wrap): def meta_module_fn(): return deferred_init.deferred_init(NestedModel, device="cuda") self._test_nested_model_with_meta_device( auto_wrap=auto_wrap, meta_module_fn=meta_module_fn, init_fn=_init_with_torchdistX, ) def _test_bad_arg(self, meta_module_fn): mod = meta_module_fn() with self.assertRaisesRegex(ValueError, "to be callable"): FSDP(mod, param_init_fn=42) @skip_if_lt_x_gpu(2) @sandcastle_skip_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) def test_bad_arg_torchdistx(self): def meta_module_fn(): return deferred_init.deferred_init(NestedModel, "cuda") self._test_bad_arg(meta_module_fn) @skip_if_lt_x_gpu(2) def test_bad_arg_meta(self): def meta_module_fn(): return NestedModel(device="meta") self._test_bad_arg(meta_module_fn) @skip_if_lt_x_gpu(2) def test_meta_device_with_mixed_precision(self): """ Tests meta device initialization with a ``param_init_fn`` when specifying mixed precision with ``param_dtype=torch.float32``. """ class FakeLinear(nn.Module): def __init__( self, in_dim: int, out_dim: int, device: Union[torch.device, str] ) -> None: super().__init__() self.weight = nn.Parameter( torch.randn((in_dim, out_dim), device=device) ) def forward(self, x: torch.Tensor) -> torch.Tensor: return x @ self.weight class Model(nn.Module): def __init__(self) -> None: super().__init__() self.lin1 = nn.Linear(5, 5, device="meta") self.lin2 = FakeLinear(5, 5, device="meta") self.relu = nn.ReLU() def forward(self, x: torch.Tensor) -> torch.Tensor: return self.lin2(self.relu(self.lin1(x))) def _module_init_fn(self, module: nn.Module): if isinstance(module, nn.Linear): torch.nn.init.normal_(module.weight, mean=0.0, std=0.1) if module.bias is not None: torch.nn.init.zeros_(module.bias) def _param_init_fn(module: nn.Module) -> None: # TODO: `module.to_empty()` is not generally correct for meta # device initialization. # https://github.com/pytorch/pytorch/issues/90465 module.to_empty(device=torch.device("cuda")) module.apply(model._module_init_fn) model = Model() # Wrap `lin1` and the top level `model` to create nested FSDP instances # where each instance has parameters FSDP( model, auto_wrap_policy=ModuleWrapPolicy({nn.Linear}), mixed_precision=MixedPrecision( param_dtype=torch.float32, reduce_dtype=torch.float16 ), param_init_fn=_param_init_fn, device_id=torch.cuda.current_device(), ) instantiate_parametrized_tests(TestFSDPWithMetaDevice) if __name__ == "__main__": run_tests()
def _init_with_torchdistX(module: nn.Module): """ torchdistX-based deferred module initialization function example using ``materialize_module``. """ assert _TORCHDISTX_AVAIL def check_fn(k): return not isinstance(k, FSDP) deferred_init.materialize_module(module, check_fn=check_fn) class TestFSDPWithMetaDevice(FSDPTest): @property def world_size(self): return 2 @property def process_group(self): return dist.distributed_c10d._get_default_group() def _compare_fsdp(self, fsdp1, fsdp2): with FSDP.summon_full_params(fsdp1): with FSDP.summon_full_params(fsdp2): for p1, p2 in zip(fsdp1.parameters(), fsdp2.parameters()): self.assertTrue(torch.allclose(p1, p2), f"{p1} vs {p2}") def _test_simple_model_with_meta_device(self, meta_module_fn, init_fn=None): # Create model on meta device and wrap with FSDP. model = meta_module_fn() is_meta = next(model.parameters()).is_meta fsdp_meta = FSDP( model, auto_wrap_policy=always_wrap, param_init_fn=init_fn, ) meta_opt = torch.optim.SGD(fsdp_meta.parameters(), lr=1e-3) # Test to make sure it is the same model parameters as regular FSDP # approach. regular = MyModel(device="cuda") _reset_params_if_meta(is_meta, regular) fsdp_regular = FSDP(regular, auto_wrap_policy=always_wrap) regular_opt = torch.optim.SGD(fsdp_regular.parameters(), lr=1e-3) self._compare_fsdp(fsdp_meta, fsdp_regular) inp = torch.randn(10, 2, device="cuda") fsdp_meta(inp).sum().backward() fsdp_regular(inp).sum().backward() meta_opt.step() regular_opt.step() self._compare_fsdp(fsdp_meta, fsdp_regular) # Test that meta init works if all submodules are contained in only a # single FSDP unit. model = meta_module_fn() fsdp_meta = FSDP(model, param_init_fn=init_fn) meta_opt = torch.optim.SGD(fsdp_meta.parameters(), lr=1e-3) regular = MyModel(device="cuda") _reset_params_if_meta(is_meta, regular) fsdp_regular = FSDP(regular, auto_wrap_policy=always_wrap) regular_opt = torch.optim.SGD(fsdp_regular.parameters(), lr=1e-3) # Run a forward + backward pass + optimizer step fsdp_meta(inp).sum().backward() fsdp_regular(inp).sum().backward() meta_opt.step() regular_opt.step() self._compare_fsdp(fsdp_meta, fsdp_regular) @skip_if_lt_x_gpu(2) def test_simple_model_with_meta_device_reset_params(self): def meta_module_fn(): return MyModel(device="meta") self._test_simple_model_with_meta_device( meta_module_fn, _init_with_reset_params ) @skip_if_lt_x_gpu(2) def test_simple_model_with_meta_device_default_init(self): def meta_module_fn(): return MyModel(device="meta") self._test_simple_model_with_meta_device(meta_module_fn) @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) def test_simple_model_with_torchdistX_default_init(self): def meta_module_fn(): return deferred_init.deferred_init(MyModel, device="cuda") self._test_simple_model_with_meta_device(meta_module_fn) @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) def test_simple_model_with_torchdistX_init_fn(self): def meta_module_fn(): return deferred_init.deferred_init(MyModel, device="cuda") self._test_simple_model_with_meta_device( meta_module_fn, init_fn=_init_with_torchdistX ) def _test_nested_model_with_meta_device( self, auto_wrap, meta_module_fn, init_fn=None ): if auto_wrap: module = meta_module_fn() is_meta = ( next(module.parameters()).is_meta or next(module.buffers()).is_meta ) fsdp_meta = FSDP( module, auto_wrap_policy=always_wrap, param_init_fn=init_fn, ) meta_opt = torch.optim.SGD(fsdp_meta.parameters(), lr=1e-3) module_regular = NestedModel(device="cuda") _reset_params_if_meta(is_meta, module_regular) fsdp_regular = FSDP( module_regular, auto_wrap_policy=always_wrap, ) regular_opt = torch.optim.SGD(fsdp_regular.parameters(), lr=1e-3) else: with enable_wrap( wrapper_cls=FSDP, param_init_fn=init_fn, ): module = meta_module_fn() is_meta = next(module.parameters()).is_meta # Non FSDP modules will still be initialized because they bubble up # to be part of a larger FSDP unit. fsdp_meta = wrap(module) meta_opt = torch.optim.SGD(fsdp_meta.parameters(), lr=1e-3) # Init and reset parameters before wrapping so that reset_params # matches up with meta device's initialization. module_regular = NestedModel(device="cuda") _reset_params_if_meta(is_meta, module_regular) with enable_wrap(wrapper_cls=FSDP): module_regular.lin1 = wrap(module_regular.lin1) module_regular.l3 = wrap(module_regular.l3) fsdp_regular = wrap(module_regular) regular_opt = torch.optim.SGD(fsdp_regular.parameters(), lr=1e-3) # Compare it before training self._compare_fsdp(fsdp_meta, fsdp_regular) inp = torch.randn(10, 2, device="cuda") fsdp_meta(inp).sum().backward() fsdp_regular(inp).sum().backward() meta_opt.step() regular_opt.step() self._compare_fsdp(fsdp_meta, fsdp_regular) @skip_if_lt_x_gpu(2) @parametrize("auto_wrap", [True, False]) def test_nested_model_with_meta_device_reset_params(self, auto_wrap): def meta_module_fn(): return NestedModel(device="meta") self._test_nested_model_with_meta_device( auto_wrap=auto_wrap, meta_module_fn=meta_module_fn, init_fn=_init_with_reset_params, ) @skip_if_lt_x_gpu(2) @parametrize("auto_wrap", [True, False]) def test_nested_model_with_meta_device_default_init(self, auto_wrap): def meta_module_fn(): return NestedModel(device="meta") self._test_nested_model_with_meta_device( auto_wrap=auto_wrap, meta_module_fn=meta_module_fn, ) @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) @parametrize("auto_wrap", [True, False]) def test_nested_model_with_torchdistX_default_init(self, auto_wrap): def meta_module_fn(): return deferred_init.deferred_init(NestedModel, device="cuda") self._test_nested_model_with_meta_device( auto_wrap=auto_wrap, meta_module_fn=meta_module_fn ) @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) @parametrize("auto_wrap", [True, False]) def test_nested_model_with_torchdistX_init_fn(self, auto_wrap): def meta_module_fn(): return deferred_init.deferred_init(NestedModel, device="cuda") self._test_nested_model_with_meta_device( auto_wrap=auto_wrap, meta_module_fn=meta_module_fn, init_fn=_init_with_torchdistX, ) def _test_bad_arg(self, meta_module_fn): mod = meta_module_fn() with self.assertRaisesRegex(ValueError, "to be callable"): FSDP(mod, param_init_fn=42) @skip_if_lt_x_gpu(2) @skip_but_pass_in_sandcastle_if( not _TORCHDISTX_AVAIL, "Test requires torchdistX: https://github.com/pytorch/torchdistX", ) def test_bad_arg_torchdistx(self): def meta_module_fn(): return deferred_init.deferred_init(NestedModel, "cuda") self._test_bad_arg(meta_module_fn) @skip_if_lt_x_gpu(2) def test_bad_arg_meta(self): def meta_module_fn(): return NestedModel(device="meta") self._test_bad_arg(meta_module_fn) @skip_if_lt_x_gpu(2) def test_meta_device_with_mixed_precision(self): """ Tests meta device initialization with a ``param_init_fn`` when specifying mixed precision with ``param_dtype=torch.float32``. """ class FakeLinear(nn.Module): def __init__( self, in_dim: int, out_dim: int, device: Union[torch.device, str] ) -> None: super().__init__() self.weight = nn.Parameter( torch.randn((in_dim, out_dim), device=device) ) def forward(self, x: torch.Tensor) -> torch.Tensor: return x @ self.weight class Model(nn.Module): def __init__(self) -> None: super().__init__() self.lin1 = nn.Linear(5, 5, device="meta") self.lin2 = FakeLinear(5, 5, device="meta") self.relu = nn.ReLU() def forward(self, x: torch.Tensor) -> torch.Tensor: return self.lin2(self.relu(self.lin1(x))) def _module_init_fn(self, module: nn.Module): if isinstance(module, nn.Linear): torch.nn.init.normal_(module.weight, mean=0.0, std=0.1) if module.bias is not None: torch.nn.init.zeros_(module.bias) def _param_init_fn(module: nn.Module) -> None: # TODO: `module.to_empty()` is not generally correct for meta # device initialization. # https://github.com/pytorch/pytorch/issues/90465 module.to_empty(device=torch.device("cuda")) module.apply(model._module_init_fn) model = Model() # Wrap `lin1` and the top level `model` to create nested FSDP instances # where each instance has parameters FSDP( model, auto_wrap_policy=ModuleWrapPolicy({nn.Linear}), mixed_precision=MixedPrecision( param_dtype=torch.float32, reduce_dtype=torch.float16 ), param_init_fn=_param_init_fn, device_id=torch.cuda.current_device(), ) instantiate_parametrized_tests(TestFSDPWithMetaDevice) if __name__ == "__main__": run_tests()
import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init
import itertools import sys from typing import Union import torch import torch.distributed as dist import torch.nn as nn from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, MixedPrecision from torch.distributed.fsdp.wrap import ( always_wrap_policy as always_wrap, enable_wrap, ModuleWrapPolicy, wrap, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) _TORCHDISTX_AVAIL = True from torchdistx import deferred_init
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_ignored_modules.py
test_ignored_states_auto_wrap
def test_ignored_states_auto_wrap(self): transformer_policy = functools.partial( transformer_auto_wrap_policy, transformer_layer_cls={nn.Sequential} ) self.run_subtests( { "policy": [transformer_policy, ModuleWrapPolicy((nn.Sequential,))], "ignore_bias": [True, False], }, self._test_ignored_states_auto_wrap, )
import functools import math import sys import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp._common_utils import _get_module_fsdp_state from torch.distributed.fsdp.wrap import ModuleWrapPolicy, transformer_auto_wrap_policy from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestFSDPIgnoredModules(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_misc.py
init_nested_wrapped_module
def init_nested_wrapped_module(): return NestedWrappedModule.init( self.process_group, FSDPInitMode.NO_FSDP, CUDAInitMode.CUDA_NEVER, ) with self.assertRaisesRegex( ValueError, "The module has CPU parameters or buffers when `sync_module_states=True`", ): FSDP( init_nested_wrapped_module(), self.process_group, sync_module_states=True, ) # Check that `device_id` with `sync_module_states=True` works nested_wrapped_module = init_nested_wrapped_module() nested_wrapped_module.buf = nn.Buffer( torch.ones((2, 2), device="cpu") * self.rank ) nested_wrapped_module.module[0].buf = nn.Buffer( torch.ones((3, 2), device="cpu") * self.rank ) nested_wrapped_module = FSDP( nested_wrapped_module, self.process_group, auto_wrap_policy=ModuleWrapPolicy({nn.Linear}), device_id=torch.cuda.current_device(), sync_module_states=True, ) # Each rank's buffers should be 0s since rank 0 is the source, and they # should be on GPU since we specified `device_id` self.assertEqual( nested_wrapped_module.buf.device, torch.device("cuda", torch.cuda.current_device()), ) self.assertEqual(nested_wrapped_module.buf, torch.zeros((2, 2))) self.assertEqual( nested_wrapped_module.module.module[0].buf.device, torch.device("cuda", torch.cuda.current_device()), ) self.assertEqual( nested_wrapped_module.module.module[0].buf, torch.zeros((3, 2)) )
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_misc.py
forward
def forward(self, x): return x
def forward(self, x, y): return self.b(self.a(x + y))
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
forward
def forward(self, x): return x
def forward(self, x, y): return self.b(self.a(x + y))
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
_check_equal
def _check_equal(local, fsdp): with FSDP.summon_full_params(fsdp): for p1, p2 in zip(fsdp.parameters(), local.parameters()): torch.testing.assert_close(p1, p2) for sharding_strategy in [ ShardingStrategy.FULL_SHARD, ShardingStrategy.SHARD_GRAD_OP, ShardingStrategy.NO_SHARD, ]: with self.subTest(sharding_strategy=sharding_strategy): fsdp_ctor = functools.partial(FSDP, sharding_strategy=sharding_strategy) m = MyModule().cuda() m_local = deepcopy(m) local_m = m_local prev_params = [p.clone() for p in m_local.parameters()] m.lin1 = fsdp_ctor(m.lin1) m = fsdp_ctor(m) _check_equal(m_local, m) opt = torch.optim.SGD(m.parameters(), lr=1e-3) opt_local = torch.optim.SGD(local_m.parameters(), lr=1e-3) for i in range(6): t = torch.ones(4, device="cuda") a, b = m(t) local_a, local_b = local_m(t) if i < 2: # use both params in loss computation. Later, # b will go unused and we check grads are the # same as local training. loss = (a @ b).sum() loss_local = (local_a @ local_b).sum() else: loss = a.sum() loss_local = local_a.sum() loss.backward() loss_local.backward() _check_resharded(m) opt.step() opt_local.step() _check_equal(m_local, m) # Ensure at least some change from previous params, otherwise # above check would be vacuously true. self.assertTrue( any( not torch.equal(p1, p2) for p1, p2 in zip(prev_params, m_local.parameters()) ) ) prev_params = [p.clone() for p in local_m.parameters()] opt.zero_grad() opt_local.zero_grad() dist.barrier()
def _check_equal(local, fsdp): with FSDP.summon_full_params(fsdp): for p1, p2 in zip(fsdp.parameters(), local.parameters()): torch.testing.assert_close(p1, p2) fsdp_ctor = functools.partial(FSDP, sharding_strategy=sharding_strategy) m = MyModule().cuda() m_local = deepcopy(m) local_m = m_local prev_params = [p.clone() for p in m_local.parameters()] m.lin1 = fsdp_ctor(m.lin1) m = fsdp_ctor(m) _check_equal(m_local, m) opt = torch.optim.SGD(m.parameters(), lr=1e-3) opt_local = torch.optim.SGD(local_m.parameters(), lr=1e-3) for i in range(6): t = torch.ones(4, device="cuda") a, b = m(t) local_a, local_b = local_m(t) if i < 2: # use both params in loss computation. Later, # b will go unused and we check grads are the # same as local training. loss = (a @ b).sum() loss_local = (local_a @ local_b).sum() else: loss = a.sum() loss_local = local_a.sum() loss.backward() loss_local.backward() _check_resharded(m) opt.step() opt_local.step() _check_equal(m_local, m) # Ensure at least some change from previous params, otherwise # above check would be vacuously true. self.assertTrue( any( not torch.equal(p1, p2) for p1, p2 in zip(prev_params, m_local.parameters()) ) ) prev_params = [p.clone() for p in local_m.parameters()] opt.zero_grad() opt_local.zero_grad() dist.barrier()
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
__init__
def __init__(self): super().__init__() self.lin = nn.Linear(100, 100)
def __init__(self) -> None: super().__init__() self.a = nn.Linear(2, 2) self.b = nn.Linear(2, 2)
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
forward
def forward(self, x): return x
def forward(self, x, y): return self.b(self.a(x + y))
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
forward
def forward(self, x): return x
def forward(self, x, y): return self.b(self.a(x + y))
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
_check_resharded
def _check_resharded(fsdp_module): for handle in fsdp_module._handles: param = handle.flat_param if handle.uses_sharded_strategy: full_param = param._full_param_padded self.assertEqual(full_param.storage().size(), 0) self.assertEqual(param.data_ptr(), param._local_shard.data_ptr())
def _check_resharded(fsdp_module): handle = fsdp_module._handle if not handle: return param = handle.flat_param if handle.uses_sharded_strategy: full_param = param._full_param_padded self.assertEqual(full_param.storage().size(), 0) self.assertEqual(param.data_ptr(), param._local_shard.data_ptr())
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
_check_equal
def _check_equal(local, fsdp): with FSDP.summon_full_params(fsdp): for p1, p2 in zip(fsdp.parameters(), local.parameters()): torch.testing.assert_close(p1, p2) for sharding_strategy in [ ShardingStrategy.FULL_SHARD, ShardingStrategy.SHARD_GRAD_OP, ShardingStrategy.NO_SHARD, ]: with self.subTest(sharding_strategy=sharding_strategy): fsdp_ctor = functools.partial(FSDP, sharding_strategy=sharding_strategy) m = MyModule().cuda() m_local = deepcopy(m) local_m = m_local prev_params = [p.clone() for p in m_local.parameters()] m.lin1 = fsdp_ctor(m.lin1) m = fsdp_ctor(m) _check_equal(m_local, m) opt = torch.optim.SGD(m.parameters(), lr=1e-3) opt_local = torch.optim.SGD(local_m.parameters(), lr=1e-3) for i in range(6): t = torch.ones(4, device="cuda") a, b = m(t) local_a, local_b = local_m(t) if i < 2: # use both params in loss computation. Later, # b will go unused and we check grads are the # same as local training. loss = (a @ b).sum() loss_local = (local_a @ local_b).sum() else: loss = a.sum() loss_local = local_a.sum() loss.backward() loss_local.backward() _check_resharded(m) opt.step() opt_local.step() _check_equal(m_local, m) # Ensure at least some change from previous params, otherwise # above check would be vacuously true. self.assertTrue( any( not torch.equal(p1, p2) for p1, p2 in zip(prev_params, m_local.parameters()) ) ) prev_params = [p.clone() for p in local_m.parameters()] opt.zero_grad() opt_local.zero_grad() dist.barrier()
def _check_equal(local, fsdp): with FSDP.summon_full_params(fsdp): for p1, p2 in zip(fsdp.parameters(), local.parameters()): torch.testing.assert_close(p1, p2) fsdp_ctor = functools.partial(FSDP, sharding_strategy=sharding_strategy) m = MyModule().cuda() m_local = deepcopy(m) local_m = m_local prev_params = [p.clone() for p in m_local.parameters()] m.lin1 = fsdp_ctor(m.lin1) m = fsdp_ctor(m) _check_equal(m_local, m) opt = torch.optim.SGD(m.parameters(), lr=1e-3) opt_local = torch.optim.SGD(local_m.parameters(), lr=1e-3) for i in range(6): t = torch.ones(4, device="cuda") a, b = m(t) local_a, local_b = local_m(t) if i < 2: # use both params in loss computation. Later, # b will go unused and we check grads are the # same as local training. loss = (a @ b).sum() loss_local = (local_a @ local_b).sum() else: loss = a.sum() loss_local = local_a.sum() loss.backward() loss_local.backward() _check_resharded(m) opt.step() opt_local.step() _check_equal(m_local, m) # Ensure at least some change from previous params, otherwise # above check would be vacuously true. self.assertTrue( any( not torch.equal(p1, p2) for p1, p2 in zip(prev_params, m_local.parameters()) ) ) prev_params = [p.clone() for p in local_m.parameters()] opt.zero_grad() opt_local.zero_grad() dist.barrier()
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
__init__
def __init__(self): super().__init__() self.lin = nn.Linear(100, 100)
def __init__(self) -> None: super().__init__() self.a = nn.Linear(2, 2) self.b = nn.Linear(2, 2)
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
__init__
def __init__(self): super().__init__() self.lin = nn.Linear(100, 100)
def __init__(self) -> None: super().__init__() self.a = nn.Linear(2, 2) self.b = nn.Linear(2, 2)
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
test_homogeneous_attributes
def test_homogeneous_attributes(self): """ Tests that passing heterogeneous values for attributes designated as homogeneous raises an error. """ # Manually construct this list but verify against the global list of # homogeneous attribute names all_attr_name_and_values = [ ("_use_orig_params", False, True), ("limit_all_gathers", False, True), ] self.assertEqual( [ attr_name_and_values[0] for attr_name_and_values in all_attr_name_and_values ], HOMOGENEOUS_ATTR_NAMES, ) self.run_subtests( {"attr_name_and_values": all_attr_name_and_values}, self._test_homogeneous_attributes, )
def test_homogeneous_attributes(self): """ Tests that passing heterogeneous values for attributes designated as homogeneous raises an error. """ # Manually construct this list but verify against the global list of # homogeneous attribute names all_attr_name_and_values = [ ("_use_orig_params", False, True), ("limit_all_gathers", False, True), ("_use_full_prec_in_eval", False, True), ] self.assertEqual( [ attr_name_and_values[0] for attr_name_and_values in all_attr_name_and_values ], HOMOGENEOUS_ATTR_NAMES, ) self.run_subtests( {"attr_name_and_values": all_attr_name_and_values}, self._test_homogeneous_attributes, )
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestFSDPMisc(FSDPTest):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestFSDPMiscMultiThread(FSDPTestMultiThread):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
__init__
def __init__(self, param_dtype, buffer_name="buffer"): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE
def __init__(self, param_dtype, buffer_name="buffer", run_checks=True): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE self.run_checks = run_checks
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
forward
def forward(self, tup): # Param and input should be the mixed precision type inp, cls, fsdp, mp_config, full_precision_param_dtype = tup expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _rebuild_full_param should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
def forward(self, tup): inp, cls, fsdp, mp_config, full_precision_param_dtype = tup if self.run_checks: # Param and input should be the mixed precision type expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _unshard should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
never_wrap_policy
def never_wrap_policy(*args, **kwargs): return False net = BatchNormNet().cuda() if convert_sync_bn: net = nn.SyncBatchNorm.convert_sync_batchnorm(net) # FSDP detects that mixed precision + batchnorm will cause issues # and thus wrap batchnorm in a distinct FSDP unit that does not # use mixed precision. mp_config = MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, ) with self.assertWarnsRegex( expected_warning=UserWarning, expected_regex="batch norm submodules will be wrapped as separate", ): model = FSDP( net, mixed_precision=mp_config, auto_wrap_policy=never_wrap_policy, ) bn = model.bn self.assertTrue(isinstance(bn, FSDP)) # policy should not have wrapped any other submodules self.assertFalse(isinstance(model.fc1, FSDP)) self.assertFalse(isinstance(model.fc2, FSDP)) no_mixed_precision = MixedPrecision() self.assertEqual(no_mixed_precision, bn.mixed_precision) self.assertNotEqual(no_mixed_precision, model.mixed_precision) inp = torch.randn((1, 2), device="cuda") # Without FSDP BN mixed precision fix, this would result in # RuntimeError: Expected counts to have type Half but got Float # for syncBN model(inp).sum().backward()
def never_wrap_policy(*args, **kwargs): return False net = BatchNormNet().cuda() if convert_sync_bn: net = nn.SyncBatchNorm.convert_sync_batchnorm(net) # FSDP detects that mixed precision + batchnorm will cause issues # and thus wrap batchnorm in a distinct FSDP unit that does not # use mixed precision. mp_config = MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, _module_classes_to_ignore=[_BatchNorm, nn.LayerNorm], ) with self.assertWarnsRegex( expected_warning=UserWarning, expected_regex="These modules will be wrapped as separate FSDP", ): model = FSDP( net, mixed_precision=mp_config, auto_wrap_policy=never_wrap_policy, ) no_mp = MixedPrecision() for mod in [model.ln, model.bn]: self.assertTrue(isinstance(mod, FSDP)) self.assertEqual(no_mp, mod.mixed_precision) # policy should not have wrapped any other submodules for mod in [model.fc1, model.fc2, model.fc3]: self.assertFalse(isinstance(mod, FSDP)) # Overall mixed precision is still enabled self.assertEqual(mp_config, model.mixed_precision) inp = torch.randn((1, 2), device="cuda") # Without FSDP BN mixed precision fix, this would result in # RuntimeError: Expected counts to have type Half but got Float # for syncBN model(inp).sum().backward()
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
forward
def forward(self, tup): # Param and input should be the mixed precision type inp, cls, fsdp, mp_config, full_precision_param_dtype = tup expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _rebuild_full_param should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
def forward(self, tup): inp, cls, fsdp, mp_config, full_precision_param_dtype = tup if self.run_checks: # Param and input should be the mixed precision type expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _unshard should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
test_unsafe_setattr
def test_unsafe_setattr(self): """ Tests that the environment variable for using unsafe setattr gates as expected. """ self.run_subtests( {"use_orig_params": [False, True]}, self._test_unsafe_setattr, )
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestFSDPMiscWorldSize1(FSDPTestMultiThread):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_misc.py
_test_unsafe_setattr
instantiate_parametrized_tests(TestFSDPMisc) if __name__ == "__main__": run_tests()
def _test_unsafe_setattr(self, use_orig_params: bool): called_setattr_override = False class SetattrLinear(nn.Module): def __init__(self, in_dim: int, out_dim: int, device: torch.device) -> None: super().__init__() self.weight = nn.Parameter( torch.randn((in_dim, out_dim), device=device) ) def forward(self, x: torch.Tensor) -> torch.Tensor: return x @ self.weight def __setattr__(self, name: str, value: Any) -> None: nonlocal called_setattr_override called_setattr_override = True return super().__setattr__(name, value) # Construct FSDP module without changing any environment variables and # run forward, which triggers both unsharded and sharded view setting module = SetattrLinear(5, 5, torch.device("cuda")) fsdp_module = FSDP(module, use_orig_params=use_orig_params) inp = torch.randn((8, 5), device=torch.device("cuda")) called_setattr_override = False fsdp_module(inp) self.assertTrue(called_setattr_override) # Repeat with unsafe setattr explicitly enabled os.environ[_FSDP_USE_UNSAFE_SETATTR] = "1" module = SetattrLinear(5, 5, torch.device("cuda")) fsdp_module = FSDP(module, use_orig_params=use_orig_params) called_setattr_override = False fsdp_module(inp) self.assertFalse(called_setattr_override) # Repeat with unsafe setattr explicitly disabled os.environ[_FSDP_USE_UNSAFE_SETATTR] = "0" module = SetattrLinear(5, 5, torch.device("cuda")) fsdp_module = FSDP(module, use_orig_params=use_orig_params) called_setattr_override = False fsdp_module(inp) self.assertTrue(called_setattr_override)
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestFSDPMiscWorldSize1(FSDPTestMultiThread):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
__init__
def __init__(self, param_dtype, buffer_name="buffer"): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE
def __init__(self, param_dtype, buffer_name="buffer", run_checks=True): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE self.run_checks = run_checks
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
forward
def forward(self, tup): # Param and input should be the mixed precision type inp, cls, fsdp, mp_config, full_precision_param_dtype = tup expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _rebuild_full_param should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
def forward(self, tup): inp, cls, fsdp, mp_config, full_precision_param_dtype = tup if self.run_checks: # Param and input should be the mixed precision type expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _unshard should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
_get_simple_nested_model
def _get_simple_nested_model(self, param_dtype, *fsdp_args, **fsdp_kwargs): model = FSDP( nn.Sequential( FSDP( LinearMixedPrecision(param_dtype, buffer_name="buffer0").cuda(), *fsdp_args, **fsdp_kwargs, ), LinearMixedPrecision(param_dtype, buffer_name="buffer1").cuda(), ), *fsdp_args, **fsdp_kwargs, ) return model
def _get_simple_nested_model( self, param_dtype, run_checks, *fsdp_args, **fsdp_kwargs ): model = FSDP( nn.Sequential( FSDP( LinearMixedPrecision( param_dtype, buffer_name="buffer0", run_checks=run_checks ).cuda(), *fsdp_args, **fsdp_kwargs, ), LinearMixedPrecision( param_dtype, buffer_name="buffer1", run_checks=run_checks ).cuda(), ), *fsdp_args, **fsdp_kwargs, ) return model
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class TestFSDPMixedPrecision(FSDPTest):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class TestFSDPMixedPrecision(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
__init__
def __init__(self): super().__init__() self.lin = nn.Linear(100, 100)
def __init__(self) -> None: super().__init__() self.a = nn.Linear(2, 2) self.b = nn.Linear(2, 2)
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
forward
def forward(self, x): return x
def forward(self, x, y): return self.b(self.a(x + y))
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
forward
def forward(self, x): return x
def forward(self, x, y): return self.b(self.a(x + y))
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
forward
def forward(self, x): return x
def forward(self, x, y): return self.b(self.a(x + y))
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModule(nn.Module):
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class MyModel(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_misc.py
_check_resharded
def _check_resharded(fsdp_module): for handle in fsdp_module._handles: param = handle.flat_param if handle.uses_sharded_strategy: full_param = param._full_param_padded self.assertEqual(full_param.storage().size(), 0) self.assertEqual(param.data_ptr(), param._local_shard.data_ptr())
def _check_resharded(fsdp_module): handle = fsdp_module._handle if not handle: return param = handle.flat_param if handle.uses_sharded_strategy: full_param = param._full_param_padded self.assertEqual(full_param.storage().size(), 0) self.assertEqual(param.data_ptr(), param._local_shard.data_ptr())
import functools import sys import warnings from collections import namedtuple from contextlib import suppress from copy import deepcopy from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
import functools import os import sys import warnings from collections import namedtuple from contextlib import nullcontext from copy import deepcopy from itertools import chain from typing import Any, Tuple import torch import torch.distributed as dist import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch.distributed.fsdp import ( CPUOffload, FlatParameter, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.fsdp._flat_param import _FSDP_USE_UNSAFE_SETATTR from torch.distributed.fsdp._runtime_utils import HOMOGENEOUS_ATTR_NAMES from torch.distributed.fsdp.wrap import ( always_wrap_policy, ModuleWrapPolicy, transformer_auto_wrap_policy, ) from torch.distributed.optim import _apply_optimizer_in_backward from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, CUDAInitMode, FSDPInitMode, FSDPTest, FSDPTestMultiThread, MLP, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
verify_eval_buffer_dtype
def verify_eval_buffer_dtype(module, input): expected_dtype = ( _BUFFER_ORIG_DTYPE if use_full_prec_in_eval else torch.float16 ) for buf in module.buffers(): self.assertEqual(expected_dtype, buf.dtype)
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
_get_underlying_module
def _get_underlying_module(m): return m.module if isinstance(m, FSDP) else m hook_handles = [] hook_handles.append( _get_underlying_module(fsdp_model[0]).register_forward_pre_hook( verify_eval_buffer_dtype ) ) hook_handles.append( _get_underlying_module(fsdp_model[1]).register_forward_pre_hook( verify_eval_buffer_dtype ) ) fsdp_model.eval() fsdp_model((inp, self, fsdp_model, mp_config, torch.float32)) for hook_handle in hook_handles: hook_handle.remove() expected_dtype = ( _BUFFER_ORIG_DTYPE if use_full_prec_in_eval else torch.float16 ) for buf in fsdp_model.buffers(): self.assertEqual(expected_dtype, buf.dtype) # model.train() + forward again should make buffers in fp16 fsdp_model.train() fsdp_model((inp, self, fsdp_model, mp_config, torch.float32)) for buf in fsdp_model.buffers(): self.assertEqual(torch.float16, buf.dtype)
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
__init__
def __init__(self, param_dtype, buffer_name="buffer"): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE
def __init__(self, param_dtype, buffer_name="buffer", run_checks=True): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE self.run_checks = run_checks
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
forward
def forward(self, tup): # Param and input should be the mixed precision type inp, cls, fsdp, mp_config, full_precision_param_dtype = tup expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _rebuild_full_param should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
def forward(self, tup): inp, cls, fsdp, mp_config, full_precision_param_dtype = tup if self.run_checks: # Param and input should be the mixed precision type expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _unshard should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
__init__
def __init__(self, param_dtype, buffer_name="buffer"): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE
def __init__(self, param_dtype, buffer_name="buffer", run_checks=True): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE self.run_checks = run_checks
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
__init__
def __init__(self, param_dtype, buffer_name="buffer"): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE
def __init__(self, param_dtype, buffer_name="buffer", run_checks=True): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE self.run_checks = run_checks
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
forward
def forward(self, tup): # Param and input should be the mixed precision type inp, cls, fsdp, mp_config, full_precision_param_dtype = tup expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _rebuild_full_param should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
def forward(self, tup): inp, cls, fsdp, mp_config, full_precision_param_dtype = tup if self.run_checks: # Param and input should be the mixed precision type expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _unshard should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
forward
def forward(self, tup): # Param and input should be the mixed precision type inp, cls, fsdp, mp_config, full_precision_param_dtype = tup expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _rebuild_full_param should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
def forward(self, tup): inp, cls, fsdp, mp_config, full_precision_param_dtype = tup if self.run_checks: # Param and input should be the mixed precision type expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _unshard should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
test_train_ema_eval_flow
def test_train_ema_eval_flow(self): """ Tests a train -> EMA update -> eval flow with mixed precision enabled. """ self.run_subtests( { "sharding_strategy": [ # We mainly want to test `SHARD_GRAD_OP` since it surfaced # the original bug of not using the right EMA parameters # for eval, but we also test the others for completeness ShardingStrategy.SHARD_GRAD_OP, ShardingStrategy.FULL_SHARD, ShardingStrategy.NO_SHARD, ] }, self._test_train_ema_eval_flow, )
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class TestFSDPTrainEval(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
_test_train_ema_eval_flow
def _test_train_ema_eval_flow(self, sharding_strategy: ShardingStrategy): class TransformerWithEMA(nn.Module): def __init__(self, device: torch.device): super().__init__() self.module = nn.Transformer(device=device) self.ema_module = AveragedModel( nn.Transformer(device=device), multi_avg_fn=torch.optim.swa_utils.get_ema_multi_avg_fn(), use_buffers=True, ) def forward(self, *args, **kwargs): # Use main copy for training and EMA copy for eval if self.training: return self.module(*args, **kwargs) return self.ema_module(*args, **kwargs) device = torch.device("cuda") model = TransformerWithEMA(device=device) policy = ModuleWrapPolicy( {nn.Transformer, nn.TransformerEncoderLayer, nn.TransformerDecoderLayer} ) mixed_precision = MixedPrecision(param_dtype=torch.float16) fsdp_model = FSDP( model, auto_wrap_policy=policy, mixed_precision=mixed_precision, sharding_strategy=sharding_strategy, ) optim = torch.optim.Adam(fsdp_model.module.parameters(), lr=1e-2) if self.rank == 0: print(fsdp_model) torch.manual_seed(1 + self.rank) eval_src = torch.randn((8, 1, 512), device=device) eval_tgt = torch.randn((16, 1, 512), device=device) eval_out_sums: List[torch.Tensor] = [] # An iteration consists of training forward/backward/optimizer, # updating the EMA copy with the main copy, and eval forward for _ in range(3): fsdp_model.train() train_src = torch.randn((8, 4, 512), device=device) train_tgt = torch.randn((16, 4, 512), device=device) train_out = fsdp_model(train_src, train_tgt) train_out.sum().backward() optim.step() optim.zero_grad() with FSDP.summon_full_params(fsdp_model): fsdp_model.ema_module.update_parameters(fsdp_model.module) fsdp_model.eval() with torch.no_grad(): eval_out = fsdp_model(eval_src, eval_tgt) eval_out_sums.append(eval_out.sum()) # Check that the eval outputs differ from iteration to iteration as a # proxy for eval using the correct EMA parameters for i in range(len(eval_out_sums) - 1): self.assertNotEqual(eval_out_sums[i], eval_out_sums[i + 1]) self.assertNotEqual(eval_out_sums[0], eval_out_sums[-1])
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class TestFSDPTrainEval(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
__init__
def __init__(self, param_dtype, buffer_name="buffer"): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE
def __init__(self, param_dtype, buffer_name="buffer", run_checks=True): super().__init__() self.lin = nn.Linear(10, 10, bias=False).to(param_dtype) # Use a configurable buffer name to avoid all submodules sharing the # same buffer name, which may hide prefixed vs. unprefixed name bugs self.buffer_name = buffer_name self.register_buffer(buffer_name, torch.randn((1, 2), dtype=_BUFFER_ORIG_DTYPE)) self._orig_param_type = param_dtype self._orig_buffer_dtype = _BUFFER_ORIG_DTYPE self.run_checks = run_checks
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_mixed_precision.py
forward
def forward(self, tup): # Param and input should be the mixed precision type inp, cls, fsdp, mp_config, full_precision_param_dtype = tup expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _rebuild_full_param should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
def forward(self, tup): inp, cls, fsdp, mp_config, full_precision_param_dtype = tup if self.run_checks: # Param and input should be the mixed precision type expected_param_type = ( mp_config.param_dtype if mp_config.param_dtype is not None else self._orig_param_type ) expected_buffer_type = ( mp_config.buffer_dtype if mp_config.buffer_dtype is not None else self._orig_buffer_dtype ) cls.assertEqual(inp.dtype, expected_param_type) # Buffer should be in specified precision as well. cls.assertEqual(getattr(self, self.buffer_name).dtype, expected_buffer_type) # In FSDP, self.params should point to the right type. num_active_fsdp = 0 for fsdp_module in FSDP.fsdp_modules(fsdp): fsdp_managed_params = fsdp_module.params # Single param assumption cls.assertEqual(1, len(fsdp_managed_params)) for param in fsdp_managed_params: # FSDP unit is currently active if it is not using the param # local shard. This supports both FULL_SHARD and SHARD_GRAD_OP # cases. In FULL_SHARD, we have the additional property that # param._full_param_padded has not been freed. param_is_sharded = ( fsdp_module.sharding_strategy != ShardingStrategy.NO_SHARD and fsdp_module.world_size > 1 ) is_fsdp_unit_active = ( param_is_sharded and param.data.data_ptr() != param._local_shard.data_ptr() ) if is_fsdp_unit_active: num_active_fsdp += 1 # This FSDP unit is active, verify param points to mixed cls.assertEqual(param.dtype, expected_param_type) # _unshard should have also freed the fp16 shard. # Shard is never allocated if param_dtype mixed precision is not # enabled. if mp_config.param_dtype is not None: cls.assertEqual(0, param._mp_shard.untyped_storage().size()) else: cls.assertFalse(hasattr(param, "_mp_shard")) elif param_is_sharded: # This FSDP unit is not active as full param has been # freed or not yet allocated. Ensure param points to full # precision param. cls.assertEqual(param.dtype, full_precision_param_dtype) # We should have gotten at least one active FSDP unit for sharded # (world size > 1) cases. For cases where param is not sharded # (ie world_size == 1) it is a bit hard to check if FSDP unit is active # as we'd always point to the local shard, so we rely on the forward # pass self.lin(inp) working well and inp being reduced precision to # implicitly validate that the param is indeed in the reduced precision. if cls.world_size > 1: cls.assertGreater(num_active_fsdp, 0) return (self.lin(inp), cls, fsdp, mp_config, full_precision_param_dtype)
import contextlib import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, sandcastle_skip_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = sandcastle_skip_if(not HAS_TORCHVISION, "no torchvision") default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
import contextlib import itertools import os import sys from functools import partial from itertools import product from typing import Any, Dict, List import torch import torch.cuda.nccl as nccl import torch.nn as nn import torch.nn.functional as F from torch import distributed as dist from torch.distributed._composable import fully_shard from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler from torch.distributed.fsdp.wrap import ModuleWrapPolicy, size_based_auto_wrap_policy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.optim.swa_utils import AveragedModel from torch.testing._internal.common_distributed import ( SaveForwardInputsModel, skip_if_lt_x_gpu, ) from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, subtest_name, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, ) import torchvision skipIfNoTorchVision = skip_but_pass_in_sandcastle_if( not HAS_TORCHVISION, "no torchvision" ) default_mp = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16, reduce_dtype=torch.float16, ) mp_only_reduce = MixedPrecision(reduce_dtype=torch.float16) mp_only_param_and_buf = MixedPrecision( param_dtype=torch.float16, buffer_dtype=torch.float16 ) mp_no_mixed_precision = MixedPrecision() nccl_supports_bf16 = dist.is_nccl_available() and nccl.version() >= (2, 10) mp_configs = [default_mp, mp_only_reduce, mp_only_param_and_buf, mp_no_mixed_precision] _BUFFER_ORIG_DTYPE = torch.float64 params = "mp_config,cpu_offload,full_precision_param_dtype,enable_sharded_grad_scaler" cpu_offload_config = [CPUOffload(offload_params=True), CPUOffload(offload_params=False)] full_precision_param_dtype_config = [torch.float32, torch.float64] enable_sharded_grad_scaler = ["enable_sharded_grad_scaler", None] configs = list( product( mp_configs, cpu_offload_config, full_precision_param_dtype_config, enable_sharded_grad_scaler, ) ) test_name_mapping = { str(CPUOffload(offload_params=True)): "offload_true", str(CPUOffload(offload_params=False)): "offload_false", str(default_mp): "mp_fp16", str(mp_only_reduce): "mp_only_reduce", str(mp_only_param_and_buf): "mp_only_param_and_buf", str(mp_no_mixed_precision): "mp_no_mp", str(torch.float32): "fp32", str(torch.float64): "fp64", "enable_sharded_grad_scaler": "enable_sharded_grad_scaler", } subtest_name = partial(subtest_name, test_name_mapping) _CURRENT_FULL_PRECISION_PARAM_DTYPE = None class LinearMixedPrecision(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_multiple_wrapping.py
__init__
def __init__(self): super().__init__() self.layers = Sequential(FSDP(Linear(5, 5)))
def __init__(self) -> None: super().__init__() self.layers = Sequential(FSDP(Linear(5, 5)))
import sys import torch from torch import distributed as dist from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.nn import Linear, Module, Sequential from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN class InnerModel(Module):
import sys import torch from torch import distributed as dist from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.nn import Linear, Module, Sequential from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN class InnerModel(Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_optim_state.py
test_optim_input_warning
def test_optim_input_warning(self): """Tests that passing the ``optim_input`` argument into optimizer state checkpointing APIs issues a warning.""" def should_check_method(method_name: str): # Check every method since they all accept `optim_input` return method_name not in ( "sharded_optim_state_dict", "flatten_sharded_optim_state_dict", ) def get_warning_context(): warning_regex = "`optim_input` argument is deprecated" return self.assertWarnsRegex( expected_warning=UserWarning, expected_regex=warning_regex ) self._run_on_all_optim_state_apis( should_check_method, get_warning_context, fsdp_kwargs=None )
def test_optim_input_warning(self): """Tests that passing the ``optim_input`` argument into optimizer state checkpointing APIs issues a warning.""" def should_check_method(method_name: str): # Check every method since they all accept `optim_input` return method_name not in ( "sharded_optim_state_dict", "flatten_sharded_optim_state_dict", ) def get_warning_context(): warning_regex = "`optim_input` argument is deprecated" return self.assertWarnsRegex( expected_warning=FutureWarning, expected_regex=warning_regex ) self._run_on_all_optim_state_apis( should_check_method, get_warning_context, fsdp_kwargs=None )
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT] class TestFSDPOptimState(FSDPTest):
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT] class TestFSDPOptimState(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_optim_state.py
get_warning_context
def get_warning_context(): warning_regex = "`optim_input` argument is deprecated" return self.assertWarnsRegex( expected_warning=UserWarning, expected_regex=warning_regex ) self._run_on_all_optim_state_apis( should_check_method, get_warning_context, fsdp_kwargs=None )
def get_warning_context(): warning_regex = "`optim_input` argument is deprecated" return self.assertWarnsRegex( expected_warning=FutureWarning, expected_regex=warning_regex ) self._run_on_all_optim_state_apis( should_check_method, get_warning_context, fsdp_kwargs=None )
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT]
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT]
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_optim_state.py
test_with_empty_optimizer_state
def test_with_empty_optimizer_state(self): class TestDummyModel(torch.nn.Module): def __init__(self): super().__init__() torch.manual_seed(0) self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU()) self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU()) self.net3 = nn.Linear(32, 64) self.net4 = nn.Sequential(nn.ReLU(), nn.Linear(64, 8)) def forward(self, x): return self.net4(self.net3(self.net2(self.net1(x)))) model = FSDP(TestDummyModel().cuda()) optim = torch.optim.Adam(model.parameters(), lr=1e-2) state_dict = optim.state_dict() gathered_state_dict = FSDP.optim_state_dict(model, optim) self.assertEqual(gathered_state_dict["state"], state_dict["state"])
def test_with_empty_optimizer_state(self): model = FSDP(TestDummyModel().cuda()) optim = torch.optim.Adam(model.parameters(), lr=1e-2) state_dict = optim.state_dict() gathered_state_dict = FSDP.optim_state_dict(model, optim) self.assertEqual(gathered_state_dict["state"], state_dict["state"])
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT] class TestFSDPOptimState(FSDPTest):
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT] class TestFSDPOptimState(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_optim_state.py
test_with_empty_optimizer_state
def test_with_empty_optimizer_state(self): class TestDummyModel(torch.nn.Module): def __init__(self): super().__init__() torch.manual_seed(0) self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU()) self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU()) self.net3 = nn.Linear(32, 64) self.net4 = nn.Sequential(nn.ReLU(), nn.Linear(64, 8)) def forward(self, x): return self.net4(self.net3(self.net2(self.net1(x)))) model = FSDP(TestDummyModel().cuda()) optim = torch.optim.Adam(model.parameters(), lr=1e-2) state_dict = optim.state_dict() gathered_state_dict = FSDP.optim_state_dict(model, optim) self.assertEqual(gathered_state_dict["state"], state_dict["state"])
def test_with_empty_optimizer_state(self): model = FSDP(TestDummyModel().cuda()) optim = torch.optim.Adam(model.parameters(), lr=1e-2) state_dict = optim.state_dict() gathered_state_dict = FSDP.optim_state_dict(model, optim) self.assertEqual(gathered_state_dict["state"], state_dict["state"])
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT] class TestFSDPOptimState(FSDPTest):
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT] class TestFSDPOptimState(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_optim_state.py
step
def step(): loss = model(model.get_input()) loss.backward(loss) optim.step() step() original_osd = deepcopy(optim.state_dict()) osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) self._check_same_state( FSDP.optim_state_dict(model, optim), osd, check_same_param_keys=True ) step() osd_to_load = FSDP.optim_state_dict_to_load( model, optim, osd, load_directly=True ) self._check_same_state( optim.state_dict(), original_osd, check_same_param_keys=True ) # Test the default setting. osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) for state in osd["state"].values(): for s in state.values(): self.assertFalse(isinstance(s, ShardedTensor)) self.assertFalse(s.is_cuda) # Test sharded state_dict without offload_to_cpu with FSDP.state_dict_type( model, StateDictType.SHARDED_STATE_DICT, ShardedStateDictConfig(), ShardedOptimStateDictConfig(offload_to_cpu=False), ): osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) for state in osd["state"].values(): for s in state.values(): if s.dim() == 0: continue self.assertTrue(isinstance(s, ShardedTensor)) if s._local_shards[0]: self.assertTrue(s._local_shards[0].tensor.is_cuda) # Test full state_dict with rank0_only with FSDP.state_dict_type( model, StateDictType.FULL_STATE_DICT, FullStateDictConfig(), FullOptimStateDictConfig( offload_to_cpu=True, rank0_only=True, ), ): osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) if dist.get_rank() > 0: self.assertEqual(osd, {}) else: for state in osd["state"].values(): for s in state.values(): if s.dim() == 0: continue self.assertFalse(s.is_cuda) self.assertFalse(isinstance(s, ShardedTensor))
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT]
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_optim_state.py
_run_test
def _run_test(use_orig_params, optimizer_has_tensor_state): model = FSDP(TestDummyModel().cuda(), use_orig_params=use_orig_params) optimizer_cls = ( torch.optim.Adam if optimizer_has_tensor_state else torch.optim.SGD ) optim = optimizer_cls(model.parameters(), lr=1e-2) def step(): loss = model(model.get_input()) loss.backward(loss) optim.step() step() original_osd = deepcopy(optim.state_dict()) for state in original_osd["state"].values(): # Add customized value state["value1"] = 2.74 state["value2"] = None osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) osd_to_load = FSDP.optim_state_dict_to_load(model, optim, osd) for state in osd_to_load["state"].values(): self.assertEqual(state["value1"], 2.74) self.assertEqual(state["value2"], None) self.run_subtests( { "use_orig_params": [False, True], "optimizer_has_tensor_state": [False, True], }, _run_test, )
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT]
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_optim_state.py
step
def step(): loss = model(model.get_input()) loss.backward(loss) optim.step() step() original_osd = deepcopy(optim.state_dict()) osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) self._check_same_state( FSDP.optim_state_dict(model, optim), osd, check_same_param_keys=True ) step() osd_to_load = FSDP.optim_state_dict_to_load( model, optim, osd, load_directly=True ) self._check_same_state( optim.state_dict(), original_osd, check_same_param_keys=True ) # Test the default setting. osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) for state in osd["state"].values(): for s in state.values(): self.assertFalse(isinstance(s, ShardedTensor)) self.assertFalse(s.is_cuda) # Test sharded state_dict without offload_to_cpu with FSDP.state_dict_type( model, StateDictType.SHARDED_STATE_DICT, ShardedStateDictConfig(), ShardedOptimStateDictConfig(offload_to_cpu=False), ): osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) for state in osd["state"].values(): for s in state.values(): if s.dim() == 0: continue self.assertTrue(isinstance(s, ShardedTensor)) if s._local_shards[0]: self.assertTrue(s._local_shards[0].tensor.is_cuda) # Test full state_dict with rank0_only with FSDP.state_dict_type( model, StateDictType.FULL_STATE_DICT, FullStateDictConfig(), FullOptimStateDictConfig( offload_to_cpu=True, rank0_only=True, ), ): osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) if dist.get_rank() > 0: self.assertEqual(osd, {}) else: for state in osd["state"].values(): for s in state.values(): if s.dim() == 0: continue self.assertFalse(s.is_cuda) self.assertFalse(isinstance(s, ShardedTensor))
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT]
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_optim_state.py
step
def step(): loss = model(model.get_input()) loss.backward(loss) optim.step() step() original_osd = deepcopy(optim.state_dict()) osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) self._check_same_state( FSDP.optim_state_dict(model, optim), osd, check_same_param_keys=True ) step() osd_to_load = FSDP.optim_state_dict_to_load( model, optim, osd, load_directly=True ) self._check_same_state( optim.state_dict(), original_osd, check_same_param_keys=True ) # Test the default setting. osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) for state in osd["state"].values(): for s in state.values(): self.assertFalse(isinstance(s, ShardedTensor)) self.assertFalse(s.is_cuda) # Test sharded state_dict without offload_to_cpu with FSDP.state_dict_type( model, StateDictType.SHARDED_STATE_DICT, ShardedStateDictConfig(), ShardedOptimStateDictConfig(offload_to_cpu=False), ): osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) for state in osd["state"].values(): for s in state.values(): if s.dim() == 0: continue self.assertTrue(isinstance(s, ShardedTensor)) if s._local_shards[0]: self.assertTrue(s._local_shards[0].tensor.is_cuda) # Test full state_dict with rank0_only with FSDP.state_dict_type( model, StateDictType.FULL_STATE_DICT, FullStateDictConfig(), FullOptimStateDictConfig( offload_to_cpu=True, rank0_only=True, ), ): osd = FSDP.optim_state_dict(model, optim, optim_state_dict=original_osd) if dist.get_rank() > 0: self.assertEqual(osd, {}) else: for state in osd["state"].values(): for s in state.values(): if s.dim() == 0: continue self.assertFalse(s.is_cuda) self.assertFalse(isinstance(s, ShardedTensor))
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT]
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_optim_state.py
test_no_grad
instantiate_parametrized_tests(TestFSDPOptimState) if __name__ == "__main__": run_tests()
def test_no_grad(self): model = TestDummyModel(no_grad=True).cuda() fsdp_model = FSDP(deepcopy(model), use_orig_params=True) fsdp_optim = torch.optim.Adam(fsdp_model.parameters(), lr=1e-2) for i in range(5): if i % 2 == 1: fsdp_model.net1[0].weight.requires_grad = True fsdp_model.net1[0].bias.requires_grad = True else: fsdp_model.net1[0].weight.requires_grad = False fsdp_model.net1[0].bias.requires_grad = False batch = fsdp_model.get_input() loss = fsdp_model(batch).sum() loss.backward() fsdp_optim.step() orig_state_dict = deepcopy(fsdp_optim.state_dict()) optim_state_dict = FSDP.optim_state_dict(fsdp_model, fsdp_optim) FSDP.optim_state_dict_to_load( fsdp_model, fsdp_optim, FSDP.optim_state_dict(fsdp_model, fsdp_optim), load_directly=True, ) self._check_same_state( fsdp_optim.state_dict(), orig_state_dict, check_same_param_keys=True, )
import bisect import sys from copy import deepcopy from enum import auto, Enum from typing import Any, Callable, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._state_dict_utils import _gather_state_dict from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( _CHECKPOINT_WRAPPED_MODULE, apply_activation_checkpointing, ) from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ShardingStrategy from torch.distributed.fsdp.fully_sharded_data_parallel import ( FullOptimStateDictConfig, FullStateDictConfig, OptimStateKeyType, ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictSettings, StateDictType, ) from torch.distributed.optim import _NamedOptimizer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) STATE_DICT_TYPES = [StateDictType.FULL_STATE_DICT, StateDictType.SHARDED_STATE_DICT] class TestFSDPOptimState(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_overlap.py
_create_model
def _create_model(compute_cycles, has_params: bool): model = FSDP( nn.Sequential( FSDP(Layer(compute_cycles, has_params)), FSDP(Layer(compute_cycles, has_params)), FSDP(Layer(compute_cycles, has_params)), FSDP(Layer(compute_cycles, has_params)), ) ).cuda() return model class Min10: def __init__(self): self.data = [] def add(self, new_data): if len(self.data) < 10: self.data.append(new_data) else: self.data = sorted(self.data) if new_data < self.data[-1]: self.data[-1] = new_data def avg(self): return mean(self.data) class TestForwardOverlapWorldSizeOne(FSDPTest): @property def world_size(self): return 1 def _dist_train(self): rank = self.rank world_size = self.world_size # Save the original torch.distributed.all_gather_into_tensor function since we will # patch it to include an artificial delay. orig_all_gather = torch.distributed.all_gather_into_tensor def run(compute_cycles, all_gather_cycles): has_params = all_gather_cycles > 0 model = _create_model(compute_cycles, has_params) # Get the input and sets the input's requires_grad to True because # we have a fake compute in the forward pass. batch = torch.rand(1).cuda() batch.requires_grad = True # Run one dummy iteration to trigger the execution order validation # all-gathers out = model(batch) out.backward() model.zero_grad(set_to_none=True) # We run 20 iterations but only collect timing data from the minimal 10 # data points because nondeterministic system events can disturb the timing. cpu_iter = Min10() cpu_wait = Min10() gpu_compute = Min10() gpu_total = Min10() for _ in range(20): # Get two events for measuring the overall time. e1 = Event(enable_timing=True) e2 = Event(enable_timing=True) cpu_start = time.process_time() all_gather_called = False def _delayed_all_gather(*args, **kwargs): nonlocal all_gather_called all_gather_called = True torch.cuda._sleep(all_gather_cycles) assert orig_all_gather return orig_all_gather(*args, **kwargs) # forward pass # # Even though both e1 & e2 are on the compute stream, since # compute depends on all_gather, e2-e1 includes all_gather time. e1.record() with patch( "torch.distributed.all_gather_into_tensor", _delayed_all_gather ): out = model(batch) if has_params and world_size > 1: self.assertTrue(all_gather_called) else: self.assertFalse(all_gather_called) e2.record() # backward pass out.backward() model.zero_grad(set_to_none=True) cpu_iter_time = time.process_time() - cpu_start # wait for gpu out.item() cpu_wait_for_gpu_time = time.process_time() - cpu_start - cpu_iter_time # get sum of the compute time times = [] for mod in model.modules(): if not isinstance(mod, Layer): continue times.append(mod.get_time()) # get gpu compute + all_gather time overall_gpu_time = e1.elapsed_time(e2) cpu_iter.add(cpu_iter_time) cpu_wait.add(cpu_wait_for_gpu_time) gpu_compute.add(sum(times)) gpu_total.add(overall_gpu_time) del model return { "cpu_iter": cpu_iter.avg(), "cpu_wait": cpu_wait.avg(), "gpu_compute": gpu_compute.avg(), "gpu_total": gpu_total.avg(), } sleep_cycles = int(100 * get_cycles_per_ms()) e1 = run(0, 0) # no compute, no all-gather e2 = run(0, sleep_cycles) # no compute, only all-gather e3 = run(sleep_cycles, 0) # only compute, no all-gather e4 = run(sleep_cycles, sleep_cycles) # both compute and all-gather debug_string = f"\nrank{rank}:\n e1: {e1}\n e2: {e2}\n e3: {e3}\n e4: {e4}" print(debug_string) # Check the cpu/gpu timing. CPU should run ahead of GPU. Therefore, cpu-gpu # wait should be long, except when there is no real work on GPU. # # If the assertions fail below, we likely have a cpu-gpu wait in the forward/backward pass. # e4["cpu_iter"] may not be short as cpu may take some time to queue both compute and all-gather. short = [ e1["cpu_iter"], e2["cpu_iter"], e3["cpu_iter"], e1["cpu_wait"], ] long = [e3["cpu_wait"], e4["cpu_wait"]] if world_size == 1: short.append(e2["cpu_wait"]) # all gather should not be happening. else: long.append( e2["cpu_wait"] ) # all gather should happen and prolong the cpu-gpu wait. for s in short: for l in long: # 10X longer is a safe margin, since the GPU work timing is around 100X more # of that of the CPU. self.assertTrue(s * 10 < l) # Check the GPU timing. short = [e1["gpu_compute"], e1["gpu_total"], e2["gpu_compute"]] long = [e3["gpu_compute"], e3["gpu_total"], e4["gpu_compute"], e4["gpu_total"]] if world_size == 1: short.append(e2["gpu_total"]) # all gather should not be happening. else: long.append( e2["gpu_total"] ) # all gather should happen and prolong the cpu-gpu wait. for s in short: for l in long: # 10X longer is a safe margin, since the time is around 100X longer # when there is work on GPU vs. no work. self.assertTrue(s * 10 < l) # Check the GPU overlapping when there is all-gather. if world_size > 1: compute_only = e3["gpu_compute"] all_gather_only = e2["gpu_total"] both = e4["gpu_total"] self.assertTrue(compute_only + all_gather_only > 1.1 * both) @skip_if_lt_x_gpu(2) def test_forward_overlap(self): self._dist_train() class TestForwardOverlapWorldSizeTwo(TestForwardOverlapWorldSizeOne): @property def world_size(self): return 2 if __name__ == "__main__": run_tests()
def _create_model(compute_cycles, has_params: bool): # Use `limit_all_gathers=False` since the timing being tested relies on the # CPU running ahead of the GPU model = FSDP( nn.Sequential( FSDP(Layer(compute_cycles, has_params), limit_all_gathers=False), FSDP(Layer(compute_cycles, has_params), limit_all_gathers=False), FSDP(Layer(compute_cycles, has_params), limit_all_gathers=False), FSDP(Layer(compute_cycles, has_params), limit_all_gathers=False), ), limit_all_gathers=False, ).cuda() return model class Min10: def __init__(self) -> None: self.data = [] def add(self, new_data): if len(self.data) < 10: self.data.append(new_data) else: self.data = sorted(self.data) if new_data < self.data[-1]: self.data[-1] = new_data def avg(self): return mean(self.data) class TestForwardOverlapWorldSizeOne(FSDPTest): @property def world_size(self): return 1 def _dist_train(self): rank = self.rank world_size = self.world_size # Save the original torch.distributed.all_gather_into_tensor function since we will # patch it to include an artificial delay. orig_all_gather = torch.distributed.all_gather_into_tensor def run(compute_cycles, all_gather_cycles): has_params = all_gather_cycles > 0 model = _create_model(compute_cycles, has_params) # Get the input and sets the input's requires_grad to True because # we have a fake compute in the forward pass. batch = torch.rand(1).cuda() batch.requires_grad = True # Run one dummy iteration to trigger the execution order validation # all-gathers out = model(batch) out.backward() model.zero_grad(set_to_none=True) # We run 20 iterations but only collect timing data from the minimal 10 # data points because nondeterministic system events can disturb the timing. cpu_iter = Min10() cpu_wait = Min10() gpu_compute = Min10() gpu_total = Min10() for _ in range(20): # Get two events for measuring the overall time. e1 = Event(enable_timing=True) e2 = Event(enable_timing=True) cpu_start = time.process_time() all_gather_called = False def _delayed_all_gather(*args, **kwargs): nonlocal all_gather_called all_gather_called = True torch.cuda._sleep(all_gather_cycles) assert orig_all_gather return orig_all_gather(*args, **kwargs) # forward pass # # Even though both e1 & e2 are on the compute stream, since # compute depends on all_gather, e2-e1 includes all_gather time. e1.record() with patch( "torch.distributed.all_gather_into_tensor", _delayed_all_gather ): out = model(batch) if has_params and world_size > 1: self.assertTrue(all_gather_called) else: self.assertFalse(all_gather_called) e2.record() # backward pass out.backward() model.zero_grad(set_to_none=True) cpu_iter_time = time.process_time() - cpu_start # wait for gpu out.item() cpu_wait_for_gpu_time = time.process_time() - cpu_start - cpu_iter_time # get sum of the compute time times = [] for mod in model.modules(): if not isinstance(mod, Layer): continue times.append(mod.get_time()) # get gpu compute + all_gather time overall_gpu_time = e1.elapsed_time(e2) cpu_iter.add(cpu_iter_time) cpu_wait.add(cpu_wait_for_gpu_time) gpu_compute.add(sum(times)) gpu_total.add(overall_gpu_time) del model return { "cpu_iter": cpu_iter.avg(), "cpu_wait": cpu_wait.avg(), "gpu_compute": gpu_compute.avg(), "gpu_total": gpu_total.avg(), } sleep_cycles = int(100 * get_cycles_per_ms()) e1 = run(0, 0) # no compute, no all-gather e2 = run(0, sleep_cycles) # no compute, only all-gather e3 = run(sleep_cycles, 0) # only compute, no all-gather e4 = run(sleep_cycles, sleep_cycles) # both compute and all-gather debug_string = f"\nrank{rank}:\n e1: {e1}\n e2: {e2}\n e3: {e3}\n e4: {e4}" print(debug_string) # Check the cpu/gpu timing. CPU should run ahead of GPU. Therefore, cpu-gpu # wait should be long, except when there is no real work on GPU. # # If the assertions fail below, we likely have a cpu-gpu wait in the forward/backward pass. # e4["cpu_iter"] may not be short as cpu may take some time to queue both compute and all-gather. short = [ e1["cpu_iter"], e2["cpu_iter"], e3["cpu_iter"], e1["cpu_wait"], ] long = [e3["cpu_wait"], e4["cpu_wait"]] if world_size == 1: short.append(e2["cpu_wait"]) # all gather should not be happening. else: long.append( e2["cpu_wait"] ) # all gather should happen and prolong the cpu-gpu wait. for s in short: for l in long: # 10X longer is a safe margin, since the GPU work timing is around 100X more # of that of the CPU. self.assertTrue(s * 10 < l) # Check the GPU timing. short = [e1["gpu_compute"], e1["gpu_total"], e2["gpu_compute"]] long = [e3["gpu_compute"], e3["gpu_total"], e4["gpu_compute"], e4["gpu_total"]] if world_size == 1: short.append(e2["gpu_total"]) # all gather should not be happening. else: long.append( e2["gpu_total"] ) # all gather should happen and prolong the cpu-gpu wait. for s in short: for l in long: # 10X longer is a safe margin, since the time is around 100X longer # when there is work on GPU vs. no work. self.assertTrue(s * 10 < l) # Check the GPU overlapping when there is all-gather. if world_size > 1: compute_only = e3["gpu_compute"] all_gather_only = e2["gpu_total"] both = e4["gpu_total"] self.assertTrue(compute_only + all_gather_only > 1.1 * both) @skip_if_lt_x_gpu(2) def test_forward_overlap(self): self._dist_train() class TestForwardOverlapWorldSizeTwo(TestForwardOverlapWorldSizeOne): @property def world_size(self): return 2 if __name__ == "__main__": run_tests()
import sys import time from statistics import mean from unittest.mock import patch import torch import torch.nn as nn from torch import distributed as dist from torch.cuda import Event from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( get_cycles_per_ms, run_tests, TEST_WITH_DEV_DBG_ASAN, )
import sys import time from statistics import mean from unittest.mock import patch import torch import torch.nn as nn from torch import distributed as dist from torch.cuda import Event from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( get_cycles_per_ms, run_tests, TEST_WITH_DEV_DBG_ASAN, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_state_dict.py
__init__
def __init__(self, wrap_fsdp, register_buffers=False, ignore_inner=False): super().__init__() self.inner = Linear(*INNER_SHAPE) if register_buffers: self.inner.register_buffer("buffer", torch.randn(BUFFER_SHAPE)) self.inner.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False ) if wrap_fsdp: self.inner = FSDP( self.inner, ignored_modules=([self.inner] if ignore_inner else []) ) self.outer = Linear(*OUTER_SHAPE) if register_buffers: self.outer.register_buffer("buffer", torch.randn(BUFFER_SHAPE)) self.outer.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False )
def __init__( self, wrap_fsdp, register_buffers=False, ignore_inner=False, mixed_precision=False, process_group=None, ): super().__init__() self.inner = Linear(*INNER_SHAPE) if register_buffers: self.inner.buffer = nn.Buffer(torch.randn(BUFFER_SHAPE)) self.inner.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False ) if wrap_fsdp: self.inner = FSDP( self.inner, ignored_modules=([self.inner] if ignore_inner else []), mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, ) if mixed_precision else None, process_group=process_group, ) self.outer = Linear(*OUTER_SHAPE) if register_buffers: self.outer.buffer = nn.Buffer(torch.randn(BUFFER_SHAPE)) self.outer.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False )
import io import itertools import sys from contextlib import suppress from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class Model(Module):
import io import itertools import sys from contextlib import nullcontext from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardedTensor, ) from torch.distributed._state_dict_utils import ( _all_gather_sharded_tensor, _gather_state_dict, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._common_utils import FSDP_PREFIX from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class Model(Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_state_dict.py
world_size
def world_size(self): return 2
def world_size(self): return min(torch.cuda.device_count(), 2)
import io import itertools import sys from contextlib import suppress from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class TestFSDPStateDict(FSDPTest):
import io import itertools import sys from contextlib import nullcontext from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardedTensor, ) from torch.distributed._state_dict_utils import ( _all_gather_sharded_tensor, _gather_state_dict, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._common_utils import FSDP_PREFIX from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class TestFSDPStateDict(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_state_dict.py
__init__
def __init__(self, wrap_fsdp, register_buffers=False, ignore_inner=False): super().__init__() self.inner = Linear(*INNER_SHAPE) if register_buffers: self.inner.register_buffer("buffer", torch.randn(BUFFER_SHAPE)) self.inner.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False ) if wrap_fsdp: self.inner = FSDP( self.inner, ignored_modules=([self.inner] if ignore_inner else []) ) self.outer = Linear(*OUTER_SHAPE) if register_buffers: self.outer.register_buffer("buffer", torch.randn(BUFFER_SHAPE)) self.outer.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False )
def __init__( self, wrap_fsdp, register_buffers=False, ignore_inner=False, mixed_precision=False, process_group=None, ): super().__init__() self.inner = Linear(*INNER_SHAPE) if register_buffers: self.inner.buffer = nn.Buffer(torch.randn(BUFFER_SHAPE)) self.inner.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False ) if wrap_fsdp: self.inner = FSDP( self.inner, ignored_modules=([self.inner] if ignore_inner else []), mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, ) if mixed_precision else None, process_group=process_group, ) self.outer = Linear(*OUTER_SHAPE) if register_buffers: self.outer.buffer = nn.Buffer(torch.randn(BUFFER_SHAPE)) self.outer.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False )
import io import itertools import sys from contextlib import suppress from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class Model(Module):
import io import itertools import sys from contextlib import nullcontext from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardedTensor, ) from torch.distributed._state_dict_utils import ( _all_gather_sharded_tensor, _gather_state_dict, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._common_utils import FSDP_PREFIX from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class Model(Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_state_dict.py
_create_module
def _create_module(wrap_fsdp=True): LINEAR_SKIP = "linear_skip" ctx = enable_wrap(wrapper_cls=FSDP) if wrap_fsdp else suppress() with ctx: module = SkipModel(double_nest=double_nest) # Full name of linear_skip param tensors in SkipModel, as would be # stored in checkpoint. linear_skip_tensor_names = [ k for k in dict(module.named_parameters()).keys() if LINEAR_SKIP in k ] # skip SkipModule linear_skip = getattr(module, LINEAR_SKIP) delattr(module, LINEAR_SKIP) # Wrap FSDP fsdp = wrap(module) # reattach setattr(module, LINEAR_SKIP, linear_skip) return fsdp, linear_skip_tensor_names fsdp, linear_skip_tensor_names = _create_module() # Run a forward pass inp = torch.randn((1, 10), device=torch.cuda.current_device()) loss = fsdp(inp) loss.sum().backward() with FSDP.state_dict_type(fsdp, STATE_DICT_MAPPING[state_dict_type]): state_dict = fsdp.state_dict() if self.rank == 0 and state_dict_type != "local_state_dict": sd_keys = list(state_dict.keys()) expected = list(SkipModel(double_nest=False).state_dict().keys()) self.assertEqual(sorted(sd_keys), sorted(expected)) # TODO: parameters in linear_skip_tensor_names should not be handled # by FSDP.state_dict(). Have a check once this is implemented in # FSDP.state_dict(). # Check that it can be loaded into FSDP. new_fsdp, _ = _create_module() _zero_model(new_fsdp) for (p1, p2) in zip(fsdp.parameters(), new_fsdp.parameters()): self.assertNotEqual(p1, p2) with FSDP.state_dict_type(new_fsdp, STATE_DICT_MAPPING[state_dict_type]): if state_dict_type != "local_state_dict": # FlatParameter has not supported deepcopy yet. state_dict = deepcopy(state_dict) new_fsdp.load_state_dict(state_dict, strict=True) for (p1, p2) in zip(fsdp.parameters(), new_fsdp.parameters()): self.assertEqual(p1, p2) # Test that the checkpoint can be loaded into a local model. local, _ = _create_module(wrap_fsdp=False) for param in local.parameters(): with torch.no_grad(): param.zero_() with fsdp.summon_full_params(fsdp): for (p1, p2) in zip(fsdp.parameters(), local.parameters()): self.assertNotEqual(p1, p2) if state_dict_type == "local_state_dict": return state_dict = _gather_state_dict(state_dict) with fsdp.summon_full_params(fsdp): if self.rank == 0: local.load_state_dict(state_dict, strict=True) for (p1, p2) in zip(fsdp.parameters(), local.parameters()): self.assertEqual(p1, p2)
def _create_module(wrap_fsdp=True): LINEAR_SKIP = "linear_skip" ctx = enable_wrap(wrapper_cls=FSDP) if wrap_fsdp else nullcontext() with ctx: module = SkipModel(double_nest=double_nest) # Full name of linear_skip param tensors in SkipModel, as would be # stored in checkpoint. linear_skip_tensor_names = [ k for k in dict(module.named_parameters()).keys() if LINEAR_SKIP in k ] # skip SkipModule linear_skip = getattr(module, LINEAR_SKIP) delattr(module, LINEAR_SKIP) # Wrap FSDP fsdp = wrap(module) # reattach setattr(module, LINEAR_SKIP, linear_skip) return fsdp, linear_skip_tensor_names fsdp, linear_skip_tensor_names = _create_module() # Run a forward pass inp = torch.randn((1, 10), device=torch.cuda.current_device()) loss = fsdp(inp) loss.sum().backward() with FSDP.state_dict_type(fsdp, STATE_DICT_MAPPING[state_dict_type]): state_dict = fsdp.state_dict() if self.rank == 0 and state_dict_type != "local_state_dict": sd_keys = list(state_dict.keys()) expected = list(SkipModel(double_nest=False).state_dict().keys()) self.assertEqual(sorted(sd_keys), sorted(expected)) # TODO: parameters in linear_skip_tensor_names should not be handled # by FSDP.state_dict(). Have a check once this is implemented in # FSDP.state_dict(). # Check that it can be loaded into FSDP. new_fsdp, _ = _create_module() _zero_model(new_fsdp) for p1, p2 in zip(fsdp.parameters(), new_fsdp.parameters()): self.assertNotEqual(p1, p2) with FSDP.state_dict_type(new_fsdp, STATE_DICT_MAPPING[state_dict_type]): if state_dict_type != "local_state_dict": # FlatParameter has not supported deepcopy yet. state_dict = deepcopy(state_dict) new_fsdp.load_state_dict(state_dict, strict=True) for p1, p2 in zip(fsdp.parameters(), new_fsdp.parameters()): self.assertEqual(p1, p2) # Test that the checkpoint can be loaded into a local model. local, _ = _create_module(wrap_fsdp=False) for param in local.parameters(): with torch.no_grad(): param.zero_() with fsdp.summon_full_params(fsdp): for p1, p2 in zip(fsdp.parameters(), local.parameters()): self.assertNotEqual(p1, p2) if state_dict_type == "local_state_dict": return state_dict = _gather_state_dict(state_dict) with fsdp.summon_full_params(fsdp): if self.rank == 0: local.load_state_dict(state_dict, strict=True) for p1, p2 in zip(fsdp.parameters(), local.parameters()): self.assertEqual(p1, p2)
import io import itertools import sys from contextlib import suppress from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, }
import io import itertools import sys from contextlib import nullcontext from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardedTensor, ) from torch.distributed._state_dict_utils import ( _all_gather_sharded_tensor, _gather_state_dict, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._common_utils import FSDP_PREFIX from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, }
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_use_orig_params.py
test_multi_tensor_apply_size0_tensors_cuda
instantiate_parametrized_tests(TestFSDPUseOrigParamsMultipleParamGroups) instantiate_parametrized_tests(TestFSDPUseOrigParamsUnshardReshard) instantiate_parametrized_tests(TestFSDPUseOrigParamsParamAccess) instantiate_parametrized_tests(TestFSDPUseOrigParamsFQNs) instantiate_parametrized_tests(TestFSDPUseOrigParamsNoSync) if __name__ == "__main__": run_tests()
def test_multi_tensor_apply_size0_tensors_cuda(self): size0_tensors = [ torch.empty(0, device="cuda") for _ in range(NUM_SIZE0_TENSORS) ] # Check that this does not segfault torch._foreach_mul_(size0_tensors, 0.1)
import copy import functools import itertools import os import sys import unittest from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, StateDictType, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import ( _FSDP_SKIP_WRITEBACK_CHECK, _FSDP_USE_FULL_PREC_IN_EVAL, ) from torch.distributed.fsdp._init_utils import NO_RESHARD_AFTER_FORWARD_STRATEGIES from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, TestCase, ) from torch.utils._triton import has_triton NUM_SIZE0_TENSORS = 1000 class TestMultiTensorApply(TestCase):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_hsdp_dtensor_state_dict.py
forward
def forward(self, x): return self.net4(self.net3(self.net2(self.net1(x))))
import io from copy import deepcopy import torch import torch.distributed as dist import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._tensor import DTensor, Replicate, Shard from torch.distributed.device_mesh import init_device_mesh from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ( ShardedOptimStateDictConfig, ShardedStateDictConfig, ShardingStrategy, StateDictType, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( DTensorTestBase, skip_if_lt_x_gpu, with_comms, ) class DenseModel(torch.nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_hsdp_dtensor_state_dict.py
get_input
def get_input(self): return torch.rand(4, 8, device="cuda") # TODO: Consolidate DeviceMesh based FSDP and HSDP test cases.
import io from copy import deepcopy import torch import torch.distributed as dist import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._tensor import DTensor, Replicate, Shard from torch.distributed.device_mesh import init_device_mesh from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ( ShardedOptimStateDictConfig, ShardedStateDictConfig, ShardingStrategy, StateDictType, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( DTensorTestBase, skip_if_lt_x_gpu, with_comms, ) class DenseModel(torch.nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_hsdp_dtensor_state_dict.py
test_root_module_is_not_FSDP
def test_root_module_is_not_FSDP(self): class FakeMPModel(torch.nn.Module): def __init__(self, device_mesh): super().__init__() torch.manual_seed(0) self.dense = FSDP( DenseModel().cuda(), use_orig_params=True, sharding_strategy=ShardingStrategy.HYBRID_SHARD, device_mesh=device_mesh, ) if dist.get_rank() == 0: self.sparse0 = nn.Sequential(nn.Linear(8, 8), nn.ReLU()) else: self.sparse1 = nn.Sequential(nn.Linear(8, 8), nn.ReLU()) def forward(self, x): if dist.get_rank() == 0: sparse = self.sparse0(x) else: sparse = self.sparse1(x) dist.all_reduce(sparse) return self.dense(sparse) mesh_2d = init_device_mesh(self.device_type, (2, self.world_size // 2)) model = FakeMPModel(device_mesh=mesh_2d).cuda() optim = torch.optim.Adam(model.parameters(), lr=1e-2) batch = torch.rand(5, 8, device=torch.device("cuda")) model(batch).sum().backward() optim.step() osd = optim.state_dict() with FSDP.state_dict_type(model, StateDictType.SHARDED_STATE_DICT): osd = FSDP.optim_state_dict(model, optim, osd) for param, state in osd["state"].items(): if "dense" in param: self.assertIsInstance(state["exp_avg"], DTensor) self.assertIsInstance(state["exp_avg_sq"], DTensor) self.assertEqual(state["exp_avg"].placements, (Replicate(), Shard(0))) self.assertEqual( state["exp_avg_sq"].placements, (Replicate(), Shard(0)) ) else: self.assertIsInstance(state["exp_avg"], torch.Tensor) self.assertIsInstance(state["exp_avg_sq"], torch.Tensor)
import io from copy import deepcopy import torch import torch.distributed as dist import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._tensor import DTensor, Replicate, Shard from torch.distributed.device_mesh import init_device_mesh from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ( ShardedOptimStateDictConfig, ShardedStateDictConfig, ShardingStrategy, StateDictType, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( DTensorTestBase, skip_if_lt_x_gpu, with_comms, ) class TestHSDPWithDeviceMeshAndDTensor(DTensorTestBase):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_tp_integration.py
__init__
def __init__(self): super().__init__() self.net1 = torch.nn.Linear(5, 8) self.relu = torch.nn.ReLU() self.net2 = torch.nn.Linear(8, 4) self.net3 = torch.nn.Linear(4, 12)
def __init__(self) -> None: super().__init__() self.net1 = torch.nn.Linear(5, 8) self.relu = torch.nn.ReLU() self.net2 = torch.nn.Linear(8, 4) self.net3 = torch.nn.Linear(4, 12)
import copy import sys from collections import OrderedDict from typing import Any, Dict, List, NamedTuple, Optional, Tuple import torch import torch.distributed._shard.sharding_spec as shard_spec from torch import distributed as dist from torch.distributed._shard import shard_module from torch.distributed._shard.sharded_tensor.api import Shard, ShardedTensor from torch.distributed._shard.sharding_plan import ShardingPlan from torch.distributed._shard.sharding_spec import ChunkShardingSpec from torch.distributed.fsdp._common_utils import _set_fsdp_flattened from torch.distributed.fsdp._fsdp_extensions import _set_fsdp_extensions, FSDPExtensions from torch.distributed.fsdp._shard_utils import _create_chunk_sharded_tensor from torch.distributed.fsdp.fully_sharded_data_parallel import ( CPUOffload, FullyShardedDataParallel as FSDP, StateDictType, ) from torch.distributed.remote_device import _remote_device from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class SimpleModel(torch.nn.Module):
import copy import sys from collections import OrderedDict from typing import Dict, List, Optional, Tuple import torch from torch import distributed as dist from torch.distributed._tensor import ( DeviceMesh, distribute_module, DTensor, init_device_mesh, Replicate, Shard, ) from torch.distributed.fsdp.fully_sharded_data_parallel import ( CPUOffload, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.tensor.debug import CommDebugMode from torch.distributed.tensor.parallel import ( ColwiseParallel, parallelize_module, RowwiseParallel, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, run_tests, TEST_WITH_DEV_DBG_ASAN, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( MLPModule, RMSNormPython, ) class SimpleModel(torch.nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_tp_integration.py
prepare_input_fn
def prepare_input_fn(mod, inputs, device_mesh): shard_tensor = DTensor.from_local(inputs[0], device_mesh, [Shard(0)]) return shard_tensor
import copy import sys from collections import OrderedDict from typing import Dict, List, Optional, Tuple import torch from torch import distributed as dist from torch.distributed._tensor import ( DeviceMesh, distribute_module, DTensor, init_device_mesh, Replicate, Shard, ) from torch.distributed.fsdp.fully_sharded_data_parallel import ( CPUOffload, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.tensor.debug import CommDebugMode from torch.distributed.tensor.parallel import ( ColwiseParallel, parallelize_module, RowwiseParallel, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, run_tests, TEST_WITH_DEV_DBG_ASAN, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( MLPModule, RMSNormPython, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_tp_integration.py
prepare_output_fn
class TestTPFSDPIntegration(FSDPTest): def _get_params_and_sharding_info( self, model: SimpleModel, sharded_param_names: List[str], tensor_parallel_size: int, ) -> Tuple[Dict[str, int], Dict[str, Tuple[torch.Size, int]]]: """ """ assert ( type(model) is SimpleModel ), "Expects a `SimpleModel` since the sharding cases on the model definition" param_name_to_numel = OrderedDict() param_name_to_sharding_info = OrderedDict() for param_name, param in model.named_parameters(): if param_name not in sharded_param_names: param_name_to_numel[param_name] = param.numel() else: param_name_to_numel[param_name] = param.numel() // tensor_parallel_size param_name_to_sharding_info[param_name] = ( param.size(), 0 if "net1" in param_name else 1, ) return param_name_to_numel, param_name_to_sharding_info
def prepare_output_fn(mod, outputs, device_mesh): return outputs.to_local() return distribute_module( module, device_mesh, input_fn=prepare_input_fn, output_fn=prepare_output_fn )
import copy import sys from collections import OrderedDict from typing import Dict, List, Optional, Tuple import torch from torch import distributed as dist from torch.distributed._tensor import ( DeviceMesh, distribute_module, DTensor, init_device_mesh, Replicate, Shard, ) from torch.distributed.fsdp.fully_sharded_data_parallel import ( CPUOffload, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.tensor.debug import CommDebugMode from torch.distributed.tensor.parallel import ( ColwiseParallel, parallelize_module, RowwiseParallel, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, run_tests, TEST_WITH_DEV_DBG_ASAN, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( MLPModule, RMSNormPython, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_tp_integration.py
_get_sub_pgs
def _get_sub_pgs(self, tensor_parallel_size: int): """ Generates TP and FSDP subprocess groups. ``tensor_parallel_size`` gives the TP process group size. For example, if the global world size is 8 and the tensor parallel size is 2, then this creates: - 4 TP subprocess groups: [0, 1], [2, 3], [4, 5], [6, 7] - 2 FSDP subprocess groups: [0, 2, 4, 6], [1, 3, 5, 7] """ tp_ranks: List[List[int]] = [] fsdp_ranks: List[List[int]] = [] for rank in range(self.world_size): tp_idx = rank // tensor_parallel_size if len(tp_ranks) <= tp_idx: tp_ranks.append([]) tp_ranks[tp_idx].append(rank) fsdp_idx = rank % tensor_parallel_size if len(fsdp_ranks) <= fsdp_idx: fsdp_ranks.append([]) fsdp_ranks[fsdp_idx].append(rank) tp_pgs = [dist.new_group(ranks) for ranks in tp_ranks] fsdp_pgs = [dist.new_group(ranks) for ranks in fsdp_ranks] tp_pg = tp_pgs[self.rank // tensor_parallel_size] fsdp_pg = fsdp_pgs[self.rank % tensor_parallel_size] return tp_pg, fsdp_pg
def _get_sub_pgs(self, tensor_parallel_size: int): """ Generates TP and FSDP subprocess groups. ``tensor_parallel_size`` gives the TP process group size. For example, if the global world size is 8 and the tensor parallel size is 2, then this creates: - 4 TP subprocess groups: [0, 1], [2, 3], [4, 5], [6, 7] - 2 FSDP subprocess groups: [0, 2, 4, 6], [1, 3, 5, 7] """ # 2-D mesh is [dp, tp] twod_mesh = DeviceMesh( device_type="cuda", mesh=torch.arange(0, self.world_size).view(-1, tensor_parallel_size), ) fsdp_pg = twod_mesh.get_group(mesh_dim=0) tp_pg = twod_mesh.get_group(mesh_dim=1) return twod_mesh, fsdp_pg, tp_pg
import copy import sys from collections import OrderedDict from typing import Any, Dict, List, NamedTuple, Optional, Tuple import torch import torch.distributed._shard.sharding_spec as shard_spec from torch import distributed as dist from torch.distributed._shard import shard_module from torch.distributed._shard.sharded_tensor.api import Shard, ShardedTensor from torch.distributed._shard.sharding_plan import ShardingPlan from torch.distributed._shard.sharding_spec import ChunkShardingSpec from torch.distributed.fsdp._common_utils import _set_fsdp_flattened from torch.distributed.fsdp._fsdp_extensions import _set_fsdp_extensions, FSDPExtensions from torch.distributed.fsdp._shard_utils import _create_chunk_sharded_tensor from torch.distributed.fsdp.fully_sharded_data_parallel import ( CPUOffload, FullyShardedDataParallel as FSDP, StateDictType, ) from torch.distributed.remote_device import _remote_device from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestTPFSDPIntegration(FSDPTest):
import copy import sys from collections import OrderedDict from typing import Dict, List, Optional, Tuple import torch from torch import distributed as dist from torch.distributed._tensor import ( DeviceMesh, distribute_module, DTensor, init_device_mesh, Replicate, Shard, ) from torch.distributed.fsdp.fully_sharded_data_parallel import ( CPUOffload, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.tensor.debug import CommDebugMode from torch.distributed.tensor.parallel import ( ColwiseParallel, parallelize_module, RowwiseParallel, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, run_tests, TEST_WITH_DEV_DBG_ASAN, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( MLPModule, RMSNormPython, ) class TestTPFSDPIntegration(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_tp_integration.py
test_fsdp_tp_checkpoint_integration
def test_fsdp_tp_checkpoint_integration(self): """Tests checkpointing for TP + FSDP integration.""" tensor_parallel_size = 2 torch.manual_seed(0) model = SimpleModel().cuda(self.rank) tp_pg, fsdp_pg = self._get_sub_pgs(tensor_parallel_size) # Shard with TP and then wrap with FSDP sharding_specs = self._get_chunk_sharding_spec(tp_pg.size(), tp_pg) sharding_plan = SimpleModel.module_sharding_plan(sharding_specs) shard_module(model, sharding_plan, process_group=tp_pg) tp_fsdp_model = FSDP(model, process_group=fsdp_pg) # Check that we produce a nested ST from model state dict with FSDP.state_dict_type(tp_fsdp_model, StateDictType.SHARDED_STATE_DICT): state_dict = tp_fsdp_model.state_dict() # TODO once 2D is out, validate the nesting self.assertTrue(_is_nested_tensor(state_dict["net1.weight"])) self.assertFalse(_is_nested_tensor(state_dict["net1.bias"])) tp_fsdp_model.load_state_dict(state_dict) tp_fsdp_optim = torch.optim.Adam(tp_fsdp_model.parameters(), lr=0.0001) input_seed = self.rank torch.manual_seed(input_seed + 1) inp_size = [2, 3, 5] inp = torch.rand(*inp_size).cuda(self.rank) tp_fsdp_model(inp).sum().backward() tp_fsdp_optim.step() # Check that we produce a nested ST from optim state dict optim_state = FSDP.sharded_optim_state_dict(tp_fsdp_model, tp_fsdp_optim) # TODO once 2D is out, validate the nesting self.assertTrue( _is_nested_tensor(optim_state["state"]["net1.weight"]["exp_avg"]) ) self.assertFalse( _is_nested_tensor(optim_state["state"]["net1.bias"]["exp_avg"]) )
import copy import sys from collections import OrderedDict from typing import Any, Dict, List, NamedTuple, Optional, Tuple import torch import torch.distributed._shard.sharding_spec as shard_spec from torch import distributed as dist from torch.distributed._shard import shard_module from torch.distributed._shard.sharded_tensor.api import Shard, ShardedTensor from torch.distributed._shard.sharding_plan import ShardingPlan from torch.distributed._shard.sharding_spec import ChunkShardingSpec from torch.distributed.fsdp._common_utils import _set_fsdp_flattened from torch.distributed.fsdp._fsdp_extensions import _set_fsdp_extensions, FSDPExtensions from torch.distributed.fsdp._shard_utils import _create_chunk_sharded_tensor from torch.distributed.fsdp.fully_sharded_data_parallel import ( CPUOffload, FullyShardedDataParallel as FSDP, StateDictType, ) from torch.distributed.remote_device import _remote_device from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestTPFSDPIntegration(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
deleted
torch
test/distributed/fsdp/test_fsdp_state_dict.py
__init__
def __init__(self, wrap_fsdp, register_buffers=False, ignore_inner=False): super().__init__() self.inner = Linear(*INNER_SHAPE) if register_buffers: self.inner.register_buffer("buffer", torch.randn(BUFFER_SHAPE)) self.inner.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False ) if wrap_fsdp: self.inner = FSDP( self.inner, ignored_modules=([self.inner] if ignore_inner else []) ) self.outer = Linear(*OUTER_SHAPE) if register_buffers: self.outer.register_buffer("buffer", torch.randn(BUFFER_SHAPE)) self.outer.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False )
def __init__( self, wrap_fsdp, register_buffers=False, ignore_inner=False, mixed_precision=False, process_group=None, ): super().__init__() self.inner = Linear(*INNER_SHAPE) if register_buffers: self.inner.buffer = nn.Buffer(torch.randn(BUFFER_SHAPE)) self.inner.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False ) if wrap_fsdp: self.inner = FSDP( self.inner, ignored_modules=([self.inner] if ignore_inner else []), mixed_precision=MixedPrecision( param_dtype=torch.float16, reduce_dtype=torch.float16, buffer_dtype=torch.float16, ) if mixed_precision else None, process_group=process_group, ) self.outer = Linear(*OUTER_SHAPE) if register_buffers: self.outer.buffer = nn.Buffer(torch.randn(BUFFER_SHAPE)) self.outer.register_buffer( "non_persistent_buffer", torch.randn(BUFFER_SHAPE), persistent=False )
import io import itertools import sys from contextlib import suppress from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class Model(Module):
import io import itertools import sys from contextlib import nullcontext from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardedTensor, ) from torch.distributed._state_dict_utils import ( _all_gather_sharded_tensor, _gather_state_dict, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._common_utils import FSDP_PREFIX from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class Model(Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_state_dict.py
test_world_size_one
def test_world_size_one(self): my_pg = None for i in range(self.world_size): pg = dist.new_group(ranks=[i]) if i == self.rank: my_pg = pg model = TransformerWithSharedParams.init( my_pg, FSDPInitMode.RECURSIVE, CUDAInitMode.CUDA_BEFORE, ) with FSDP.state_dict_type(model, StateDictType.SHARDED_STATE_DICT): state_dict = model.state_dict() model.load_state_dict(state_dict) dist.barrier()
import io import itertools import sys from contextlib import nullcontext from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardedTensor, ) from torch.distributed._state_dict_utils import ( _all_gather_sharded_tensor, _gather_state_dict, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._common_utils import FSDP_PREFIX from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class TestFSDPStateDict(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_state_dict.py
world_size
def world_size(self): return 2
def world_size(self): return min(torch.cuda.device_count(), 2)
import io import itertools import sys from contextlib import suppress from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._shard_utils import _gather_state_dict from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class TestFSDPStateDict(FSDPTest):
import io import itertools import sys from contextlib import nullcontext from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardedTensor, ) from torch.distributed._state_dict_utils import ( _all_gather_sharded_tensor, _gather_state_dict, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._common_utils import FSDP_PREFIX from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class TestFSDPStateDict(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_state_dict.py
test_local_state_dict_reshard
instantiate_parametrized_tests(TestFSDPStateDict) if __name__ == "__main__": run_tests()
def test_local_state_dict_reshard(self): """ This test demonstrates the ability to do resharding when using local_state_dict. Although we do not recommend users to use local_state_dict, there are still some corner cases that using local_state_dict is a better solution. """ model = FSDP(Model(wrap_fsdp=True)).cuda() optim = torch.optim.SGD(model.parameters(), lr=0.1) batch = torch.randn(4, 4, device=torch.cuda.current_device()) output = model(batch) loss = output.sum() loss.backward() optim.step() with FSDP.state_dict_type(model, StateDictType.LOCAL_STATE_DICT): state_dict = model.state_dict() rank = dist.get_rank() new_pg = dist.new_group(ranks=[0, 1]) resharded_state_dict = {} # Mimic resharding from 4 GPUs to 2 GPUs for key, value in state_dict.items(): if isinstance(value, ShardedTensor): full_flat_param = _all_gather_sharded_tensor(value) if rank < 2: full_numel = full_flat_param.size() chunks = full_flat_param.chunk(2) flat_param = chunks[rank] shard_offset = 0 if rank == 0 else chunks[0].numel() local_shards = [ Shard.from_tensor_and_offsets(flat_param, [shard_offset], rank) ] sharded_tensor = init_from_local_shards( local_shards, full_numel, process_group=new_pg ) resharded_state_dict[key] = sharded_tensor else: if rank < 2: resharded_state_dict[key] = value if rank < 2: model2 = FSDP( Model(wrap_fsdp=True, process_group=new_pg), process_group=new_pg ).cuda() with FSDP.state_dict_type(model2, StateDictType.LOCAL_STATE_DICT): model2.load_state_dict(resharded_state_dict) with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT): full_state_dict1 = model.state_dict() if rank < 2: with FSDP.state_dict_type(model2, StateDictType.FULL_STATE_DICT): full_state_dict2 = model2.state_dict() self.assertEqual(full_state_dict1, full_state_dict2)
import io import itertools import sys from contextlib import nullcontext from copy import deepcopy from functools import partial from typing import Any, Dict import torch import torch.nn as nn from torch import distributed as dist from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardedTensor, ) from torch.distributed._state_dict_utils import ( _all_gather_sharded_tensor, _gather_state_dict, ) from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( apply_activation_checkpointing, checkpoint_wrapper, CheckpointImpl, ) from torch.distributed.fsdp import ( CPUOffload, FullStateDictConfig, FullyShardedDataParallel as FSDP, LocalStateDictConfig, MixedPrecision, ShardedStateDictConfig, StateDictType, ) from torch.distributed.fsdp._common_utils import FSDP_PREFIX from torch.distributed.fsdp._unshard_param_utils import FLAT_PARAM from torch.distributed.fsdp.wrap import enable_wrap, ModuleWrapPolicy, wrap from torch.nn import Linear, Module, TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel import DistributedDataParallel from torch.optim import SGD from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _assert_module_states, _broadcast_state_dict, _get_state_dict, _zero_model, CUDAInitMode, FSDPInitMode, FSDPTest, get_full_params, SkipModel, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) INNER_SHAPE = [4, 4] OUTER_SHAPE = [4, 5] BUFFER_SHAPE = [5, 5] NON_ROOT_FSDP_PREFIX = "non_fsdp_lin" _UNFLATTENED_STATE_DICT_IMPLS = ["state_dict", "sharded_state_dict"] _FLATTENED_STATE_DICT_IMPLS = ["local_state_dict"] _SUPPORTED_STATE_DICT_IMPLS = ( _UNFLATTENED_STATE_DICT_IMPLS + _FLATTENED_STATE_DICT_IMPLS ) STATE_DICT_MAPPING = { "state_dict": StateDictType.FULL_STATE_DICT, "local_state_dict": StateDictType.LOCAL_STATE_DICT, "sharded_state_dict": StateDictType.SHARDED_STATE_DICT, } class TestFSDPStateDict4GPUs(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_unshard_params.py
__init__
def __init__(self): super().__init__() self.a = nn.Parameter(torch.zeros(5))
def __init__(self) -> None: super().__init__() self.a = nn.Parameter(torch.zeros(5))
import contextlib import itertools import math import sys from typing import Any, Dict, List, Optional, Union import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.flat_param import FlatParameter from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN class MyModule(nn.Module):
import contextlib import itertools import math import sys from typing import Any, Dict, List, Optional, Union import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import FlatParameter from torch.distributed.fsdp.fully_sharded_data_parallel import FLAT_PARAM from torch.distributed.fsdp.wrap import ModuleWrapPolicy from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN class MyModule(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_hsdp_dtensor_state_dict.py
__init__
def __init__(self) -> None: super().__init__() torch.manual_seed(0) self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU()) self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU()) self.net3 = nn.Sequential(nn.Linear(32, 64), nn.ReLU()) self.net4 = nn.Sequential(nn.ReLU(), nn.Linear(64, 8))
import io from copy import deepcopy import torch import torch.distributed as dist import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._tensor import DTensor, Replicate, Shard from torch.distributed.device_mesh import init_device_mesh from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ( ShardedOptimStateDictConfig, ShardedStateDictConfig, ShardingStrategy, StateDictType, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( DTensorTestBase, skip_if_lt_x_gpu, with_comms, ) class DenseModel(torch.nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_hsdp_dtensor_state_dict.py
forward
def forward(self, x): return self.net4(self.net3(self.net2(self.net1(x))))
import io from copy import deepcopy import torch import torch.distributed as dist import torch.nn as nn from torch.distributed._shard.sharded_tensor import ShardedTensor from torch.distributed._tensor import DTensor, Replicate, Shard from torch.distributed.device_mesh import init_device_mesh from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.api import ( ShardedOptimStateDictConfig, ShardedStateDictConfig, ShardingStrategy, StateDictType, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( DTensorTestBase, skip_if_lt_x_gpu, with_comms, ) class DenseModel(torch.nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_shard_utils.py
_create_local_chunk
def _create_local_chunk(self, tensor): chunk = tensor.chunk(2)[self.rank] offsets = [0] if self.rank == 0 else [tensor.shape[0] - chunk.shape[0]] shard = Shard.from_tensor_and_offsets(chunk, offsets, self.rank) return init_from_local_shards([shard], tensor.numel())
import torch from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardMetadata, ) from torch.distributed._shard.sharding_spec import ( ChunkShardingSpec, EnumerableShardingSpec, ) from torch.distributed.distributed_c10d import _get_default_group from torch.distributed.fsdp._shard_utils import ( _create_chunk_sharded_tensor, _offsets_to_split_sizes, _reshard_flatten_tensor, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import TestCase class TestShardUtilsDistributed(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
deleted
torch
test/distributed/fsdp/test_shard_utils.py
_create_enumerate_spec
def _create_enumerate_spec(self, tensor): # Since placement is not used, always set placement to rank0 to mimic # the actual usage. metadata = [ ShardMetadata([0], [101], placement="rank0/cuda:0"), ShardMetadata([101], [900], placement="rank0/cuda:0"), ] return EnumerableShardingSpec(metadata)
import torch from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardMetadata, ) from torch.distributed._shard.sharding_spec import ( ChunkShardingSpec, EnumerableShardingSpec, ) from torch.distributed.distributed_c10d import _get_default_group from torch.distributed.fsdp._shard_utils import ( _create_chunk_sharded_tensor, _offsets_to_split_sizes, _reshard_flatten_tensor, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import TestCase class TestShardUtilsDistributed(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
deleted
torch
test/distributed/fsdp/test_shard_utils.py
_create_chunk_spec
def _create_chunk_spec(self): return ChunkShardingSpec(dim=0, placements=["rank0/cuda:0"])
import torch from torch.distributed._shard.sharded_tensor import ( init_from_local_shards, Shard, ShardMetadata, ) from torch.distributed._shard.sharding_spec import ( ChunkShardingSpec, EnumerableShardingSpec, ) from torch.distributed.distributed_c10d import _get_default_group from torch.distributed.fsdp._shard_utils import ( _create_chunk_sharded_tensor, _offsets_to_split_sizes, _reshard_flatten_tensor, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import TestCase class TestShardUtilsDistributed(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
deleted
torch
test/distributed/fsdp/test_fsdp_use_orig_params.py
test_diff_hyperparams_cpu_offload
def test_diff_hyperparams_cpu_offload(self, sharding_strategy_str: str): """ Tests FSDP parity with DDP when using multiple parameter groups with different hyperparameter settings with CPU offloading enabled. This is separate from :meth:`test_diff_hyperparams` because CPU offloading has some issues with subtesting for some specific subtesting configs (e.g., with ``offload_params=False`` followed by ``True`` but not vice versa). """ sharding_strategy = self._get_sharding_strategy_from_str(sharding_strategy_str) self._test_diff_hyperparams( cuda_init_mode=CUDAInitMode.CUDA_BEFORE, init_optim_before_wrap=False, optim_class=torch.optim.Adam, multi_tensor=False, set_to_none=False, backward_prefetch=BackwardPrefetch.BACKWARD_PRE, cpu_offload=CPUOffload(offload_params=True), sharding_strategy=sharding_strategy, )
def test_diff_hyperparams_cpu_offload(self, sharding_strategy_str: str): """ Tests FSDP parity with DDP when using multiple parameter groups with different hyperparameter settings with CPU offloading enabled. This is separate from :meth:`test_diff_hyperparams` because CPU offloading has some issues with subtesting for some specific subtesting configs (e.g., with ``offload_params=False`` followed by ``True`` but not vice versa). """ sharding_strategy = self._get_sharding_strategy_from_str(sharding_strategy_str) for skip_writeback_check in (False, True): self._test_diff_hyperparams( cuda_init_mode=CUDAInitMode.CUDA_BEFORE, init_optim_before_wrap=False, optim_class=torch.optim.Adam, multi_tensor=False, set_to_none=False, backward_prefetch=BackwardPrefetch.BACKWARD_PRE, cpu_offload=CPUOffload(offload_params=True), sharding_strategy=sharding_strategy, skip_writeback_check=skip_writeback_check, )
import copy import functools import itertools import sys from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestFSDPUseOrigParamsMultipleParamGroups(FSDPTest):
import copy import functools import itertools import os import sys import unittest from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, StateDictType, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import ( _FSDP_SKIP_WRITEBACK_CHECK, _FSDP_USE_FULL_PREC_IN_EVAL, ) from torch.distributed.fsdp._init_utils import NO_RESHARD_AFTER_FORWARD_STRATEGIES from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, TestCase, ) from torch.utils._triton import has_triton class TestFSDPUseOrigParamsMultipleParamGroups(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_use_orig_params.py
_test_multiple_optimizers
def _test_multiple_optimizers(self, sharding_strategy: ShardingStrategy): ddp_model = self._get_ddp_transformer(find_unused_params=True) ddp_param_groups = self._get_param_groups(ddp_model) assert len(ddp_param_groups) == 3, f"{len(ddp_param_groups)}" ( fsdp_model, _, ) = self._get_fsdp_transformer_and_optim( # ignore returned optimizer cuda_init_mode=CUDAInitMode.CUDA_BEFORE, init_optim_before_wrap=False, optim_class=torch.optim.Adam, # ignored multi_tensor=False, # ignored sharding_strategy=sharding_strategy, backward_prefetch=BackwardPrefetch.BACKWARD_PRE, cpu_offload=None, ) fsdp_param_groups = self._get_param_groups(fsdp_model) assert len(fsdp_param_groups) == 3, f"{len(fsdp_param_groups)}" ddp_optims = [] fsdp_optims = [] # For the transformer model, every parameter is either a weight or a # bias, so we only use the first two parameter groups. Moreover, we use # Adam and AdamW in particular since they both use bias correction # dependent on the step, which is incremented even if a parameter has a # zero gradient but not if the gradient is `None`. This is to test that # we are differentiating between a zero and `None` gradient correctly. optim_ctors = [ functools.partial(torch.optim.Adam, lr=5e-3), functools.partial(torch.optim.AdamW, lr=1e-2), ] for optim_ctor, ddp_param_group, fsdp_param_group in zip( optim_ctors, ddp_param_groups[:2], fsdp_param_groups[:2], ): ddp_optims.append(optim_ctor(ddp_param_group["params"])) fsdp_optims.append(optim_ctor(fsdp_param_group["params"])) device = torch.device("cuda") # Check that there exists a `FlatParameter` that has both a weight and # a bias in this rank's shard has_both = False for fsdp_module in FSDP.fsdp_modules(fsdp_model): for handle in fsdp_module._handles: flat_param = handle.flat_param assert flat_param._params is not None has_weight = False has_bias = False for param, fqn in zip(flat_param._params, flat_param._fqns): if "weight" in fqn and param.numel() > 0: has_weight = True elif "bias" in fqn and param.numel() > 0: has_bias = True has_both |= has_weight and has_bias assert has_both, ( f"Rank {self.rank} does not have a `FlatParameter` with both a " "weight and a bias in its shard, meaning that this test is vacuous" ) # Run one iteration to generate gradients def run_iter(): iter_losses = [] for model, optims in ((ddp_model, ddp_optims), (fsdp_model, fsdp_optims)): module = model.module inp = module.get_input(device) output = model(*inp) loss = module.get_loss(inp, output).to(device) iter_losses.append(loss) module.run_backward(loss) for optim in optims: optim.step() torch.testing.assert_close(iter_losses[0], iter_losses[1]) iter_losses.clear() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) run_iter() # Only set the weights' gradients to None ddp_optims[0].zero_grad(set_to_none=True) fsdp_optims[0].zero_grad(set_to_none=True) inp = ddp_model.module.get_input(device) ddp_output = ddp_model(*inp) fsdp_output = fsdp_model(*inp) # Check that FSDP correctly exposes gradients even after forward # (namely, `None` for weights and non-`None` for biases) for (ddp_n, ddp_p), (fsdp_n, fsdp_p) in zip( ddp_model.module.named_parameters(), fsdp_model.named_parameters(), ): self.assertEqual(ddp_n, clean_tensor_name(fsdp_n)) if fsdp_p.numel() == 0: # Not in this rank's shard self.assertTrue(fsdp_p.grad is None) continue if ddp_p.grad is None: self.assertTrue(fsdp_p.grad is None) else: self.assertEqual(ddp_p.flatten(), fsdp_p.flatten()) self.assertEqual(ddp_p.grad.flatten(), fsdp_p.grad.flatten()) self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) # Finish the iteration (backward pass and optimizer step) ddp_loss = ddp_model.module.get_loss(inp, ddp_output).to(device) fsdp_loss = fsdp_model.module.get_loss(inp, fsdp_output).to(device) ddp_model.module.run_backward(ddp_loss) fsdp_model.module.run_backward(fsdp_loss) for optim in itertools.chain(ddp_optims, fsdp_optims): optim.step() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) # Run one more iteration to confirm bias corrections are correct run_iter() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model)
def _test_multiple_optimizers(self, sharding_strategy: ShardingStrategy): ddp_model = self._get_ddp_transformer(find_unused_params=True) ddp_param_groups = self._get_param_groups(ddp_model) assert len(ddp_param_groups) == 3, f"{len(ddp_param_groups)}" ( fsdp_model, _, ) = self._get_fsdp_transformer_and_optim( # ignore returned optimizer cuda_init_mode=CUDAInitMode.CUDA_BEFORE, init_optim_before_wrap=False, optim_class=torch.optim.Adam, # ignored multi_tensor=False, # ignored sharding_strategy=sharding_strategy, backward_prefetch=BackwardPrefetch.BACKWARD_PRE, cpu_offload=None, ) fsdp_param_groups = self._get_param_groups(fsdp_model) assert len(fsdp_param_groups) == 3, f"{len(fsdp_param_groups)}" ddp_optims = [] fsdp_optims = [] # For the transformer model, every parameter is either a weight or a # bias, so we only use the first two parameter groups. Moreover, we use # Adam and AdamW in particular since they both use bias correction # dependent on the step, which is incremented even if a parameter has a # zero gradient but not if the gradient is `None`. This is to test that # we are differentiating between a zero and `None` gradient correctly. optim_ctors = [ functools.partial(torch.optim.Adam, lr=5e-3), functools.partial(torch.optim.AdamW, lr=1e-2), ] for optim_ctor, ddp_param_group, fsdp_param_group in zip( optim_ctors, ddp_param_groups[:2], fsdp_param_groups[:2], ): ddp_optims.append(optim_ctor(ddp_param_group["params"])) fsdp_optims.append(optim_ctor(fsdp_param_group["params"])) device = torch.device("cuda") # Check that there exists a `FlatParameter` that has both a weight and # a bias in this rank's shard has_both = False for fsdp_module in FSDP.fsdp_modules(fsdp_model): handle = fsdp_module._handle if not handle: continue flat_param = handle.flat_param assert flat_param._params is not None has_weight = False has_bias = False for param, fqn in zip(flat_param._params, flat_param._fqns): if "weight" in fqn and param.numel() > 0: has_weight = True elif "bias" in fqn and param.numel() > 0: has_bias = True has_both |= has_weight and has_bias assert has_both, ( f"Rank {self.rank} does not have a `FlatParameter` with both a " "weight and a bias in its shard, meaning that this test is vacuous" ) # Run one iteration to generate gradients def run_iter(): iter_losses = [] for model, optims in ((ddp_model, ddp_optims), (fsdp_model, fsdp_optims)): module = model.module inp = module.get_input(device) output = model(*inp) loss = module.get_loss(inp, output).to(device) iter_losses.append(loss) module.run_backward(loss) for optim in optims: optim.step() torch.testing.assert_close(iter_losses[0], iter_losses[1]) iter_losses.clear() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) run_iter() # Only set the weights' gradients to None ddp_optims[0].zero_grad(set_to_none=True) fsdp_optims[0].zero_grad(set_to_none=True) inp = ddp_model.module.get_input(device) ddp_output = ddp_model(*inp) fsdp_output = fsdp_model(*inp) # Check that FSDP correctly exposes gradients even after forward # (namely, `None` for weights and non-`None` for biases) if sharding_strategy in NO_RESHARD_AFTER_FORWARD_STRATEGIES: # Skip the check since we do not expose the gradients after forward # for these strategies return for (ddp_n, ddp_p), (fsdp_n, fsdp_p) in zip( ddp_model.module.named_parameters(), fsdp_model.named_parameters(), ): self.assertEqual(ddp_n, clean_tensor_name(fsdp_n)) if fsdp_p.numel() == 0: # Not in this rank's shard self.assertTrue(fsdp_p.grad is None) continue if ddp_p.grad is None: self.assertTrue(fsdp_p.grad is None) else: self.assertEqual(ddp_p.flatten(), fsdp_p.flatten()) self.assertEqual(ddp_p.grad.flatten(), fsdp_p.grad.flatten()) self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) # Finish the iteration (backward pass and optimizer step) ddp_loss = ddp_model.module.get_loss(inp, ddp_output).to(device) fsdp_loss = fsdp_model.module.get_loss(inp, fsdp_output).to(device) ddp_model.module.run_backward(ddp_loss) fsdp_model.module.run_backward(fsdp_loss) for optim in itertools.chain(ddp_optims, fsdp_optims): optim.step() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) # Run one more iteration to confirm bias corrections are correct run_iter() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model)
import copy import functools import itertools import sys from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class TestFSDPUseOrigParamsMultipleParamGroups(FSDPTest):
import copy import functools import itertools import os import sys import unittest from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, StateDictType, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import ( _FSDP_SKIP_WRITEBACK_CHECK, _FSDP_USE_FULL_PREC_IN_EVAL, ) from torch.distributed.fsdp._init_utils import NO_RESHARD_AFTER_FORWARD_STRATEGIES from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, TestCase, ) from torch.utils._triton import has_triton class TestFSDPUseOrigParamsMultipleParamGroups(FSDPTest):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_use_orig_params.py
run_iter
def run_iter(): iter_losses = [] for model, optims in ((ddp_model, ddp_optims), (fsdp_model, fsdp_optims)): module = model.module inp = module.get_input(device) output = model(*inp) loss = module.get_loss(inp, output).to(device) iter_losses.append(loss) module.run_backward(loss) for optim in optims: optim.step() torch.testing.assert_close(iter_losses[0], iter_losses[1]) iter_losses.clear() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) run_iter() # Only set the weights' gradients to None ddp_optims[0].zero_grad(set_to_none=True) fsdp_optims[0].zero_grad(set_to_none=True) inp = ddp_model.module.get_input(device) ddp_output = ddp_model(*inp) fsdp_output = fsdp_model(*inp) # Check that FSDP correctly exposes gradients even after forward # (namely, `None` for weights and non-`None` for biases) for (ddp_n, ddp_p), (fsdp_n, fsdp_p) in zip( ddp_model.module.named_parameters(), fsdp_model.named_parameters(), ): self.assertEqual(ddp_n, clean_tensor_name(fsdp_n)) if fsdp_p.numel() == 0: # Not in this rank's shard self.assertTrue(fsdp_p.grad is None) continue if ddp_p.grad is None: self.assertTrue(fsdp_p.grad is None) else: self.assertEqual(ddp_p.flatten(), fsdp_p.flatten()) self.assertEqual(ddp_p.grad.flatten(), fsdp_p.grad.flatten()) self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) # Finish the iteration (backward pass and optimizer step) ddp_loss = ddp_model.module.get_loss(inp, ddp_output).to(device) fsdp_loss = fsdp_model.module.get_loss(inp, fsdp_output).to(device) ddp_model.module.run_backward(ddp_loss) fsdp_model.module.run_backward(fsdp_loss) for optim in itertools.chain(ddp_optims, fsdp_optims): optim.step() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) # Run one more iteration to confirm bias corrections are correct run_iter() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model)
def run_iter(): iter_losses = [] for model, optims in ((ddp_model, ddp_optims), (fsdp_model, fsdp_optims)): module = model.module inp = module.get_input(device) output = model(*inp) loss = module.get_loss(inp, output).to(device) iter_losses.append(loss) module.run_backward(loss) for optim in optims: optim.step() torch.testing.assert_close(iter_losses[0], iter_losses[1]) iter_losses.clear() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) run_iter() # Only set the weights' gradients to None ddp_optims[0].zero_grad(set_to_none=True) fsdp_optims[0].zero_grad(set_to_none=True) inp = ddp_model.module.get_input(device) ddp_output = ddp_model(*inp) fsdp_output = fsdp_model(*inp) # Check that FSDP correctly exposes gradients even after forward # (namely, `None` for weights and non-`None` for biases) if sharding_strategy in NO_RESHARD_AFTER_FORWARD_STRATEGIES: # Skip the check since we do not expose the gradients after forward # for these strategies return for (ddp_n, ddp_p), (fsdp_n, fsdp_p) in zip( ddp_model.module.named_parameters(), fsdp_model.named_parameters(), ): self.assertEqual(ddp_n, clean_tensor_name(fsdp_n)) if fsdp_p.numel() == 0: # Not in this rank's shard self.assertTrue(fsdp_p.grad is None) continue if ddp_p.grad is None: self.assertTrue(fsdp_p.grad is None) else: self.assertEqual(ddp_p.flatten(), fsdp_p.flatten()) self.assertEqual(ddp_p.grad.flatten(), fsdp_p.grad.flatten()) self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) # Finish the iteration (backward pass and optimizer step) ddp_loss = ddp_model.module.get_loss(inp, ddp_output).to(device) fsdp_loss = fsdp_model.module.get_loss(inp, fsdp_output).to(device) ddp_model.module.run_backward(ddp_loss) fsdp_model.module.run_backward(fsdp_loss) for optim in itertools.chain(ddp_optims, fsdp_optims): optim.step() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model) # Run one more iteration to confirm bias corrections are correct run_iter() self._check_ddp_fsdp_param_parity(ddp_model, fsdp_model)
import copy import functools import itertools import sys from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
import copy import functools import itertools import os import sys import unittest from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, StateDictType, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import ( _FSDP_SKIP_WRITEBACK_CHECK, _FSDP_USE_FULL_PREC_IN_EVAL, ) from torch.distributed.fsdp._init_utils import NO_RESHARD_AFTER_FORWARD_STRATEGIES from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, TestCase, ) from torch.utils._triton import has_triton
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_unshard_params.py
test_unshard_params_respects_reshard
def test_unshard_params_respects_reshard(self): """ Tests that unsharding parameters respects the expected reshard behavior between forward and backward as well as after backward. """ self.run_subtests( { "rank0_only": [False, True], "offload_to_cpu": [False, True], "mixed_precision": [MixedPrecision(param_dtype=torch.float16), None], "use_orig_params": [False, True], }, self._test_unshard_params_respects_reshard, )
def test_unshard_params_respects_reshard(self): """ Tests that unsharding parameters respects the expected reshard behavior between forward and backward as well as after backward. For mixed precision, we should *not* respect the reshard behavior because the ``summon_full_params()`` forces full precision, which uses a different all-gather tensor than the one already in memory and will not persist any modifications correctly. """ self.run_subtests( { "rank0_only": [False, True], "offload_to_cpu": [False, True], "mixed_precision": [MixedPrecision(param_dtype=torch.float16), None], "use_orig_params": [False, True], }, self._test_unshard_params_respects_reshard, )
import contextlib import itertools import math import sys from typing import Any, Dict, List, Optional, Union import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.flat_param import FlatParameter from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN class TestUnshardParams(TestUnshardParamsBase):
import contextlib import itertools import math import sys from typing import Any, Dict, List, Optional, Union import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import FlatParameter from torch.distributed.fsdp.fully_sharded_data_parallel import FLAT_PARAM from torch.distributed.fsdp.wrap import ModuleWrapPolicy from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN class TestUnshardParams(TestUnshardParamsBase):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_unshard_params.py
_get_unsharded_storage_size
def _get_unsharded_storage_size(flat_param: FlatParameter): return flat_param._full_param_padded.storage().size() # Validate the expected behavior: the root does not reshard after # forward; the non-root reshards after forward; and both reshard after # backward output = model(torch.zeros(5, device=self.device)) self.assertEqual( expected_outer_flat_param_unsharded_numel, _get_unsharded_storage_size(outer_flat_param), ) self.assertEqual(0, _get_unsharded_storage_size(inner_flat_param)) output.sum().backward() self.assertEqual(0, _get_unsharded_storage_size(outer_flat_param)) self.assertEqual(0, _get_unsharded_storage_size(inner_flat_param)) # Check that with parameter unsharding in between forward and backward # as well as after backward, the reshard behavior matches output = model(torch.zeros(5, device=self.device)) with FSDP.summon_full_params( model, rank0_only=rank0_only, writeback=not rank0_only, offload_to_cpu=offload_to_cpu, ): pass self.assertEqual( expected_outer_flat_param_unsharded_numel, _get_unsharded_storage_size(outer_flat_param), ) self.assertEqual(0, _get_unsharded_storage_size(inner_flat_param)) output.sum().backward() with FSDP.summon_full_params( model, rank0_only=rank0_only, writeback=not rank0_only, offload_to_cpu=offload_to_cpu, ): pass self.assertEqual(0, _get_unsharded_storage_size(outer_flat_param)) self.assertEqual(0, _get_unsharded_storage_size(inner_flat_param))
def _get_unsharded_storage_size(flat_param: FlatParameter): return flat_param._full_param_padded.storage().size() # Validate the expected behavior: the root does not reshard after # forward; the non-root reshards after forward; and both reshard after # backward output = model(torch.zeros(5, device=self.device)) self.assertEqual( expected_outer_flat_param_unsharded_numel, _get_unsharded_storage_size(outer_flat_param), ) self.assertEqual(0, _get_unsharded_storage_size(inner_flat_param)) output.sum().backward() self.assertEqual(0, _get_unsharded_storage_size(outer_flat_param)) self.assertEqual(0, _get_unsharded_storage_size(inner_flat_param)) # Check that with parameter unsharding in between forward and backward # as well as after backward, the reshard behavior matches output = model(torch.zeros(5, device=self.device)) with FSDP.summon_full_params( model, rank0_only=rank0_only, writeback=not rank0_only, offload_to_cpu=offload_to_cpu, ): pass if mixed_precision is not None: # After forcing full precision, we must invalidate the existing # unsharded low-precision flat parameter since it will not persist # changes from the `summon_full_params()` context, so we cannot # respect the reshard behavior expected_outer_flat_param_unsharded_numel = 0 self.assertEqual( expected_outer_flat_param_unsharded_numel, _get_unsharded_storage_size(outer_flat_param), ) self.assertEqual(0, _get_unsharded_storage_size(inner_flat_param)) output.sum().backward() with FSDP.summon_full_params( model, rank0_only=rank0_only, writeback=not rank0_only, offload_to_cpu=offload_to_cpu, ): pass self.assertEqual(0, _get_unsharded_storage_size(outer_flat_param)) self.assertEqual(0, _get_unsharded_storage_size(inner_flat_param))
import contextlib import itertools import math import sys from typing import Any, Dict, List, Optional, Union import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.flat_param import FlatParameter from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN
import contextlib import itertools import math import sys from typing import Any, Dict, List, Optional, Union import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import FlatParameter from torch.distributed.fsdp.fully_sharded_data_parallel import FLAT_PARAM from torch.distributed.fsdp.wrap import ModuleWrapPolicy from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_unshard_params.py
_get_error_context
def _get_error_context(is_supported: bool): return ( contextlib.suppress() if is_supported else self.assertRaises(NotImplementedError) ) # some configs are not implemented yet
def _get_error_context(is_supported: bool): return ( contextlib.nullcontext() if is_supported else self.assertRaises(NotImplementedError) ) # some configs are not implemented yet
import contextlib import itertools import math import sys from typing import Any, Dict, List, Optional, Union import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.flat_param import FlatParameter from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN
import contextlib import itertools import math import sys from typing import Any, Dict, List, Optional, Union import torch import torch.distributed.fsdp._traversal_utils as traversal_utils import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import FlatParameter from torch.distributed.fsdp.fully_sharded_data_parallel import FLAT_PARAM from torch.distributed.fsdp.wrap import ModuleWrapPolicy from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, NestedWrappedModule, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import run_tests, TEST_WITH_DEV_DBG_ASAN
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_use_orig_params.py
__init__
def __init__(self): super().__init__() torch.manual_seed(42) # 5 * 5 = 25 numel -> pad to 26 -> 13 on each rank self.lin1 = nn.Linear(5, 5, bias=False) # 5 * 7 + 7 = 42 numel -> no pad -> 21 on each rank # 21 of weight on rank 0; 14 of weight and 7 of bias on rank 1 self.lin2 = nn.Linear(5, 7)
def __init__(self) -> None: super().__init__() torch.manual_seed(42) # 5 * 5 = 25 numel -> pad to 26 -> 13 on each rank self.lin1 = nn.Linear(5, 5, bias=False) # 5 * 7 + (1) + 7 = 43 numel -> pad to 44 -> 22 on each rank, # where the (1) is from intra-`FlatParameter` alignment padding # 22 of weight on rank 0; 13 of weight, 1 alignment padding, # and 7 of bias on rank 1 self.lin2 = nn.Linear(5, 7)
import copy import functools import itertools import sys from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class Model(nn.Module):
import copy import functools import itertools import os import sys import unittest from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, StateDictType, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import ( _FSDP_SKIP_WRITEBACK_CHECK, _FSDP_USE_FULL_PREC_IN_EVAL, ) from torch.distributed.fsdp._init_utils import NO_RESHARD_AFTER_FORWARD_STRATEGIES from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, TestCase, ) from torch.utils._triton import has_triton class Model(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_use_orig_params.py
check_parameter_parity
def check_parameter_parity(ddp_model, fsdp_model): assert self.rank in ( 0, 1, ), f"Expects world size of 2 but got {self.world_size}" for (n1, p1), (n2, p2) in zip( ddp_model.module.named_parameters(), fsdp_model.named_parameters(), ): self.assertEqual(n1, clean_tensor_name(n2)) if sharding_strategy == ShardingStrategy.NO_SHARD: # For `NO_SHARD`, do nothing since the original parameters # are unflattened pass # Otherwise, case on the parameter (see the model definition) elif n1 == "lin1.weight": if self.rank == 0: p1 = p1.flatten()[:13] elif self.rank == 1: p1 = p1.flatten()[13:] elif n1 == "lin2.weight": if self.rank == 0: p1 = p1.flatten()[:21] elif self.rank == 1: p1 = p1.flatten()[21:] elif n1 == "lin2.bias": if self.rank == 0: p1 = torch.empty(0, device=p1.device) elif self.rank == 1: p1 = p1.flatten() torch.testing.assert_close(p1, p2) ddp_model = DDP(Model().cuda(), device_ids=[self.rank]) fsdp_model = FSDP( Model().cuda(), sharding_strategy=sharding_strategy, auto_wrap_policy=always_wrap_policy, use_orig_params=True, ) LR = 1e-2 ddp_optim = torch.optim.Adam(ddp_model.parameters(), lr=LR) fsdp_optim = torch.optim.Adam(fsdp_model.parameters(), lr=LR) device = torch.device("cuda") inp = fsdp_model.get_input(device) ddp_out = ddp_model(*inp) fsdp_out = fsdp_model(*inp) check_parameter_parity(ddp_model, fsdp_model) ddp_loss = ddp_model.module.get_loss(inp, ddp_out) fsdp_loss = fsdp_model.get_loss(inp, fsdp_out) ddp_loss.backward() fsdp_loss.backward() ddp_optim.step() fsdp_optim.step() check_parameter_parity(ddp_model, fsdp_model) inp = fsdp_model.get_input(device) ddp_out = ddp_model(*inp) fsdp_out = fsdp_model(*inp) check_parameter_parity(ddp_model, fsdp_model)
def check_parameter_parity( ddp_model: DDP, fsdp_model: FSDP, between_fwd_and_bwd: bool ): assert self.rank in ( 0, 1, ), f"Expects world size of 2 but got {self.world_size}" for (n1, p1), (n2, p2) in zip( ddp_model.module.named_parameters(), fsdp_model.named_parameters(), ): self.assertEqual(n1, clean_tensor_name(n2)) if sharding_strategy == ShardingStrategy.NO_SHARD: # For `NO_SHARD`, do nothing since the original parameters # are unflattened pass elif ( between_fwd_and_bwd and sharding_strategy in NO_RESHARD_AFTER_FORWARD_STRATEGIES ): # For no reshard after forward strategies, do nothing since # FSDP did not use sharded views after forward pass # Otherwise, case on the parameter (see the model definition) elif n1 == "lin1.weight": if self.rank == 0: p1 = p1.flatten()[:13] elif self.rank == 1: p1 = p1.flatten()[13:] elif n1 == "lin2.weight": if self.rank == 0: p1 = p1.flatten()[:22] elif self.rank == 1: p1 = p1.flatten()[22:] elif n1 == "lin2.bias": if self.rank == 0: p1 = torch.empty(0, device=p1.device) elif self.rank == 1: p1 = p1.flatten() torch.testing.assert_close(p1, p2) ddp_model = DDP(Model().cuda(), device_ids=[self.rank]) fsdp_model = FSDP( Model().cuda(), sharding_strategy=sharding_strategy, auto_wrap_policy=always_wrap_policy, use_orig_params=True, ) LR = 1e-2 ddp_optim = torch.optim.Adam(ddp_model.parameters(), lr=LR) fsdp_optim = torch.optim.Adam(fsdp_model.parameters(), lr=LR) device = torch.device("cuda") inp = fsdp_model.get_input(device) ddp_out = ddp_model(*inp) fsdp_out = fsdp_model(*inp) check_parameter_parity(ddp_model, fsdp_model, True) ddp_loss = ddp_model.module.get_loss(inp, ddp_out) fsdp_loss = fsdp_model.get_loss(inp, fsdp_out) ddp_loss.backward() fsdp_loss.backward() ddp_optim.step() fsdp_optim.step() check_parameter_parity(ddp_model, fsdp_model, False) inp = fsdp_model.get_input(device) ddp_out = ddp_model(*inp) fsdp_out = fsdp_model(*inp) check_parameter_parity(ddp_model, fsdp_model, True)
import copy import functools import itertools import sys from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, )
import copy import functools import itertools import os import sys import unittest from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, StateDictType, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import ( _FSDP_SKIP_WRITEBACK_CHECK, _FSDP_USE_FULL_PREC_IN_EVAL, ) from torch.distributed.fsdp._init_utils import NO_RESHARD_AFTER_FORWARD_STRATEGIES from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, TestCase, ) from torch.utils._triton import has_triton
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_fsdp_use_orig_params.py
__init__
def __init__(self): super().__init__() torch.manual_seed(42) # 5 * 5 = 25 numel -> pad to 26 -> 13 on each rank self.lin1 = nn.Linear(5, 5, bias=False) # 5 * 7 + 7 = 42 numel -> no pad -> 21 on each rank # 21 of weight on rank 0; 14 of weight and 7 of bias on rank 1 self.lin2 = nn.Linear(5, 7)
def __init__(self) -> None: super().__init__() torch.manual_seed(42) # 5 * 5 = 25 numel -> pad to 26 -> 13 on each rank self.lin1 = nn.Linear(5, 5, bias=False) # 5 * 7 + (1) + 7 = 43 numel -> pad to 44 -> 22 on each rank, # where the (1) is from intra-`FlatParameter` alignment padding # 22 of weight on rank 0; 13 of weight, 1 alignment padding, # and 7 of bias on rank 1 self.lin2 = nn.Linear(5, 7)
import copy import functools import itertools import sys from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, ) class Model(nn.Module):
import copy import functools import itertools import os import sys import unittest from typing import Any, Dict, List, Optional, Tuple, Type import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, StateDictType, ) from torch.distributed.fsdp._common_utils import clean_tensor_name from torch.distributed.fsdp._flat_param import ( _FSDP_SKIP_WRITEBACK_CHECK, _FSDP_USE_FULL_PREC_IN_EVAL, ) from torch.distributed.fsdp._init_utils import NO_RESHARD_AFTER_FORWARD_STRATEGIES from torch.distributed.fsdp.wrap import always_wrap_policy, ModuleWrapPolicy from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.parallel.distributed import DistributedDataParallel as DDP from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( CUDAInitMode, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, TEST_WITH_DEV_DBG_ASAN, TestCase, ) from torch.utils._triton import has_triton class Model(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/launcher/test_run.py
test_launch_with_env_vars
run_id = str(uuid.uuid4().int) nnodes = 1 nproc_per_node = 4 world_size = nnodes * nproc_per_node os.environ["PET_NNODES"] = str(nnodes) os.environ["PET_NPROC_PER_NODE"] = str(nproc_per_node) os.environ["PET_RDZV_BACKEND"] = "etcd" os.environ["PET_RDZV_ENDPOINT"] = self._etcd_endpoint os.environ["PET_RDZV_ID"] = run_id os.environ["PET_MONITOR_INTERVAL"] = "1" os.environ["PET_START_METHOD"] = "spawn" os.environ["PET_NO_PYTHON"] = "1" script_args = [path("bin/test_script.sh"), f"{self.test_dir}"] with self.assertRaises(ValueError): # --no-python cannot be used with --module os.environ["PET_MODULE"] = "1" launch.main(script_args) os.environ["PET_MODULE"] = "0" launch.main(script_args) # make sure all the workers ran # each worker touches a file with its global rank as the name self.assertSetEqual( {str(i) for i in range(world_size)}, set(os.listdir(self.test_dir)) )
def test_launch_with_env_vars(self): run_id = str(uuid.uuid4().int) nnodes = 1 nproc_per_node = 4 world_size = nnodes * nproc_per_node os.environ["PET_NNODES"] = str(nnodes) os.environ["PET_NPROC_PER_NODE"] = str(nproc_per_node) os.environ["PET_RDZV_ID"] = run_id os.environ["PET_MONITOR_INTERVAL"] = "1" os.environ["PET_START_METHOD"] = "spawn" os.environ["PET_NO_PYTHON"] = "1" script_args = [path("bin/test_script.sh"), f"{self.test_dir}"] with self.assertRaises(ValueError): # --no-python cannot be used with --module os.environ["PET_MODULE"] = "1" launch.main(script_args) os.environ["PET_MODULE"] = "0" launch.main(script_args) # make sure all the workers ran # each worker touches a file with its global rank as the name self.assertSetEqual( {str(i) for i in range(world_size)}, set(os.listdir(self.test_dir)) )
import io import multiprocessing as mp import os import runpy import shutil import subprocess import sys import tempfile import uuid from contextlib import closing, redirect_stderr, redirect_stdout from unittest import mock from unittest.mock import MagicMock, Mock, patch import torch.distributed.run as launch from torch.distributed.elastic.agent.server.api import RunResult, WorkerState from torch.distributed.elastic.multiprocessing import DefaultLogsSpecs from torch.distributed.elastic.multiprocessing.errors import ChildFailedError from torch.distributed.elastic.utils import get_socket_with_port from torch.distributed.elastic.utils.distributed import get_free_port from torch.testing._internal.common_utils import ( run_tests, skip_but_pass_in_sandcastle_if, TEST_WITH_DEV_DBG_ASAN, TestCase, ) class ElasticLaunchTest(TestCase):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_fsdp_tp_integration.py
assert_local_shard_across_ranks
instantiate_parametrized_tests(TestTPFSDPIntegration) if __name__ == "__main__": run_tests()
def assert_local_shard_across_ranks(local_tensor, group, check_equal=True): gathered_tensors = [ torch.empty_like(local_tensor) for _ in range(group.size()) ] dist.all_gather(gathered_tensors, local_tensor, group=group) # on dp mesh dim local tensor does not equal tensor_to_compare = gathered_tensors[0] for tensor in gathered_tensors[1:]: if check_equal: self.assertTrue(torch.equal(tensor, tensor_to_compare)) else: self.assertFalse(torch.equal(tensor, tensor_to_compare)) dp_group = dp_mesh.get_group() # check on dp mesh dim param local tensor does not equal local_param = model.param.to_local() assert_local_shard_across_ranks(local_param, dp_group, check_equal=False) # check on dp mesh dim buffer local tensor does not equal local_buf = model.buf.to_local() assert_local_shard_across_ranks(local_buf, dp_group, check_equal=False) # wrap with fsdp sync param should sync dp mesh dim fsdp_mod = FSDP(model, device_mesh=dp_mesh, sync_module_states=True) with fsdp_mod.summon_full_params(fsdp_mod): # on dp mesh dim local param does equal after sync_module_states local_param = fsdp_mod.param.to_local() assert_local_shard_across_ranks(local_param, dp_group, check_equal=True) # on dp mesh dim local buf does equal after sync_module_states local_buf = fsdp_mod.buf.to_local() assert_local_shard_across_ranks(local_buf, dp_group, check_equal=True)
import copy import sys from collections import OrderedDict from typing import Dict, List, Optional, Tuple import torch from torch import distributed as dist from torch.distributed._tensor import ( DeviceMesh, distribute_module, DTensor, init_device_mesh, Replicate, Shard, ) from torch.distributed.fsdp.fully_sharded_data_parallel import ( CPUOffload, FullyShardedDataParallel as FSDP, ShardingStrategy, ) from torch.distributed.tensor.debug import CommDebugMode from torch.distributed.tensor.parallel import ( ColwiseParallel, parallelize_module, RowwiseParallel, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, run_tests, TEST_WITH_DEV_DBG_ASAN, ) from torch.testing._internal.distributed._tensor.common_dtensor import ( MLPModule, RMSNormPython, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_shard_utils.py
test_create_chunk_dtensor
def test_create_chunk_dtensor(self): device_mesh = self.build_device_mesh() for size in ((1,), (1, 6), (12,), (12, 6), (25,), (25, 6)): tensor = self._create_tensor(*size) tensor_chunks = torch.chunk(tensor, self.world_size, dim=0) dtensor = _create_chunk_dtensor(tensor, self.rank, device_mesh) local_tensor = dtensor.to_local() if local_tensor.numel() != 0: self.assertEqual(local_tensor, tensor_chunks[self.rank]) else: self.assertEqual(self.rank >= len(tensor_chunks), True)
import torch from torch.distributed.distributed_c10d import _get_default_group from torch.distributed.fsdp._shard_utils import ( _create_chunk_dtensor, _create_chunk_sharded_tensor, ) from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_utils import run_tests from torch.testing._internal.distributed._tensor.common_dtensor import ( DTensorTestBase, skip_if_lt_x_gpu, with_comms, ) class TestShardUtilsDistributedDTensor(DTensorTestBase):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
added
torch
test/distributed/fsdp/test_utils.py
test_apply_to_tensors
def test_apply_to_tensors(self, devices): if "cuda" in devices and ( not torch.cuda.is_available() or torch.cuda.device_count() < 1 ): raise unittest.SkipTest("Skipped due to lack of GPU") expected = 0 def get_a_tensor(): """Return a random tensor on random device.""" dev = random.choice(devices) shape = random.choice(((1), (2, 3), (4, 5, 6), (7, 8, 9, 10))) t = torch.rand(shape).to(dev) nonlocal expected expected += t.numel() return t @dataclass class SomeDataClass: some_key: str some_float: float some_tensor: List[torch.Tensor] # create a mixed bag of data. data = [1, "str"] data.append({"key1": get_a_tensor(), "key2": {1: get_a_tensor()}, "key3": 3}) data.insert(0, {"x", get_a_tensor(), get_a_tensor()}) data.append(([1], get_a_tensor(), (1), [get_a_tensor()], {1, 2})) data.append({"abc": SomeDataClass("some_key", 1.0, [get_a_tensor()])}) od = OrderedDict() od["k"] = "value" data.append(od) total = 0 def fn(t): nonlocal total total += t.numel() return t new_data = _apply_to_tensors(fn, data) self.assertEqual(total, expected) for i, v in enumerate(data): self.assertEqual(type(new_data[i]), type(v))
def test_apply_to_tensors(self, devices): if "cuda" in devices and ( not torch.cuda.is_available() or torch.cuda.device_count() < 1 ): raise unittest.SkipTest("Skipped due to lack of GPU") expected = 0 def get_a_tensor(): """Return a random tensor on random device.""" dev = random.choice(devices) shape = random.choice(((1), (2, 3), (4, 5, 6), (7, 8, 9, 10))) t = torch.rand(shape).to(dev) nonlocal expected expected += t.numel() return t @dataclass class NonFrozenDataClass: some_key: str some_float: float some_tensor: List[torch.Tensor] @dataclass(frozen=True) class FrozenDataClass: some_key: str some_float: float some_tensor: List[torch.Tensor] # create a mixed bag of data. data = [1, "str"] data.append({"key1": get_a_tensor(), "key2": {1: get_a_tensor()}, "key3": 3}) data.insert(0, {"x", get_a_tensor(), get_a_tensor()}) data.append(([1], get_a_tensor(), (1), [get_a_tensor()], {1, 2})) data.append( {"non_frozen_ds": NonFrozenDataClass("some_key", 1.0, [get_a_tensor()])} ) data.append({"frozen_ds": FrozenDataClass("some_key", 1.0, [get_a_tensor()])}) od = OrderedDict() od["k"] = "value" data.append(od) total = 0 def fn(t): nonlocal total total += t.numel() return t new_data = _apply_to_tensors(fn, data) self.assertEqual(total, expected) for i, v in enumerate(data): self.assertEqual(type(new_data[i]), type(v))
import random import sys import unittest from collections import OrderedDict from dataclasses import dataclass from enum import auto, Enum from typing import List import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp._utils import _apply_to_tensors from torch.distributed.fsdp._wrap_utils import _get_fully_sharded_module_to_states from torch.distributed.fsdp.wrap import ModuleWrapPolicy from torch.distributed.utils import _replace_by_prefix from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, subtest, TEST_WITH_DEV_DBG_ASAN, TestCase, ) class TestUtils(TestCase):
import random import sys import unittest from collections import OrderedDict from dataclasses import dataclass from typing import List import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.utils import _apply_to_tensors, _replace_by_prefix from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, subtest, TEST_WITH_DEV_DBG_ASAN, TestCase, ) class TestUtils(TestCase):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_utils.py
get_a_tensor
def get_a_tensor(): """Return a random tensor on random device.""" dev = random.choice(devices) shape = random.choice(((1), (2, 3), (4, 5, 6), (7, 8, 9, 10))) t = torch.rand(shape).to(dev) nonlocal expected expected += t.numel() return t @dataclass class SomeDataClass: some_key: str some_float: float some_tensor: List[torch.Tensor] # create a mixed bag of data. data = [1, "str"] data.append({"key1": get_a_tensor(), "key2": {1: get_a_tensor()}, "key3": 3}) data.insert(0, {"x", get_a_tensor(), get_a_tensor()}) data.append(([1], get_a_tensor(), (1), [get_a_tensor()], {1, 2})) data.append({"abc": SomeDataClass("some_key", 1.0, [get_a_tensor()])}) od = OrderedDict() od["k"] = "value" data.append(od) total = 0
def get_a_tensor(): """Return a random tensor on random device.""" dev = random.choice(devices) shape = random.choice(((1), (2, 3), (4, 5, 6), (7, 8, 9, 10))) t = torch.rand(shape).to(dev) nonlocal expected expected += t.numel() return t @dataclass class NonFrozenDataClass: some_key: str some_float: float some_tensor: List[torch.Tensor] @dataclass(frozen=True) class FrozenDataClass: some_key: str some_float: float some_tensor: List[torch.Tensor] # create a mixed bag of data. data = [1, "str"] data.append({"key1": get_a_tensor(), "key2": {1: get_a_tensor()}, "key3": 3}) data.insert(0, {"x", get_a_tensor(), get_a_tensor()}) data.append(([1], get_a_tensor(), (1), [get_a_tensor()], {1, 2})) data.append( {"non_frozen_ds": NonFrozenDataClass("some_key", 1.0, [get_a_tensor()])} ) data.append({"frozen_ds": FrozenDataClass("some_key", 1.0, [get_a_tensor()])}) od = OrderedDict() od["k"] = "value" data.append(od) total = 0
import random import sys import unittest from collections import OrderedDict from dataclasses import dataclass from enum import auto, Enum from typing import List import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp._utils import _apply_to_tensors from torch.distributed.fsdp._wrap_utils import _get_fully_sharded_module_to_states from torch.distributed.fsdp.wrap import ModuleWrapPolicy from torch.distributed.utils import _replace_by_prefix from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, subtest, TEST_WITH_DEV_DBG_ASAN, TestCase, )
import random import sys import unittest from collections import OrderedDict from dataclasses import dataclass from typing import List import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.utils import _apply_to_tensors, _replace_by_prefix from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, subtest, TEST_WITH_DEV_DBG_ASAN, TestCase, )
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_utils.py
test_get_fully_sharded_module_to_states
def test_get_fully_sharded_module_to_states(self): """ Tests the helper function ``_get_fully_sharded_module_states()`` that performs the pseudo-auto-wrapping for the non-wrapper path. NOTE: This test is hard coded against ``Model``. """ model = self.Model(TestGetSubmoduleToStates.SharedParameterMode.PARENT_CHILD) # Compute the mapping from fully sharded module to states according to # a logical module wrap policy module_classes = (nn.Sequential,) auto_wrap_policy = ModuleWrapPolicy(set(module_classes)) fully_sharded_module_to_states = _get_fully_sharded_module_to_states( model, auto_wrap_policy, set(), set() ) # Check the number of submodules with states in the mapping num_submodules_with_states = sum( isinstance(submodule, module_classes) for submodule in model.modules() ) # explicitly show how to compute the expected number if not isinstance(model, module_classes): num_submodules_with_states += 1 # always include the root assert num_submodules_with_states == 4, f"{num_submodules_with_states}" self.assertEqual( len(fully_sharded_module_to_states), num_submodules_with_states ) # Check the mapping, i.e. that the dict order follows `model.modules()` # order and that the contents are expected fully_sharded_modules = list(fully_sharded_module_to_states.keys()) expected_fully_sharded_modules = [ module for module in model.modules() if isinstance(module, nn.Sequential) or module is model ] self.assertEqual(expected_fully_sharded_modules, fully_sharded_modules) # - Root module `model` self.assertEqual(fully_sharded_modules[0], model) root_states = fully_sharded_module_to_states[fully_sharded_modules[0]] self.assertEqual(root_states.params, [model.lin.weight]) self.assertEqual(root_states.buffers, []) # - `seq1` self.assertEqual(fully_sharded_modules[1], model.seq1) seq1_states = fully_sharded_module_to_states[fully_sharded_modules[1]] self.assertEqual( seq1_states.params, [model.seq1[0].weight, model.seq1[1].weight] ) self.assertEqual(seq1_states.buffers, [model.seq1.seq1_buffer]) # - `seq2` self.assertEqual(fully_sharded_modules[2], model.seq2) seq2_states = fully_sharded_module_to_states[fully_sharded_modules[2]] self.assertEqual(seq2_states.params, [model.seq2[1].weight]) self.assertEqual(seq2_states.buffers, [model.seq2[1].seq2_1_buffer]) # - `seq2[0]` self.assertEqual(fully_sharded_modules[3], model.seq2[0]) seq2_0_states = fully_sharded_module_to_states[fully_sharded_modules[3]] self.assertEqual(seq2_0_states.params, []) # shared parameter self.assertEqual(seq2_0_states.buffers, [])
instantiate_parametrized_tests(TestUtils) if __name__ == "__main__": run_tests()
import random import sys import unittest from collections import OrderedDict from dataclasses import dataclass from enum import auto, Enum from typing import List import torch import torch.nn as nn from torch import distributed as dist from torch.distributed.fsdp._utils import _apply_to_tensors from torch.distributed.fsdp._wrap_utils import _get_fully_sharded_module_to_states from torch.distributed.fsdp.wrap import ModuleWrapPolicy from torch.distributed.utils import _replace_by_prefix from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, subtest, TEST_WITH_DEV_DBG_ASAN, TestCase, ) class TestGetSubmoduleToStates(TestCase):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
deleted
torch
test/distributed/fsdp/test_wrap.py
__init__
def __init__(self): super().__init__() self.lin = nn.Linear(10, 10, bias=False) self.bn1 = nn.BatchNorm1d(10) self.bn2 = nn.BatchNorm2d(10) self.bn3 = nn.BatchNorm3d(10) self.sync_bn = nn.SyncBatchNorm(10)
def __init__(self) -> None: super().__init__() self.lin = nn.Linear(10, 10, bias=False) self.bn1 = nn.BatchNorm1d(10) self.bn2 = nn.BatchNorm2d(10) self.bn3 = nn.BatchNorm3d(10) self.sync_bn = nn.SyncBatchNorm(10)
import functools import os import tempfile import unittest from enum import auto, Enum from typing import Callable, Union import torch import torch.nn as nn import torch.nn.functional as F from torch.distributed.fsdp.fully_sharded_data_parallel import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, ) from torch.distributed.fsdp.wrap import ( _FSDPPolicy, _or_policy, _wrap_batchnorm_individually, always_wrap_policy, enable_wrap, ModuleWrapPolicy, size_based_auto_wrap_policy, transformer_auto_wrap_policy, wrap, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _maybe_cuda, CUDAInitMode, DummyProcessGroup, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( FILE_SCHEMA, find_free_port, instantiate_parametrized_tests, parametrize, run_tests, TestCase, ) class BatchNormNet(nn.Module):
import functools import itertools import os import tempfile import unittest from enum import auto, Enum from typing import Callable, Union import torch import torch.nn as nn import torch.nn.functional as F from torch.distributed.fsdp._wrap_utils import _validate_frozen_params from torch.distributed.fsdp.fully_sharded_data_parallel import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.wrap import ( _or_policy, _Policy, _wrap_module_cls_individually, always_wrap_policy, CustomPolicy, enable_wrap, ModuleWrapPolicy, size_based_auto_wrap_policy, transformer_auto_wrap_policy, wrap, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_cuda import TEST_MULTIGPU from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _maybe_cuda, CUDAInitMode, DummyProcessGroup, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( FILE_SCHEMA, find_free_port, instantiate_parametrized_tests, parametrize, run_tests, TEST_CUDA, TestCase, ) class BatchNormNet(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified
torch
test/distributed/fsdp/test_wrap.py
__init__
def __init__(self): super().__init__() self.lin = nn.Linear(10, 10, bias=False) self.bn1 = nn.BatchNorm1d(10) self.bn2 = nn.BatchNorm2d(10) self.bn3 = nn.BatchNorm3d(10) self.sync_bn = nn.SyncBatchNorm(10)
def __init__(self) -> None: super().__init__() self.lin = nn.Linear(10, 10, bias=False) self.bn1 = nn.BatchNorm1d(10) self.bn2 = nn.BatchNorm2d(10) self.bn3 = nn.BatchNorm3d(10) self.sync_bn = nn.SyncBatchNorm(10)
import functools import os import tempfile import unittest from enum import auto, Enum from typing import Callable, Union import torch import torch.nn as nn import torch.nn.functional as F from torch.distributed.fsdp.fully_sharded_data_parallel import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, ) from torch.distributed.fsdp.wrap import ( _FSDPPolicy, _or_policy, _wrap_batchnorm_individually, always_wrap_policy, enable_wrap, ModuleWrapPolicy, size_based_auto_wrap_policy, transformer_auto_wrap_policy, wrap, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _maybe_cuda, CUDAInitMode, DummyProcessGroup, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( FILE_SCHEMA, find_free_port, instantiate_parametrized_tests, parametrize, run_tests, TestCase, ) class BatchNormNet(nn.Module):
import functools import itertools import os import tempfile import unittest from enum import auto, Enum from typing import Callable, Union import torch import torch.nn as nn import torch.nn.functional as F from torch.distributed.fsdp._wrap_utils import _validate_frozen_params from torch.distributed.fsdp.fully_sharded_data_parallel import ( BackwardPrefetch, CPUOffload, FullyShardedDataParallel as FSDP, MixedPrecision, ShardingStrategy, ) from torch.distributed.fsdp.wrap import ( _or_policy, _Policy, _wrap_module_cls_individually, always_wrap_policy, CustomPolicy, enable_wrap, ModuleWrapPolicy, size_based_auto_wrap_policy, transformer_auto_wrap_policy, wrap, ) from torch.nn import TransformerDecoderLayer, TransformerEncoderLayer from torch.nn.modules.batchnorm import _BatchNorm from torch.testing._internal.common_cuda import TEST_MULTIGPU from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.testing._internal.common_fsdp import ( _maybe_cuda, CUDAInitMode, DummyProcessGroup, FSDPInitMode, FSDPTest, TransformerWithSharedParams, ) from torch.testing._internal.common_utils import ( FILE_SCHEMA, find_free_port, instantiate_parametrized_tests, parametrize, run_tests, TEST_CUDA, TestCase, ) class BatchNormNet(nn.Module):
c263bd43e8e8502d4726643bc6fd046f0130ac0e
32f585d9346e316e554c8d9bf7548af9f62141fc
modified