1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
|
# Owner(s): ["oncall: distributed"]
import contextlib
from copy import deepcopy
from functools import partial
import torch
import torch.nn as nn
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
apply_activation_checkpointing,
checkpoint_wrapper,
CheckpointImpl,
CheckpointWrapper,
offload_wrapper,
OffloadWrapper,
)
from torch.distributed.fsdp.wrap import ModuleWrapPolicy
from torch.testing._internal.common_fsdp import get_devtype
from torch.testing._internal.common_utils import run_tests, TestCase
from torch.utils.checkpoint import checkpoint
_SAVED_PREFIX = "_saved_"
GRAD_FN_NEXT_FUNCTIONS = "next_functions"
device_type = torch.device(get_devtype())
class CheckpointWrapperTest(TestCase):
def test_load_activation_checkpointed_module(self):
lin = nn.Linear(10, 10, bias=False)
lin = checkpoint_wrapper(
lin,
checkpoint_fn=checkpoint,
# checkpoint kwargs
use_reentrant=True,
preserve_rng_state=False,
)
state_dict = deepcopy(lin.state_dict())
# Load into non-checkpoint wrapped linear module
lin_new = nn.Linear(10, 10, bias=False)
lin_new.load_state_dict(state_dict)
for p1, p2 in zip(lin.parameters(), lin_new.parameters()):
self.assertEqual(p1, p2)
self.assertTrue(torch.allclose(p1, p2))
# Load non-checkpoint wrapped module into checkpoint wrapped one
# Make params different
for p in lin_new.parameters():
with torch.no_grad():
p.add_(0.5)
state_dict = deepcopy(lin_new.state_dict())
# Verify checkpoint wrapped linear can load unwrapped linear
lin.load_state_dict(state_dict)
for p1, p2 in zip(lin.parameters(), lin_new.parameters()):
self.assertEqual(p1, p2)
def test_checkpoint_wrapper_kwarg_support(self):
class MyModel(nn.Module):
def __init__(self) -> None:
super().__init__()
self.lin = nn.Linear(10, 10)
def forward(self, a, b, c=None, d=None, **kwargs):
return (self.lin(a), self.lin(b), self.lin(c), self.lin(d))
for wrapper in [
partial(checkpoint_wrapper, checkpoint_impl=CheckpointImpl.REENTRANT),
partial(checkpoint_wrapper, checkpoint_impl=CheckpointImpl.NO_REENTRANT),
offload_wrapper,
]:
with self.subTest(wrapper=wrapper):
model = wrapper(MyModel())
if wrapper == offload_wrapper:
self.assertTrue(isinstance(model, OffloadWrapper))
else:
self.assertTrue(isinstance(model, CheckpointWrapper))
# Verify kwargs can be passed in
inp = torch.ones(4, 10, requires_grad=True)
out = model(inp, inp, c=inp, d=inp, e=inp, f=inp)
self.assertTrue(isinstance(out, tuple))
self.assertEqual(4, len(out))
# Without kwargs should have equivalent gradient requirements.
out_no_kwarg = model(inp, inp, inp, inp)
for t1, t2 in zip(out_no_kwarg, out):
self.assertEqual(t1, t2)
self.assertEqual(t1.requires_grad, t2.requires_grad)
# Test model that enforces kwarg inputs
class ModelEnforceKwarg(nn.Module):
def __init__(self) -> None:
super().__init__()
self.lin = nn.Linear(10, 10)
def forward(self, *, a=None, b=None):
return (self.lin(a), self.lin(b))
model = checkpoint_wrapper(
ModelEnforceKwarg(), checkpoint_impl=CheckpointImpl.REENTRANT
)
inp = torch.ones(4, 10, requires_grad=True)
out = model(a=inp, b=inp)
self.assertEqual(2, len(out))
def test_checkpoint_wrapper_args_kwargs(self):
"""
Tests that checkpoint_wrapper can pass down args / kwargs to configure
torch.utils.checkpoint.
"""
count = 0
@contextlib.contextmanager
def ctx_manager():
nonlocal count
count += 1
yield
def get_ctx_mgrs():
return (ctx_manager(), ctx_manager())
# kwargs test
torch_utils_checkpoint = torch.utils.checkpoint.checkpoint
m = checkpoint_wrapper(
torch.nn.Linear(1, 1),
checkpoint_fn=torch_utils_checkpoint,
use_reentrant=False,
context_fn=get_ctx_mgrs,
)
m(torch.randn(2, 1)).sum().backward()
self.assertEqual(2, count)
def test_checkpoint_wrapper_parity(self):
"""
Tests that using checkpoint_wrapper or the functional
torch.utils.checkpoint (with the same reentrant config)
results in the same maximum memory usage, i.e. they are
equivalent memory usage wise.
"""
class Model(nn.Module):
def __init__(
self,
n: int,
use_cp: bool,
use_wrapper: bool = False,
use_reentrant: bool = True,
):
super().__init__()
self.layers = nn.ModuleList()
self.n = n
self.use_cp = use_cp
self.use_wrapper = use_wrapper
self.use_reentrant = use_reentrant
wrp = partial(
checkpoint_wrapper,
checkpoint_impl=(
CheckpointImpl.REENTRANT
if use_reentrant
else CheckpointImpl.NO_REENTRANT
),
)
for i in range(self.n):
l = nn.Sequential(
nn.Linear(256, 256), nn.Linear(256, 256), nn.Linear(256, 256)
)
use_checkpoint_wrapper = self.use_wrapper
if use_checkpoint_wrapper:
l = wrp(l)
self.layers.append(l)
def forward(self, x):
for i in range(self.n):
if self.use_wrapper or not self.use_cp:
x = self.layers[i](x)
else:
x = checkpoint(
self.layers[i], x, use_reentrant=self.use_reentrant
)
return x
def test(use_checkpointing, use_wrapper, use_reentrant):
a = Model(
8,
use_checkpointing,
use_wrapper=use_wrapper,
use_reentrant=use_reentrant,
).to(device_type.type)
x = torch.randn(10000, 256, requires_grad=True).to(device_type.type)
torch.get_device_module(device_type.type).reset_peak_memory_stats()
loss = a(x).sum()
loss.backward()
return torch.get_device_module(device_type.type).max_memory_allocated()
functional_no_reentrant = test(
use_checkpointing=True, use_wrapper=False, use_reentrant=False
)
wrapper_no_reentrant = test(
use_checkpointing=False, use_wrapper=True, use_reentrant=False
)
self.assertEqual(functional_no_reentrant, wrapper_no_reentrant)
functional_reentrant = test(
use_checkpointing=True, use_wrapper=False, use_reentrant=True
)
wrapper_reentrant = test(
use_checkpointing=False, use_wrapper=True, use_reentrant=True
)
self.assertEqual(functional_reentrant, wrapper_reentrant)
def test_forward_missing_attributes(self):
lin = nn.Linear(1, 1)
m = nn.Sequential(lin, lin)
wrapped = CheckpointWrapper(m)
# Test indexing is forwarded
self.assertEqual(wrapped[0], lin)
# Test missing attributes are forwarded.
m._foo = "bar"
self.assertEqual(wrapped._foo, "bar")
def test_apply_activation_checkpointing(self):
"""
Ensures that `apply_activation_checkpointing` can be used
to swap modules for their checkpoint-wrapped counterparts given
a model.
"""
class LinearWithBatchNorm(nn.Module):
def __init__(self) -> None:
super().__init__()
self.lin = nn.Linear(10, 10)
self.bn = nn.BatchNorm1d(10)
self.nested_linear = nn.Sequential(nn.Linear(10, 10))
def forward(self, x):
return self.bn(self.nested_linear(self.lin(x)))
class MyModel(nn.Module):
def __init__(self) -> None:
super().__init__()
self.seq = nn.Sequential(
LinearWithBatchNorm(), LinearWithBatchNorm(), LinearWithBatchNorm()
)
def forward(self, x):
return self.seq(x)
def check_fn(l):
return isinstance(l, nn.Linear)
n_linear = None
for i, wrapper in enumerate(
[
partial(checkpoint_wrapper, checkpoint_impl=CheckpointImpl.REENTRANT),
partial(
checkpoint_wrapper, checkpoint_impl=CheckpointImpl.NO_REENTRANT
),
offload_wrapper,
]
):
model = MyModel()
if n_linear is None:
n_linear = sum(
1 if isinstance(x, nn.Linear) else 0 for x in model.modules()
)
with self.subTest(wrapper=wrapper):
if i != 0:
apply_activation_checkpointing(
model, checkpoint_wrapper_fn=wrapper, check_fn=check_fn
)
else:
apply_activation_checkpointing(
model,
checkpoint_wrapper_fn=wrapper,
auto_wrap_policy=ModuleWrapPolicy({nn.Linear}),
)
n_linear_wrapped = sum(
1 if isinstance(x, nn.Linear) else 0 for x in model.modules()
)
n_checkpointed = sum(
1 if isinstance(x, (CheckpointWrapper, OffloadWrapper)) else 0
for x in model.modules()
)
self.assertEqual(n_checkpointed, n_linear_wrapped)
self.assertEqual(n_linear, n_linear_wrapped)
for j in range(3):
self.assertTrue(
isinstance(
model.seq[j].lin, (CheckpointWrapper, OffloadWrapper)
)
)
self.assertTrue(
isinstance(
model.seq[j].nested_linear[0],
(CheckpointWrapper, OffloadWrapper),
)
)
inp = torch.randn(4, 10, requires_grad=True)
for i in range(6):
# Kwarg input
loss = model(x=inp).sum()
self.assertTrue(loss.requires_grad)
loss.backward()
# ensure checkpointed part of model has gradients
for j in range(3):
weight_lin = model.seq[j].lin._checkpoint_wrapped_module.weight
bias_lin = model.seq[j].lin._checkpoint_wrapped_module.bias
weight_nested_lin = (
model.seq[j]
.nested_linear[0]
._checkpoint_wrapped_module.weight
)
bias_nested_lin = (
model.seq[j]
.nested_linear[0]
._checkpoint_wrapped_module.bias
)
for param in [
weight_lin,
bias_lin,
weight_nested_lin,
bias_nested_lin,
]:
self.assertTrue(param.requires_grad)
self.assertFalse(param.grad is None)
def test_fqn(self):
lin = nn.Linear(10, 10, bias=False)
lin = checkpoint_wrapper(lin)
state_dict = lin.state_dict()
for fqn, _ in lin.named_parameters():
self.assertTrue(fqn in state_dict, msg=f"{fqn} not in state_dict.")
def test_checkpoint_wrapper_cpu_offload(self):
model = nn.Sequential(
nn.Linear(10, 10),
nn.Linear(10, 10),
nn.Linear(10, 10),
).to(device_type.type)
# Patch saved_tensor_hooks to make the unpack keep the tensor on CPU for
# testing, otherwise the tensor access during the DFS will cause orig
# unpack to run, transferring the tensor back to GPU.
def patched_init(saved_tensor_hook_obj, pack_hook, _):
saved_tensor_hook_obj.pack_hook = pack_hook
def testing_cpu_offload_unpack_hook(packed):
_, tensor = packed
return tensor
saved_tensor_hook_obj.unpack_hook = testing_cpu_offload_unpack_hook
orig_init = torch.autograd.graph.saved_tensors_hooks.__init__
torch.autograd.graph.saved_tensors_hooks.__init__ = patched_init
model = offload_wrapper(model)
inp = torch.randn(3, 10, device=device_type.type)
loss = model(inp).sum()
# All autograd saved tensors should be offloaded to CPU.
offload_verified = False
def dfs(grad_fn):
for e in dir(grad_fn):
if not e.startswith(_SAVED_PREFIX):
continue
saved = getattr(grad_fn, e)
if isinstance(saved, torch.Tensor):
self.assertEqual(torch.device("cpu"), saved.device)
nonlocal offload_verified
offload_verified = True
if hasattr(grad_fn, GRAD_FN_NEXT_FUNCTIONS):
for next_grad_fn, _ in grad_fn.next_functions:
dfs(next_grad_fn)
dfs(loss.grad_fn)
self.assertTrue(offload_verified)
torch.autograd.graph.saved_tensors_hooks.__init__ = orig_init
if __name__ == "__main__":
run_tests()
|