Debian Codegraph @

tests/test_offload.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 os
16 import unittest
17 from tempfile import TemporaryDirectory
18
19 import torch
20 import torch.nn as nn
21
22 from accelerate.utils import (
23 OffloadedWeightsLoader,
24 extract_submodules_state_dict,
25 load_offloaded_weight,
26 offload_state_dict,
27 offload_weight,
28 )
29
30
31 class ModelForTest(nn.Module):
32 def __init__(self):
33 super().__init__()
34 self.linear1 = nn.Linear(3, 4)
35 self.batchnorm = nn.BatchNorm1d(4)
36 self.linear2 = nn.Linear(4, 5)
37
38 def forward(self, x):
39 return self.linear2(self.batchnorm(self.linear1(x)))
40
41
42 class OffloadTester(unittest.TestCase):
43 def test_offload_state_dict(self):
44 model = ModelForTest()
45 with TemporaryDirectory() as tmp_dir:
46 offload_state_dict(tmp_dir, model.state_dict())
47 index_file = os.path.join(tmp_dir, "index.json")
48 assert os.path.isfile(index_file)
49 # TODO: add tests on what is inside the index
50
51 for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]:
52 weight_file = os.path.join(tmp_dir, f"{key}.dat")
53 assert os.path.isfile(weight_file)
54 # TODO: add tests on the fact weights are properly loaded
55
56 def test_offload_weight(self):
57 dtypes = [torch.float16, torch.float32, torch.bfloat16]
58
59 for dtype in dtypes:
60 weight = torch.randn(2, 3, dtype=dtype)
61 with TemporaryDirectory() as tmp_dir:
62 index = offload_weight(weight, "weight", tmp_dir, {})
63 weight_file = os.path.join(tmp_dir, "weight.dat")
64 assert os.path.isfile(weight_file)
65 assert index == {"weight": {"shape": [2, 3], "dtype": str(dtype).split(".")[1]}}
66
67 new_weight = load_offloaded_weight(weight_file, index["weight"])
68 assert torch.equal(weight, new_weight)
69
70 def test_offload_weights_loader(self):
71 model = ModelForTest()
72 state_dict = model.state_dict()
73 cpu_part = {k: v for k, v in state_dict.items() if "linear2" not in k}
74 disk_part = {k: v for k, v in state_dict.items() if "linear2" in k}
75
76 with TemporaryDirectory() as tmp_dir:
77 offload_state_dict(tmp_dir, disk_part)
78 weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir)
79
80 # Every key is there with the right value
81 assert sorted(weight_map) == sorted(state_dict.keys())
82 for key, param in state_dict.items():
83 assert torch.allclose(param, weight_map[key])
84
85 cpu_part = {k: v for k, v in state_dict.items() if "weight" in k}
86 disk_part = {k: v for k, v in state_dict.items() if "weight" not in k}
87
88 with TemporaryDirectory() as tmp_dir:
89 offload_state_dict(tmp_dir, disk_part)
90 weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir)
91
92 # Every key is there with the right value
93 assert sorted(weight_map) == sorted(state_dict.keys())
94 for key, param in state_dict.items():
95 assert torch.allclose(param, weight_map[key])
96
97 with TemporaryDirectory() as tmp_dir:
98 offload_state_dict(tmp_dir, state_dict)
99 # Duplicates are removed
100 weight_map = OffloadedWeightsLoader(state_dict=cpu_part, save_folder=tmp_dir)
101
102 # Every key is there with the right value
103 assert sorted(weight_map) == sorted(state_dict.keys())
104 for key, param in state_dict.items():
105 assert torch.allclose(param, weight_map[key])
106
107 def test_extract_submodules_state_dict(self):
108 state_dict = {"a.1": 0, "a.10": 1, "a.2": 2}
109 extracted = extract_submodules_state_dict(state_dict, ["a.1", "a.2"])
110 assert extracted == {"a.1": 0, "a.2": 2}
111
112 state_dict = {"a.1.a": 0, "a.10.a": 1, "a.2.a": 2}
113 extracted = extract_submodules_state_dict(state_dict, ["a.1", "a.2"])
114 assert extracted == {"a.1.a": 0, "a.2.a": 2}