Debian Codegraph @

tests/test_optimizer.py

raw
1 # Copyright 2022 The HuggingFace Team. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import pickle
16
17 import torch
18
19 from accelerate import Accelerator
20 from accelerate.test_utils import require_cpu, require_fp16, require_non_cpu
21 from accelerate.test_utils.testing import AccelerateTestCase
22
23
24 @require_cpu
25 class CPUOptimizerTester(AccelerateTestCase):
26 def test_accelerated_optimizer_pickling(self):
27 model = torch.nn.Linear(10, 10)
28 optimizer = torch.optim.SGD(model.parameters(), 0.1)
29 accelerator = Accelerator()
30 optimizer = accelerator.prepare(optimizer)
31 try:
32 pickle.loads(pickle.dumps(optimizer))
33 except Exception as e:
34 self.fail(f"Accelerated optimizer pickling failed with {e}")
35
36
37 @require_fp16
38 @require_non_cpu
39 class OptimizerTester(AccelerateTestCase):
40 def test_accelerated_optimizer_step_was_skipped(self):
41 model = torch.nn.Linear(5, 5)
42 optimizer = torch.optim.SGD(model.parameters(), 0.1)
43 accelerator = Accelerator(mixed_precision="fp16")
44 model, optimizer = accelerator.prepare(model, optimizer)
45
46 loss = model(torch.randn(2, 5, device=accelerator.device)).sum()
47 accelerator.backward(loss)
48 for p in model.parameters():
49 # Fake the gradients, as if there's no overflow
50 p.grad.fill_(0.01)
51
52 optimizer.step()
53 assert optimizer.step_was_skipped is False
54
55 loss = model(torch.randn(2, 5, device=accelerator.device)).sum()
56 accelerator.backward(loss)
57 for p in model.parameters():
58 p.grad.fill_(0.01)
59 # Manually set the gradients to be NaN, as if there's an overflow
60 p.grad[0] = torch.tensor(float("nan"))
61
62 optimizer.step()
63 assert optimizer.step_was_skipped is True
64
65 loss = model(torch.randn(2, 5, device=accelerator.device)).sum()
66 accelerator.backward(loss)
67 for p in model.parameters():
68 p.grad.fill_(0.01)
69 # Manually set the gradients to be NaN, as if there's an overflow
70 p.grad[0] = torch.tensor(float("nan"))
71
72 optimizer.step()
73 assert optimizer.step_was_skipped is True
74
75 loss = model(torch.randn(2, 5, device=accelerator.device)).sum()
76 accelerator.backward(loss)
77 for p in model.parameters():
78 # Fake the gradients, as if there's no overflow
79 p.grad.fill_(0.01)
80
81 optimizer.step()
82 assert optimizer.step_was_skipped is False