| 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 json |
| 16 |
import os |
| 17 |
import tempfile |
| 18 |
import unittest |
| 19 |
import warnings |
| 20 |
from collections import OrderedDict |
| 21 |
from typing import Optional |
| 22 |
|
| 23 |
import torch |
| 24 |
import torch.nn as nn |
| 25 |
from parameterized import parameterized |
| 26 |
from safetensors.torch import save_file |
| 27 |
|
| 28 |
from accelerate import init_empty_weights |
| 29 |
from accelerate.big_modeling import cpu_offload |
| 30 |
from accelerate.test_utils import ( |
| 31 |
require_huggingface_suite, |
| 32 |
require_multi_device, |
| 33 |
require_non_cpu, |
| 34 |
require_non_hpu, |
| 35 |
torch_device, |
| 36 |
) |
| 37 |
from accelerate.utils.modeling import ( |
| 38 |
align_module_device, |
| 39 |
check_device_map, |
| 40 |
clean_device_map, |
| 41 |
compute_module_sizes, |
| 42 |
compute_module_total_buffer_size, |
| 43 |
convert_file_size_to_int, |
| 44 |
dtype_byte_size, |
| 45 |
find_tied_parameters, |
| 46 |
get_balanced_memory, |
| 47 |
get_module_size_with_ties, |
| 48 |
get_state_dict_offloaded_model, |
| 49 |
infer_auto_device_map, |
| 50 |
load_checkpoint_in_model, |
| 51 |
load_state_dict, |
| 52 |
named_module_tensors, |
| 53 |
retie_parameters, |
| 54 |
set_module_tensor_to_device, |
| 55 |
) |
| 56 |
from accelerate.utils.other import extract_model_from_parallel |
| 57 |
|
| 58 |
|
| 59 |
torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu" |
| 60 |
|
| 61 |
|
| 62 |
class ModelForTest(nn.Module): |
| 63 |
def __init__(self): |
| 64 |
super().__init__() |
| 65 |
self.linear1 = nn.Linear(3, 4) |
| 66 |
self.batchnorm = nn.BatchNorm1d(4) |
| 67 |
self.linear2 = nn.Linear(4, 5) |
| 68 |
|
| 69 |
def forward(self, x): |
| 70 |
return self.linear2(self.batchnorm(self.linear1(x))) |
| 71 |
|
| 72 |
|
| 73 |
class NestedModelForTest(nn.Module): |
| 74 |
def __init__(self): |
| 75 |
super().__init__() |
| 76 |
self.model = ModelForTest() |
| 77 |
|
| 78 |
def forward(self, x): |
| 79 |
return self.model(x) |
| 80 |
|
| 81 |
|
| 82 |
class LinearWithNonPersistentBuffers(nn.Module): |
| 83 |
def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None: |
| 84 |
factory_kwargs = {"device": device, "dtype": dtype} |
| 85 |
super().__init__() |
| 86 |
self.in_features = in_features |
| 87 |
self.out_features = out_features |
| 88 |
self.register_buffer("weight", torch.empty((out_features, in_features), **factory_kwargs)) |
| 89 |
if bias: |
| 90 |
self.register_buffer("bias", torch.empty(out_features, **factory_kwargs), persistent=False) |
| 91 |
else: |
| 92 |
self.register_buffer("bias", None) |
| 93 |
|
| 94 |
def forward(self, input: torch.Tensor) -> torch.Tensor: |
| 95 |
return torch.nn.functional.linear(input, self.weight, self.bias) |
| 96 |
|
| 97 |
|
| 98 |
class ModelSeveralDtypes(nn.Module): |
| 99 |
def __init__(self): |
| 100 |
super().__init__() |
| 101 |
self.register_buffer("int_param", torch.randint(high=10, size=(15, 30))) |
| 102 |
self.register_parameter("float_param", torch.nn.Parameter(torch.rand(10, 5))) |
| 103 |
|
| 104 |
def forward(self, x): |
| 105 |
return x + 2 |
| 106 |
|
| 107 |
|
| 108 |
def sequential_model(num_layers): |
| 109 |
layers = OrderedDict([(f"linear{i}", nn.Linear(1000, 1000)) for i in range(1, num_layers + 1)]) |
| 110 |
return nn.Sequential(layers) |
| 111 |
|
| 112 |
|
| 113 |
class ModelingUtilsTester(unittest.TestCase): |
| 114 |
def test_dtype_byte_size(self): |
| 115 |
self.assertEqual(dtype_byte_size(torch.bool), 1 / 8) |
| 116 |
self.assertEqual(dtype_byte_size(torch.float16), 2) |
| 117 |
self.assertEqual(dtype_byte_size(torch.bfloat16), 2) |
| 118 |
self.assertEqual(dtype_byte_size(torch.float32), 4) |
| 119 |
self.assertEqual(dtype_byte_size(torch.float64), 8) |
| 120 |
# All 1-byte FP8 dtypes available in this torch should report 1 byte. |
| 121 |
# Previously only e4m3fn/e5m2 were handled; the *fnuz and e8m0fnu |
| 122 |
# variants fell through to a regex with no trailing digit and raised. |
| 123 |
for name in ( |
| 124 |
"float8_e4m3fn", |
| 125 |
"float8_e5m2", |
| 126 |
"float8_e4m3fnuz", |
| 127 |
"float8_e5m2fnuz", |
| 128 |
"float8_e8m0fnu", |
| 129 |
): |
| 130 |
if hasattr(torch, name): |
| 131 |
self.assertEqual(dtype_byte_size(getattr(torch, name)), 1, msg=name) |
| 132 |
|
| 133 |
def check_set_module_tensor_for_device(self, model, device1, device2): |
| 134 |
assert model.linear1.weight.device == torch.device(device1) |
| 135 |
|
| 136 |
with self.subTest("Access by submodule and direct name for a parameter"): |
| 137 |
set_module_tensor_to_device(model.linear1, "weight", device2) |
| 138 |
assert model.linear1.weight.device == torch.device(device2) |
| 139 |
|
| 140 |
if torch.device(device2) == torch.device("meta"): |
| 141 |
with self.assertRaises(ValueError): |
| 142 |
# We need a `value` to set the weight back on device1 |
| 143 |
set_module_tensor_to_device(model.linear1, "weight", device1) |
| 144 |
|
| 145 |
set_module_tensor_to_device(model.linear1, "weight", device1, value=torch.randn(4, 3)) |
| 146 |
else: |
| 147 |
set_module_tensor_to_device(model.linear1, "weight", device1) |
| 148 |
assert model.linear1.weight.device == torch.device(device1) |
| 149 |
|
| 150 |
with self.subTest("Access by module and full name for a parameter"): |
| 151 |
set_module_tensor_to_device(model, "linear1.weight", device2) |
| 152 |
assert model.linear1.weight.device == torch.device(device2) |
| 153 |
|
| 154 |
if torch.device(device2) == torch.device("meta"): |
| 155 |
with self.assertRaises(ValueError): |
| 156 |
# We need a `value` to set the weight back on device1 |
| 157 |
set_module_tensor_to_device(model, "linear1.weight", device1) |
| 158 |
set_module_tensor_to_device(model, "linear1.weight", device1, value=torch.randn(4, 3)) |
| 159 |
else: |
| 160 |
set_module_tensor_to_device(model, "linear1.weight", device1) |
| 161 |
assert model.linear1.weight.device == torch.device(device1) |
| 162 |
|
| 163 |
assert model.batchnorm.running_mean.device == torch.device(device1) |
| 164 |
|
| 165 |
with self.subTest("Access by submodule and direct name for a buffer"): |
| 166 |
set_module_tensor_to_device(model.batchnorm, "running_mean", device2) |
| 167 |
assert model.batchnorm.running_mean.device == torch.device(device2) |
| 168 |
|
| 169 |
if torch.device(device2) == torch.device("meta"): |
| 170 |
with self.assertRaises(ValueError): |
| 171 |
# We need a `value` to set the weight back on device1 |
| 172 |
set_module_tensor_to_device(model.batchnorm, "running_mean", device1) |
| 173 |
set_module_tensor_to_device(model.batchnorm, "running_mean", device1, value=torch.randn(4)) |
| 174 |
else: |
| 175 |
set_module_tensor_to_device(model.batchnorm, "running_mean", device1) |
| 176 |
assert model.batchnorm.running_mean.device == torch.device(device1) |
| 177 |
|
| 178 |
with self.subTest("Access by module and full name for a parameter"): |
| 179 |
set_module_tensor_to_device(model, "batchnorm.running_mean", device2) |
| 180 |
assert model.batchnorm.running_mean.device == torch.device(device2) |
| 181 |
|
| 182 |
if torch.device(device2) == torch.device("meta"): |
| 183 |
with self.assertRaises(ValueError): |
| 184 |
# We need a `value` to set the weight back on CPU |
| 185 |
set_module_tensor_to_device(model, "batchnorm.running_mean", device1) |
| 186 |
|
| 187 |
set_module_tensor_to_device(model, "batchnorm.running_mean", device1, value=torch.randn(4)) |
| 188 |
else: |
| 189 |
set_module_tensor_to_device(model, "batchnorm.running_mean", device1) |
| 190 |
assert model.batchnorm.running_mean.device == torch.device(device1) |
| 191 |
|
| 192 |
def test_set_module_tensor_to_meta_and_cpu(self): |
| 193 |
model = ModelForTest() |
| 194 |
self.check_set_module_tensor_for_device(model, "cpu", "meta") |
| 195 |
|
| 196 |
@require_non_cpu |
| 197 |
def test_set_module_tensor_to_cpu_and_gpu(self): |
| 198 |
model = ModelForTest() |
| 199 |
self.check_set_module_tensor_for_device(model, "cpu", torch_device) |
| 200 |
|
| 201 |
@require_non_cpu |
| 202 |
def test_set_module_tensor_to_meta_and_gpu(self): |
| 203 |
model = ModelForTest().to(torch_device) |
| 204 |
self.check_set_module_tensor_for_device(model, torch_device, "meta") |
| 205 |
|
| 206 |
@require_non_hpu # hpu does not support device indexing "hpu:1" |
| 207 |
@require_multi_device |
| 208 |
def test_set_module_tensor_between_gpus(self): |
| 209 |
model = ModelForTest().to(torch_device) |
| 210 |
self.check_set_module_tensor_for_device(model, torch_device, torch_device.replace("0", "1")) |
| 211 |
|
| 212 |
def test_set_module_tensor_sets_dtype(self): |
| 213 |
model = ModelForTest() |
| 214 |
set_module_tensor_to_device(model, "linear1.weight", "cpu", value=model.linear1.weight, dtype=torch.float16) |
| 215 |
assert model.linear1.weight.dtype == torch.float16 |
| 216 |
|
| 217 |
def test_set_module_tensor_checks_shape(self): |
| 218 |
model = ModelForTest() |
| 219 |
tensor = torch.zeros((2, 2)) |
| 220 |
with self.assertRaises(ValueError) as cm: |
| 221 |
set_module_tensor_to_device(model, "linear1.weight", "cpu", value=tensor) |
| 222 |
assert ( |
| 223 |
str(cm.exception) |
| 224 |
== 'Trying to set a tensor of shape torch.Size([2, 2]) in "weight" (which has shape torch.Size([4, 3])), this looks incorrect.' |
| 225 |
) |
| 226 |
|
| 227 |
def test_named_tensors(self): |
| 228 |
model = nn.BatchNorm1d(4) |
| 229 |
named_tensors = named_module_tensors(model) |
| 230 |
assert [name for name, _ in named_tensors] == [ |
| 231 |
"weight", |
| 232 |
"bias", |
| 233 |
"running_mean", |
| 234 |
"running_var", |
| 235 |
"num_batches_tracked", |
| 236 |
] |
| 237 |
|
| 238 |
named_tensors = named_module_tensors(model, include_buffers=False) |
| 239 |
assert [name for name, _ in named_tensors] == ["weight", "bias"] |
| 240 |
|
| 241 |
model = ModelForTest() |
| 242 |
named_tensors = named_module_tensors(model) |
| 243 |
assert [name for name, _ in named_tensors] == [] |
| 244 |
|
| 245 |
named_tensors = named_module_tensors(model, recurse=True) |
| 246 |
assert [name for name, _ in named_tensors] == [ |
| 247 |
"linear1.weight", |
| 248 |
"linear1.bias", |
| 249 |
"batchnorm.weight", |
| 250 |
"batchnorm.bias", |
| 251 |
"linear2.weight", |
| 252 |
"linear2.bias", |
| 253 |
"batchnorm.running_mean", |
| 254 |
"batchnorm.running_var", |
| 255 |
"batchnorm.num_batches_tracked", |
| 256 |
] |
| 257 |
|
| 258 |
named_tensors = named_module_tensors(model, include_buffers=False, recurse=True) |
| 259 |
assert [name for name, _ in named_tensors] == [ |
| 260 |
"linear1.weight", |
| 261 |
"linear1.bias", |
| 262 |
"batchnorm.weight", |
| 263 |
"batchnorm.bias", |
| 264 |
"linear2.weight", |
| 265 |
"linear2.bias", |
| 266 |
] |
| 267 |
|
| 268 |
model = LinearWithNonPersistentBuffers(10, 10) |
| 269 |
|
| 270 |
named_tensors = named_module_tensors(model, include_buffers=True, remove_non_persistent=False) |
| 271 |
assert [name for name, _ in named_tensors] == ["weight", "bias"] |
| 272 |
|
| 273 |
named_tensors = named_module_tensors(model, include_buffers=True, remove_non_persistent=True) |
| 274 |
assert [name for name, _ in named_tensors] == ["weight"] |
| 275 |
|
| 276 |
def test_find_tied_parameters(self): |
| 277 |
model = sequential_model(4) |
| 278 |
assert find_tied_parameters(model) == [] |
| 279 |
|
| 280 |
model.linear2.weight = model.linear1.weight |
| 281 |
assert find_tied_parameters(model) == [["linear1.weight", "linear2.weight"]] |
| 282 |
|
| 283 |
model.linear4.weight = model.linear1.weight |
| 284 |
assert find_tied_parameters(model) == [["linear1.weight", "linear2.weight", "linear4.weight"]] |
| 285 |
|
| 286 |
model = sequential_model(5) |
| 287 |
model.linear1.weight = model.linear4.weight |
| 288 |
model.linear2.weight = model.linear3.weight |
| 289 |
model.linear5.weight = model.linear2.weight |
| 290 |
tied_params = sorted(find_tied_parameters(model), key=lambda x: len(x)) |
| 291 |
assert tied_params == [ |
| 292 |
["linear1.weight", "linear4.weight"], |
| 293 |
["linear2.weight", "linear3.weight", "linear5.weight"], |
| 294 |
] |
| 295 |
|
| 296 |
model = nn.Sequential(OrderedDict([("block1", sequential_model(4)), ("block2", sequential_model(4))])) |
| 297 |
model.block1.linear1.weight = model.block2.linear1.weight |
| 298 |
assert find_tied_parameters(model) == [["block1.linear1.weight", "block2.linear1.weight"]] |
| 299 |
|
| 300 |
layer = nn.Linear(10, 10) |
| 301 |
model = nn.Sequential(layer, layer) |
| 302 |
tied_params = find_tied_parameters(model) |
| 303 |
assert sorted(tied_params) == [["0.bias", "1.bias"], ["0.weight", "1.weight"]] |
| 304 |
|
| 305 |
def test_retie_parameters(self): |
| 306 |
model = sequential_model(2) |
| 307 |
retie_parameters(model, [["linear1.weight", "linear2.weight"]]) |
| 308 |
assert model.linear1.weight is model.linear2.weight |
| 309 |
|
| 310 |
model = sequential_model(3) |
| 311 |
retie_parameters(model, [["linear1.weight", "linear2.weight", "linear3.weight"]]) |
| 312 |
|
| 313 |
assert model.linear1.weight is model.linear2.weight |
| 314 |
assert model.linear1.weight is model.linear3.weight |
| 315 |
|
| 316 |
model = sequential_model(5) |
| 317 |
retie_parameters( |
| 318 |
model, [["linear1.weight", "linear4.weight"], ["linear2.weight", "linear3.weight", "linear5.weight"]] |
| 319 |
) |
| 320 |
|
| 321 |
assert model.linear1.weight is model.linear4.weight |
| 322 |
assert model.linear2.weight is model.linear3.weight |
| 323 |
assert model.linear2.weight is model.linear5.weight |
| 324 |
|
| 325 |
model = nn.Sequential(OrderedDict([("block1", sequential_model(4)), ("block2", sequential_model(4))])) |
| 326 |
retie_parameters(model, [["block1.linear1.weight", "block2.linear1.weight"]]) |
| 327 |
|
| 328 |
assert model.block1.linear1.weight is model.block2.linear1.weight |
| 329 |
|
| 330 |
def test_compute_module_sizes(self): |
| 331 |
model = ModelForTest() |
| 332 |
expected_sizes = {"": 236, "linear1": 64, "linear1.weight": 48, "linear1.bias": 16} |
| 333 |
expected_sizes.update({"linear2": 100, "linear2.weight": 80, "linear2.bias": 20}) |
| 334 |
expected_sizes.update({"batchnorm": 72, "batchnorm.weight": 16, "batchnorm.bias": 16}) |
| 335 |
expected_sizes.update( |
| 336 |
{"batchnorm.running_mean": 16, "batchnorm.running_var": 16, "batchnorm.num_batches_tracked": 8} |
| 337 |
) |
| 338 |
|
| 339 |
module_sizes = compute_module_sizes(model) |
| 340 |
assert module_sizes == expected_sizes |
| 341 |
|
| 342 |
model.half() |
| 343 |
expected_sizes = {k: s // 2 for k, s in expected_sizes.items()} |
| 344 |
# This one is not converted to half. |
| 345 |
expected_sizes["batchnorm.num_batches_tracked"] = 8 |
| 346 |
# This impacts batchnorm and total |
| 347 |
expected_sizes["batchnorm"] += 4 |
| 348 |
expected_sizes[""] += 4 |
| 349 |
|
| 350 |
module_sizes = compute_module_sizes(model) |
| 351 |
assert module_sizes == expected_sizes |
| 352 |
|
| 353 |
def test_compute_module_total_buffer_size(self): |
| 354 |
model = ModelForTest() |
| 355 |
model.linear1.register_buffer("test_buffer", torch.zeros(10, 10)) |
| 356 |
model.register_buffer("test_buffer2", torch.zeros(20, 10)) |
| 357 |
|
| 358 |
buffer_size = compute_module_total_buffer_size(model) |
| 359 |
assert buffer_size == 1240 |
| 360 |
|
| 361 |
model.half() |
| 362 |
buffer_size = compute_module_total_buffer_size(model) |
| 363 |
assert buffer_size == 624 |
| 364 |
|
| 365 |
def test_check_device_map(self): |
| 366 |
model = ModelForTest() |
| 367 |
check_device_map(model, {"": 0}) |
| 368 |
with self.assertRaises(ValueError): |
| 369 |
check_device_map(model, {"linear1": 0, "linear2": 1}) |
| 370 |
|
| 371 |
check_device_map(model, {"linear1": 0, "linear2": 1, "batchnorm": 1}) |
| 372 |
|
| 373 |
def test_check_device_map_invalid_keys(self): |
| 374 |
model = ModelForTest() |
| 375 |
|
| 376 |
device_map = { |
| 377 |
"linear1": "cpu", # Valid module |
| 378 |
"batchnorm": "cpu", # Valid module |
| 379 |
"linear2": "cpu", # Valid module |
| 380 |
"invalid_module": 0, # Invalid - should trigger warning |
| 381 |
"another_invalid": 1, # Invalid - should trigger warning |
| 382 |
} |
| 383 |
|
| 384 |
# Test for the warning about invalid keys |
| 385 |
with self.assertWarns(UserWarning) as cm: |
| 386 |
check_device_map(model, device_map) |
| 387 |
|
| 388 |
warning_msg = str(cm.warning) |
| 389 |
self.assertIn("device_map keys do not match any submodules", warning_msg) |
| 390 |
self.assertIn("invalid_module", warning_msg) |
| 391 |
self.assertIn("another_invalid", warning_msg) |
| 392 |
|
| 393 |
def shard_test_model(self, model, tmp_dir): |
| 394 |
module_index = { |
| 395 |
"linear1": "checkpoint_part1.bin", |
| 396 |
"batchnorm": "checkpoint_part2.bin", |
| 397 |
"linear2": "checkpoint_part3.bin", |
| 398 |
} |
| 399 |
index = {} |
| 400 |
for name, _ in model.state_dict().items(): |
| 401 |
module = name.split(".")[0] |
| 402 |
index[name] = module_index[module] |
| 403 |
|
| 404 |
with open(os.path.join(tmp_dir, "weight_map.index.json"), "w") as f: |
| 405 |
json.dump(index, f) |
| 406 |
|
| 407 |
for module, fname in module_index.items(): |
| 408 |
state_dict = {k: v for k, v in model.state_dict().items() if k.startswith(module)} |
| 409 |
full_fname = os.path.join(tmp_dir, fname) |
| 410 |
torch.save(state_dict, full_fname) |
| 411 |
|
| 412 |
def test_load_checkpoint_in_model(self): |
| 413 |
# Check with whole checkpoint |
| 414 |
model = ModelForTest() |
| 415 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 416 |
fname = os.path.join(tmp_dir, "pt_model.bin") |
| 417 |
torch.save(model.state_dict(), fname) |
| 418 |
load_checkpoint_in_model(model, fname) |
| 419 |
|
| 420 |
# Check with sharded index |
| 421 |
model = ModelForTest() |
| 422 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 423 |
self.shard_test_model(model, tmp_dir) |
| 424 |
index_file = os.path.join(tmp_dir, "weight_map.index.json") |
| 425 |
load_checkpoint_in_model(model, index_file) |
| 426 |
|
| 427 |
# Check with sharded checkpoint |
| 428 |
model = ModelForTest() |
| 429 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 430 |
self.shard_test_model(model, tmp_dir) |
| 431 |
load_checkpoint_in_model(model, tmp_dir) |
| 432 |
|
| 433 |
@require_non_cpu |
| 434 |
def test_load_checkpoint_in_model_one_gpu(self): |
| 435 |
device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"} |
| 436 |
|
| 437 |
# Check with whole checkpoint |
| 438 |
model = ModelForTest() |
| 439 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 440 |
fname = os.path.join(tmp_dir, "pt_model.bin") |
| 441 |
torch.save(model.state_dict(), fname) |
| 442 |
load_checkpoint_in_model(model, fname, device_map=device_map) |
| 443 |
assert model.linear1.weight.device == torch.device(torch_device) |
| 444 |
assert model.batchnorm.weight.device == torch.device("cpu") |
| 445 |
assert model.linear2.weight.device == torch.device("cpu") |
| 446 |
|
| 447 |
# Check with sharded index |
| 448 |
model = ModelForTest() |
| 449 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 450 |
self.shard_test_model(model, tmp_dir) |
| 451 |
index_file = os.path.join(tmp_dir, "weight_map.index.json") |
| 452 |
load_checkpoint_in_model(model, index_file, device_map=device_map) |
| 453 |
|
| 454 |
assert model.linear1.weight.device == torch.device(torch_device) |
| 455 |
assert model.batchnorm.weight.device == torch.device("cpu") |
| 456 |
assert model.linear2.weight.device == torch.device("cpu") |
| 457 |
|
| 458 |
# Check with sharded checkpoint folder |
| 459 |
model = ModelForTest() |
| 460 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 461 |
self.shard_test_model(model, tmp_dir) |
| 462 |
load_checkpoint_in_model(model, tmp_dir, device_map=device_map) |
| 463 |
|
| 464 |
assert model.linear1.weight.device == torch.device(torch_device) |
| 465 |
assert model.batchnorm.weight.device == torch.device("cpu") |
| 466 |
assert model.linear2.weight.device == torch.device("cpu") |
| 467 |
|
| 468 |
@require_non_cpu |
| 469 |
def test_load_checkpoint_in_model_disk_offload(self): |
| 470 |
device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "cpu"} |
| 471 |
|
| 472 |
model = ModelForTest() |
| 473 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 474 |
fname = os.path.join(tmp_dir, "pt_model.bin") |
| 475 |
torch.save(model.state_dict(), fname) |
| 476 |
load_checkpoint_in_model(model, fname, device_map=device_map, offload_folder=tmp_dir) |
| 477 |
assert model.linear1.weight.device == torch.device("cpu") |
| 478 |
assert model.batchnorm.weight.device == torch.device("meta") |
| 479 |
# Buffers are not offloaded by default |
| 480 |
assert model.batchnorm.running_mean.device == torch.device("cpu") |
| 481 |
assert model.linear2.weight.device == torch.device("cpu") |
| 482 |
|
| 483 |
model = ModelForTest() |
| 484 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 485 |
fname = os.path.join(tmp_dir, "pt_model.bin") |
| 486 |
torch.save(model.state_dict(), fname) |
| 487 |
load_checkpoint_in_model(model, fname, device_map=device_map, offload_folder=tmp_dir, offload_buffers=True) |
| 488 |
assert model.linear1.weight.device == torch.device("cpu") |
| 489 |
assert model.batchnorm.weight.device == torch.device("meta") |
| 490 |
assert model.batchnorm.running_mean.device == torch.device("meta") |
| 491 |
assert model.linear2.weight.device == torch.device("cpu") |
| 492 |
|
| 493 |
@require_non_hpu # hpu does not support device indexing "hpu:1" |
| 494 |
@require_multi_device |
| 495 |
def test_load_checkpoint_in_model_two_gpu(self): |
| 496 |
device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 1} |
| 497 |
|
| 498 |
# Check with whole checkpoint |
| 499 |
model = ModelForTest() |
| 500 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 501 |
fname = os.path.join(tmp_dir, "pt_model.bin") |
| 502 |
torch.save(model.state_dict(), fname) |
| 503 |
load_checkpoint_in_model(model, fname, device_map=device_map) |
| 504 |
assert model.linear1.weight.device == torch.device(torch_device) |
| 505 |
assert model.batchnorm.weight.device == torch.device("cpu") |
| 506 |
assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1")) |
| 507 |
|
| 508 |
# Check with sharded index |
| 509 |
model = ModelForTest() |
| 510 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 511 |
self.shard_test_model(model, tmp_dir) |
| 512 |
index_file = os.path.join(tmp_dir, "weight_map.index.json") |
| 513 |
load_checkpoint_in_model(model, index_file, device_map=device_map) |
| 514 |
|
| 515 |
assert model.linear1.weight.device == torch.device(torch_device) |
| 516 |
assert model.batchnorm.weight.device == torch.device("cpu") |
| 517 |
assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1")) |
| 518 |
|
| 519 |
# Check with sharded checkpoint |
| 520 |
model = ModelForTest() |
| 521 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 522 |
self.shard_test_model(model, tmp_dir) |
| 523 |
load_checkpoint_in_model(model, tmp_dir, device_map=device_map) |
| 524 |
|
| 525 |
assert model.linear1.weight.device == torch.device(torch_device) |
| 526 |
assert model.batchnorm.weight.device == torch.device("cpu") |
| 527 |
assert model.linear2.weight.device == torch.device(torch_device.replace("0", "1")) |
| 528 |
|
| 529 |
def test_load_checkpoint_in_model_dtype(self): |
| 530 |
with tempfile.NamedTemporaryFile(suffix=".pt") as tmpfile: |
| 531 |
model = ModelSeveralDtypes() |
| 532 |
torch.save(model.state_dict(), tmpfile.name) |
| 533 |
|
| 534 |
new_model = ModelSeveralDtypes() |
| 535 |
load_checkpoint_in_model( |
| 536 |
new_model, tmpfile.name, offload_state_dict=True, dtype=torch.float16, device_map={"": "cpu"} |
| 537 |
) |
| 538 |
|
| 539 |
assert new_model.int_param.dtype == torch.int64 |
| 540 |
assert new_model.float_param.dtype == torch.float16 |
| 541 |
|
| 542 |
@parameterized.expand([(None,), ({"": "cpu"},)]) |
| 543 |
def test_load_checkpoint_in_model_unexpected_keys(self, device_map: Optional[dict]): |
| 544 |
model = ModelForTest() |
| 545 |
|
| 546 |
state_dict = model.state_dict() |
| 547 |
state_dict["foo"] = torch.rand(4, 5) |
| 548 |
with tempfile.NamedTemporaryFile(suffix=".pt") as tmpfile: |
| 549 |
torch.save(state_dict, tmpfile) |
| 550 |
|
| 551 |
model = ModelForTest() |
| 552 |
|
| 553 |
with self.assertLogs() as cm: |
| 554 |
load_checkpoint_in_model(model, tmpfile.name, device_map=device_map) |
| 555 |
|
| 556 |
self.assertTrue(any("were not used when" in out for out in cm.output)) |
| 557 |
|
| 558 |
with self.assertRaises((ValueError, RuntimeError)): |
| 559 |
load_checkpoint_in_model(model, tmpfile.name, device_map=device_map, strict=True) |
| 560 |
|
| 561 |
def test_clean_device_map(self): |
| 562 |
# Regroup everything if all is on the same device |
| 563 |
assert clean_device_map({"a": 0, "b": 0, "c": 0}) == {"": 0} |
| 564 |
# Regroups children of level 1 on the same device |
| 565 |
assert clean_device_map({"a.x": 0, "a.y": 0, "b.x": 1, "b.y": 1, "c": 1}) == {"a": 0, "b": 1, "c": 1} |
| 566 |
# Regroups children of level 2 on the same device |
| 567 |
assert clean_device_map({"a.x": 0, "a.y": 0, "b.x.0": 1, "b.x.1": 1, "b.y.0": 2, "b.y.1": 2, "c": 2}) == { |
| 568 |
"a": 0, |
| 569 |
"b.x": 1, |
| 570 |
"b.y": 2, |
| 571 |
"c": 2, |
| 572 |
} |
| 573 |
|
| 574 |
def test_infer_auto_device_map(self): |
| 575 |
model = ModelForTest() |
| 576 |
# model has size 236: linear1 64, batchnorm 72, linear2 100 |
| 577 |
try: |
| 578 |
with self.assertLogs() as cm: |
| 579 |
device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 200}) |
| 580 |
self.assertFalse(any("insufficient memory" in out for out in cm.output)) |
| 581 |
except AssertionError: |
| 582 |
# No logs exist; test passes implicitly |
| 583 |
pass |
| 584 |
|
| 585 |
# only linear1 fits on device 0 as we keep memory available for the maximum layer in case of offload |
| 586 |
assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": 1} |
| 587 |
|
| 588 |
device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 172, 2: 200}) |
| 589 |
# On device 1, we don't care about keeping size available for the max layer, so even if there is just the |
| 590 |
# size available for batchnorm + linear2, they fit here. |
| 591 |
assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": 1} |
| 592 |
|
| 593 |
model.linear1.weight = model.linear2.weight |
| 594 |
device_map = infer_auto_device_map(model, max_memory={0: 200, 1: 200}) |
| 595 |
# By tying weights, the whole model fits on device 0 |
| 596 |
assert device_map == {"": 0} |
| 597 |
|
| 598 |
# When splitting a bigger model, the split is done at the layer level |
| 599 |
model = nn.Sequential(ModelForTest(), ModelForTest(), ModelForTest()) |
| 600 |
device_map = infer_auto_device_map(model, max_memory={0: 500, 1: 500}) |
| 601 |
assert device_map == {"0": 0, "1.linear1": 0, "1.batchnorm": 0, "1.linear2": 1, "2": 1} |
| 602 |
|
| 603 |
# With no_split_module_classes, it's done at that module level |
| 604 |
model = nn.Sequential(ModelForTest(), ModelForTest(), ModelForTest()) |
| 605 |
device_map = infer_auto_device_map( |
| 606 |
model, max_memory={0: 500, 1: 500}, no_split_module_classes=["ModelForTest"] |
| 607 |
) |
| 608 |
assert device_map == {"0": 0, "1": 1, "2": 1} |
| 609 |
|
| 610 |
def test_infer_auto_device_map_with_tied_weights(self): |
| 611 |
model = nn.Sequential( |
| 612 |
OrderedDict([("layer1", ModelForTest()), ("layer2", ModelForTest()), ("layer3", ModelForTest())]) |
| 613 |
) |
| 614 |
model.layer3.linear2.weight = model.layer1.linear2.weight |
| 615 |
device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500}) |
| 616 |
expected = {"layer1": 0, "layer3.linear2": 0, "layer2": 1, "layer3.linear1": 1, "layer3.batchnorm": 1} |
| 617 |
assert device_map == expected |
| 618 |
|
| 619 |
# With three weights tied together |
| 620 |
model.layer2.linear2.weight = model.layer1.linear2.weight |
| 621 |
device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500}) |
| 622 |
expected = { |
| 623 |
"layer1": 0, |
| 624 |
"layer2.linear2": 0, |
| 625 |
"layer3.linear2": 0, |
| 626 |
"layer2.linear1": 1, |
| 627 |
"layer2.batchnorm": 1, |
| 628 |
"layer3.linear1": 1, |
| 629 |
"layer3.batchnorm": 1, |
| 630 |
} |
| 631 |
assert device_map == expected |
| 632 |
|
| 633 |
# With two groups of weights tied together |
| 634 |
model.layer2.linear1.weight = model.layer1.linear1.weight |
| 635 |
device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 500}) |
| 636 |
expected = { |
| 637 |
"layer1": 0, |
| 638 |
"layer2.linear1": 0, |
| 639 |
"layer2.linear2": 0, |
| 640 |
"layer3.linear2": 0, |
| 641 |
"layer2.batchnorm": 1, |
| 642 |
"layer3.linear1": 1, |
| 643 |
"layer3.batchnorm": 1, |
| 644 |
} |
| 645 |
assert device_map == expected |
| 646 |
|
| 647 |
# With weights ties in the same module |
| 648 |
model = nn.Sequential( |
| 649 |
OrderedDict( |
| 650 |
[ |
| 651 |
("linear1", nn.Linear(4, 4)), |
| 652 |
("linear2", nn.Linear(6, 6)), |
| 653 |
("linear3", nn.Linear(4, 4)), |
| 654 |
("linear4", nn.Linear(6, 6)), |
| 655 |
] |
| 656 |
) |
| 657 |
) |
| 658 |
model.linear3.weight = model.linear1.weight |
| 659 |
model.linear3.bias = model.linear1.bias |
| 660 |
device_map = infer_auto_device_map(model, max_memory={0: 250, 1: 400}) |
| 661 |
expected = {"linear1": 0, "linear2": 1, "linear3": 0, "linear4": 1} |
| 662 |
assert device_map == expected |
| 663 |
|
| 664 |
# With tied weights sharing a same prefix name (`compute.weight` vs `compute.weight_submodule.parameter`) |
| 665 |
class SubModule(torch.nn.Module): |
| 666 |
def __init__(self, ref_to_parameter): |
| 667 |
super().__init__() |
| 668 |
self.parameter = ref_to_parameter |
| 669 |
|
| 670 |
def forward(self, x): |
| 671 |
return self.x + torch.max(self.parameter) |
| 672 |
|
| 673 |
class LinearModuleAndSubModule(torch.nn.Linear): |
| 674 |
def __init__(self, in_features, out_features): |
| 675 |
super().__init__(in_features, out_features) |
| 676 |
self.weight_submodule = SubModule(self.weight) |
| 677 |
|
| 678 |
def forward(self, x): |
| 679 |
return torch.nn.functional.linear(self.weight_submodule(x), self.weight) |
| 680 |
|
| 681 |
class Model(torch.nn.Module): |
| 682 |
def __init__(self): |
| 683 |
super().__init__() |
| 684 |
self.compute = LinearModuleAndSubModule(3, 8) |
| 685 |
|
| 686 |
def forward(self, x): |
| 687 |
return self.compute(x) |
| 688 |
|
| 689 |
model = Model() |
| 690 |
|
| 691 |
device_memory = {0: 4, "cpu": 96000} # Low memory device, just to force splitting and trigger the error |
| 692 |
infer_auto_device_map(model, device_memory) |
| 693 |
|
| 694 |
@require_huggingface_suite |
| 695 |
def test_infer_auto_device_map_on_t0pp(self): |
| 696 |
from transformers import AutoConfig, AutoModelForSeq2SeqLM |
| 697 |
|
| 698 |
config = AutoConfig.from_pretrained("bigscience/T0pp") |
| 699 |
with init_empty_weights(): |
| 700 |
model = AutoModelForSeq2SeqLM.from_config(config) |
| 701 |
model.tie_weights() |
| 702 |
|
| 703 |
special_dtypes = {n: torch.float32 for n, _ in model.named_parameters() if "wo" in n} |
| 704 |
max_memory = {0: 10**10, 1: 10**10, "cpu": 10**10} |
| 705 |
device_map = infer_auto_device_map( |
| 706 |
model, |
| 707 |
no_split_module_classes=["T5Block"], |
| 708 |
dtype=torch.float16, |
| 709 |
max_memory=max_memory, |
| 710 |
special_dtypes=special_dtypes, |
| 711 |
) |
| 712 |
|
| 713 |
# The 3 tied weights should all be on device 0 |
| 714 |
assert device_map["shared"] == 0 |
| 715 |
assert device_map["encoder.embed_tokens"] == 0 |
| 716 |
assert device_map["decoder.embed_tokens"] == 0 |
| 717 |
|
| 718 |
def test_infer_auto_device_map_with_buffer_check(self): |
| 719 |
model = ModelForTest() |
| 720 |
model.linear1.register_buffer("test_buffer1", torch.zeros(10, 2)) |
| 721 |
model.batchnorm.register_buffer("test_buffer2", torch.zeros(10, 3)) |
| 722 |
model.linear2.register_buffer("test_buffer3", torch.zeros(10, 3)) |
| 723 |
# model has size 236(parameters) + 360(buffers): linear1 64 + 80, batchnorm 72 + 160, linear2 100 + 120 |
| 724 |
|
| 725 |
# Only linear1 (144) fits on device 0, and remaining buffers (batchnorm's 160 + linear2's 120 = 280) won't fit |
| 726 |
# device 0, because they will also be loaded to device 0 all at once when inferencing without offload_buffers |
| 727 |
# Should print a warning as intended in such case |
| 728 |
with self.assertWarns(Warning): |
| 729 |
device_map = infer_auto_device_map(model, max_memory={0: 400, "cpu": "1GB"}) |
| 730 |
assert device_map == {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"} |
| 731 |
|
| 732 |
# Only linear1 (144) fits on device 0, and remaining buffers (batchnorm's 160 + linear2's 120 = 280) won't fit |
| 733 |
# device 0, but with offload_buffers they won't be loaded to device 0 all at once, so it's ok now |
| 734 |
# Should NOT print a warning in such case |
| 735 |
with warnings.catch_warnings(record=True) as w: |
| 736 |
warnings.simplefilter("always") |
| 737 |
device_map = infer_auto_device_map(model, max_memory={0: 400, "cpu": "1GB"}, offload_buffers=True) |
| 738 |
assert len(w) == 0 |
| 739 |
assert device_map == {"linear1": 0, "batchnorm": "cpu", "linear2": "cpu"} |
| 740 |
|
| 741 |
def test_infer_auto_device_map_with_buffer_check_and_multi_devices(self): |
| 742 |
model = ModelForTest() |
| 743 |
model.linear1.register_buffer("test_buffer1", torch.zeros(10, 2)) |
| 744 |
model.batchnorm.register_buffer("test_buffer2", torch.zeros(10, 3)) |
| 745 |
model.linear2.register_buffer("test_buffer3", torch.zeros(10, 3)) |
| 746 |
model.linear3 = nn.Linear(4, 5) |
| 747 |
model.linear3.register_buffer("test_buffer4", torch.zeros(10, 2)) |
| 748 |
# model has size 336(parameters) + 440(buffers): linear1 64 + 80, batchnorm 72 + 160, linear2 100 + 120, |
| 749 |
# linear3 100 + 80 |
| 750 |
|
| 751 |
# Now we have two devices, linear1 will fit on device 0, batchnorm will fit on device 1, and the second device |
| 752 |
# can hold all remaining buffers |
| 753 |
# Should NOT print a warning in such case |
| 754 |
with warnings.catch_warnings(record=True) as w: |
| 755 |
warnings.simplefilter("always") |
| 756 |
device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 400, "cpu": "1GB"}) |
| 757 |
assert len(w) == 0 |
| 758 |
assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"} |
| 759 |
|
| 760 |
# Now we have two devices, but neither the first nor the second device can hold all remaining buffers |
| 761 |
# Should print a warning as intended in such case |
| 762 |
with self.assertWarns(Warning): |
| 763 |
device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 200, "cpu": "1GB"}) |
| 764 |
assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"} |
| 765 |
|
| 766 |
# Now we have two devices, neither can hold all the buffers, but we are using the offload_buffers=True |
| 767 |
# Should NOT print a warning in such case |
| 768 |
with warnings.catch_warnings(record=True) as w: |
| 769 |
warnings.simplefilter("always") |
| 770 |
device_map = infer_auto_device_map(model, max_memory={0: 400, 1: 200, "cpu": "1GB"}, offload_buffers=True) |
| 771 |
assert len(w) == 0 |
| 772 |
assert device_map == {"linear1": 0, "batchnorm": 1, "linear2": "cpu", "linear3": "cpu"} |
| 773 |
|
| 774 |
def test_infer_auto_device_map_with_fallback_allocation(self): |
| 775 |
# Create a model where modules cannot be allocated without fallback_allocation |
| 776 |
# Define the inner module with its layers |
| 777 |
inner_module = nn.Sequential( |
| 778 |
OrderedDict([("linear1", nn.Linear(10, 4)), ("linear2", nn.Linear(4, 4)), ("linear3", nn.Linear(4, 8))]) |
| 779 |
) |
| 780 |
|
| 781 |
# Wrap the inner module in another module |
| 782 |
model = nn.Sequential(OrderedDict([("module", inner_module)])) |
| 783 |
|
| 784 |
max_memory = {0: 256} |
| 785 |
|
| 786 |
# Without fallback_allocation |
| 787 |
with self.assertLogs() as cm: |
| 788 |
device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=False) |
| 789 |
# No module should be assigned to device 0 |
| 790 |
assert all(device != 0 for device in device_map.values()) |
| 791 |
# Check for warning about insufficient memory |
| 792 |
self.assertTrue(any("insufficient memory" in out for out in cm.output)) |
| 793 |
|
| 794 |
# With fallback_allocation |
| 795 |
try: |
| 796 |
with self.assertLogs() as cm: |
| 797 |
device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=True) |
| 798 |
self.assertFalse(any("insufficient memory" in out for out in cm.output)) |
| 799 |
except AssertionError: |
| 800 |
# No logs exist; test passes implicitly |
| 801 |
pass |
| 802 |
# At least one submodule should be assigned to device 0 |
| 803 |
assert any(device == 0 for device in device_map.values()) |
| 804 |
|
| 805 |
expected_device_map = {"module.linear1": "disk", "module.linear2": 0, "module.linear3": "disk"} |
| 806 |
assert device_map == expected_device_map |
| 807 |
|
| 808 |
def test_infer_auto_device_map_with_fallback_allocation_no_fit(self): |
| 809 |
# Create a model where even the smallest submodules cannot fit |
| 810 |
inner_module = nn.Sequential( |
| 811 |
OrderedDict( |
| 812 |
[("linear1", nn.Linear(10, 10)), ("linear2", nn.Linear(10, 10)), ("linear3", nn.Linear(10, 10))] |
| 813 |
) |
| 814 |
) |
| 815 |
|
| 816 |
# Wrap the inner module in another module |
| 817 |
model = nn.Sequential(OrderedDict([("module", inner_module)])) |
| 818 |
|
| 819 |
max_memory = {0: 30} |
| 820 |
|
| 821 |
# With fallback_allocation |
| 822 |
try: |
| 823 |
with self.assertLogs() as cm: |
| 824 |
device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=True) |
| 825 |
# No module should be assigned to device 0 |
| 826 |
assert all(device != 0 for device in device_map.values()) |
| 827 |
# Check for warning about insufficient memory |
| 828 |
self.assertTrue(any("insufficient memory" in out for out in cm.output)) |
| 829 |
except AssertionError: |
| 830 |
# No logs exist; test passes implicitly |
| 831 |
pass |
| 832 |
|
| 833 |
def test_infer_auto_device_map_with_fallback_allocation_partial_fit(self): |
| 834 |
# Create a model with deeper hierarchy |
| 835 |
class CustomModule(nn.Module): |
| 836 |
def __init__(self): |
| 837 |
super().__init__() |
| 838 |
self.submodule1 = nn.Linear(20, 20) |
| 839 |
self.submodule2 = nn.Linear(20, 20) |
| 840 |
|
| 841 |
model = nn.Sequential( |
| 842 |
OrderedDict([("module1", CustomModule()), ("module2", CustomModule()), ("module3", CustomModule())]) |
| 843 |
) |
| 844 |
|
| 845 |
max_memory = {0: 5000} |
| 846 |
|
| 847 |
# With fallback_allocation |
| 848 |
device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=True) |
| 849 |
# Check that at least some parameters are assigned to device 0 |
| 850 |
assigned_to_device_0 = [name for name, device in device_map.items() if device == 0] |
| 851 |
assert len(assigned_to_device_0) > 0 |
| 852 |
|
| 853 |
def test_infer_auto_device_map_with_fallback_allocation_tied_weights(self): |
| 854 |
# Create a model with tied weights |
| 855 |
class TiedWeightsModel(nn.Module): |
| 856 |
def __init__(self): |
| 857 |
super().__init__() |
| 858 |
self.linear1 = nn.Linear(10, 10) |
| 859 |
self.linear2 = nn.Linear(10, 10) |
| 860 |
self.linear2.weight = self.linear1.weight |
| 861 |
|
| 862 |
model = TiedWeightsModel() |
| 863 |
|
| 864 |
max_memory = {0: 600} |
| 865 |
|
| 866 |
# With fallback_allocation |
| 867 |
device_map = infer_auto_device_map(model, max_memory=max_memory, fallback_allocation=True) |
| 868 |
# Check that tied modules are assigned correctly |
| 869 |
expected_device_map = {"": 0} |
| 870 |
assert device_map == expected_device_map |
| 871 |
|
| 872 |
def test_infer_auto_device_map_with_fallback_allocation_and_buffers(self): |
| 873 |
# Create a model with buffers |
| 874 |
model = nn.Sequential( |
| 875 |
OrderedDict( |
| 876 |
[("linear1", nn.Linear(10, 10)), ("batchnorm", nn.BatchNorm1d(10)), ("linear2", nn.Linear(10, 10))] |
| 877 |
) |
| 878 |
) |
| 879 |
model.linear1.register_buffer("buffer1", torch.zeros(5)) |
| 880 |
model.batchnorm.register_buffer("buffer2", torch.zeros(5)) |
| 881 |
model.linear2.register_buffer("buffer3", torch.zeros(5)) |
| 882 |
|
| 883 |
max_memory = {0: 678} |
| 884 |
|
| 885 |
# With fallback_allocation and offload_buffers=False |
| 886 |
with self.assertWarns(Warning) as cm: |
| 887 |
device_map = infer_auto_device_map( |
| 888 |
model, max_memory=max_memory, fallback_allocation=True, offload_buffers=False |
| 889 |
) |
| 890 |
|
| 891 |
# Check that the warning contains the expected message |
| 892 |
warning_message = str(cm.warning) |
| 893 |
assert "offload_buffers" in warning_message or "Current model requires" in warning_message |
| 894 |
|
| 895 |
# Verify that the entire model is assigned to device 0 |
| 896 |
expected_device_map = {"batchnorm": 0, "linear1": "disk", "linear2": "disk"} |
| 897 |
assert device_map == expected_device_map |
| 898 |
|
| 899 |
@require_non_cpu |
| 900 |
def test_get_balanced_memory(self): |
| 901 |
model = ModelForTest() |
| 902 |
# model has size 236: linear1 64, batchnorm 72, linear2 100 |
| 903 |
max_memory = get_balanced_memory(model, max_memory={0: 200, 1: 200}) |
| 904 |
assert {0: 200, 1: 200} == max_memory |
| 905 |
|
| 906 |
# We should be able to set models on a non-contiguous sub-set of |
| 907 |
max_memory = get_balanced_memory(model, max_memory={0: 200, 2: 200}) |
| 908 |
assert {0: 200, 2: 200} == max_memory |
| 909 |
|
| 910 |
max_memory = get_balanced_memory(model, max_memory={0: 300, 1: 300}) |
| 911 |
assert {0: 215, 1: 300} == max_memory |
| 912 |
|
| 913 |
# Last device always get max memory to give more buffer and avoid accidental CPU offload |
| 914 |
max_memory = get_balanced_memory(model, max_memory={0: 300, 1: 500}) |
| 915 |
assert {0: 215, 1: 500} == max_memory |
| 916 |
|
| 917 |
# Last device always get max memory to give more buffer, even if CPU is provided |
| 918 |
max_memory = get_balanced_memory(model, max_memory={0: 300, "cpu": 1000}) |
| 919 |
assert {0: 300, "cpu": 1000} == max_memory |
| 920 |
|
| 921 |
# If we set a device to 0, it's not counted. |
| 922 |
max_memory = get_balanced_memory(model, max_memory={0: 0, 1: 300, 2: 300}) |
| 923 |
assert {0: 0, 1: 215, 2: 300} == max_memory |
| 924 |
|
| 925 |
# If we set a device to 0, it's not counted. |
| 926 |
max_memory = get_balanced_memory(model, max_memory={0: 0, "cpu": 100}) |
| 927 |
assert {0: 0, "cpu": 100} == max_memory |
| 928 |
|
| 929 |
def test_get_balanced_memory_no_split_module_classes_set(self): |
| 930 |
"""Regression test: no_split_module_classes should accept a set without raising TypeError. |
| 931 |
|
| 932 |
In accelerate<=1.5.0, passing a set caused: |
| 933 |
TypeError: unhashable type: 'set' |
| 934 |
because the code did `set(no_split_module_classes)` without first |
| 935 |
normalizing set inputs to a list. Fixed in #2345. |
| 936 |
""" |
| 937 |
model = ModelForTest() |
| 938 |
# Pass no_split_module_classes as a set (not list/tuple) |
| 939 |
# This should not raise "TypeError: unhashable type: 'set'" |
| 940 |
max_memory = get_balanced_memory( |
| 941 |
model, |
| 942 |
max_memory={0: 300, 1: 300}, |
| 943 |
no_split_module_classes={"Linear"}, |
| 944 |
) |
| 945 |
assert isinstance(max_memory, dict) |
| 946 |
|
| 947 |
# Also verify infer_auto_device_map handles set input |
| 948 |
from accelerate import infer_auto_device_map |
| 949 |
|
| 950 |
device_map = infer_auto_device_map( |
| 951 |
model, |
| 952 |
max_memory={0: 300, 1: 300}, |
| 953 |
no_split_module_classes={"Linear"}, |
| 954 |
) |
| 955 |
assert isinstance(device_map, dict) |
| 956 |
|
| 957 |
# Tests that get_module_size_with_ties returns the correct tied modules in |
| 958 |
# models with tied parameters whose parent modules share the same name prefix |
| 959 |
# See issue #3308: https://github.com/huggingface/accelerate/issues/3308 |
| 960 |
def test_get_module_size_with_ties(self): |
| 961 |
# Create a model with a ModuleList containing more than 10 elements |
| 962 |
# so the names of some layers share the same prefix, e.g. "1" and "10" |
| 963 |
num_layers = 15 |
| 964 |
model = nn.ModuleList([nn.Linear(10, 10) for _ in range(num_layers)]) |
| 965 |
# Tie .weight for all the layers |
| 966 |
for i in range(1, num_layers): |
| 967 |
model[i].weight = model[i - 1].weight |
| 968 |
# Each tied parameter group is sorted in alphabetical ordering, |
| 969 |
# mimicking the output of find_tied_parameters |
| 970 |
tied_parameters = [sorted([f"{i}.weight" for i in range(num_layers)])] |
| 971 |
# Compute module sizes |
| 972 |
weight_size, bias_size = ( |
| 973 |
model[0].weight.element_size() * model[0].weight.numel(), |
| 974 |
model[0].bias.element_size() * model[0].bias.numel(), |
| 975 |
) |
| 976 |
module_sizes = dict( |
| 977 |
**{"": num_layers * (weight_size + bias_size)}, |
| 978 |
**{f"{i}": (weight_size + bias_size) for i in range(num_layers)}, |
| 979 |
**{f"{i}.weight": weight_size for i in range(num_layers)}, |
| 980 |
**{f"{i}.bias": bias_size for i in range(num_layers)}, |
| 981 |
) |
| 982 |
# Simulate the input for get_module_size_with_ties when invoked from infer_auto_device_map |
| 983 |
# when the first module in model is being processed |
| 984 |
modules_to_treat = list(model.named_children())[1:] |
| 985 |
tied_params = tied_parameters[0][1:] |
| 986 |
module_size = weight_size + bias_size |
| 987 |
|
| 988 |
module_size_with_ties, tied_module_names, tied_modules = get_module_size_with_ties( |
| 989 |
tied_params, module_size, module_sizes, modules_to_treat |
| 990 |
) |
| 991 |
# The expected lists are ordered using as key the module names, to follow |
| 992 |
# the same order as the tied_parameters returned by find_tied_parameters |
| 993 |
expected_tied_module_names, expected_tied_modules = map( |
| 994 |
list, zip(*sorted(modules_to_treat, key=lambda x: x[0])) |
| 995 |
) |
| 996 |
|
| 997 |
assert module_size_with_ties == module_size + (num_layers - 1) * bias_size |
| 998 |
assert tied_module_names == expected_tied_module_names |
| 999 |
assert tied_modules == expected_tied_modules |
| 1000 |
|
| 1001 |
@require_non_cpu |
| 1002 |
def test_load_state_dict(self): |
| 1003 |
state_dict = {k: torch.randn(4, 5) for k in ["a", "b", "c"]} |
| 1004 |
device_maps = [{"a": "cpu", "b": 0, "c": "disk"}, {"a": 0, "b": 0, "c": "disk"}, {"a": 0, "b": 0, "c": 0}] |
| 1005 |
|
| 1006 |
for device_map in device_maps: |
| 1007 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 1008 |
checkpoint_file = os.path.join(tmp_dir, "model.safetensors") |
| 1009 |
save_file(state_dict, checkpoint_file, metadata={"format": "pt"}) |
| 1010 |
|
| 1011 |
loaded_state_dict = load_state_dict(checkpoint_file, device_map=device_map) |
| 1012 |
|
| 1013 |
for param, device in device_map.items(): |
| 1014 |
device = device if device != "disk" else "cpu" |
| 1015 |
assert loaded_state_dict[param].device == torch.device(device) |
| 1016 |
|
| 1017 |
def test_convert_file_size(self): |
| 1018 |
result = convert_file_size_to_int("0MB") |
| 1019 |
assert result == 0 |
| 1020 |
|
| 1021 |
result = convert_file_size_to_int("100MB") |
| 1022 |
assert result == (100 * (10**6)) |
| 1023 |
|
| 1024 |
result = convert_file_size_to_int("2GiB") |
| 1025 |
assert result == (2 * (2**30)) |
| 1026 |
|
| 1027 |
result = convert_file_size_to_int("512KiB") |
| 1028 |
assert result == (512 * (2**10)) |
| 1029 |
|
| 1030 |
result = convert_file_size_to_int("1.5GB") |
| 1031 |
assert result == (1.5 * (10**9)) |
| 1032 |
|
| 1033 |
result = convert_file_size_to_int("100KB") |
| 1034 |
assert result == (100 * (10**3)) |
| 1035 |
|
| 1036 |
result = convert_file_size_to_int(500) |
| 1037 |
assert result == 500 |
| 1038 |
|
| 1039 |
with self.assertRaises(ValueError): |
| 1040 |
convert_file_size_to_int("5MBB") |
| 1041 |
|
| 1042 |
with self.assertRaises(ValueError): |
| 1043 |
convert_file_size_to_int("5k0MB") |
| 1044 |
|
| 1045 |
with self.assertRaises(ValueError): |
| 1046 |
convert_file_size_to_int("-1GB") |
| 1047 |
|
| 1048 |
def test_get_state_dict_offloaded_model(self): |
| 1049 |
for model_cls in (ModelForTest, NestedModelForTest): |
| 1050 |
model = model_cls() |
| 1051 |
execution_device = torch.device(torch_device) |
| 1052 |
original_state_dict = model.state_dict() |
| 1053 |
|
| 1054 |
cpu_offload(model, execution_device=execution_device) |
| 1055 |
state_dict = get_state_dict_offloaded_model(model) |
| 1056 |
|
| 1057 |
assert original_state_dict.keys() == state_dict.keys() |
| 1058 |
for key in original_state_dict: |
| 1059 |
assert torch.equal(original_state_dict[key], state_dict[key]) |
| 1060 |
|
| 1061 |
def test_align_module_device_simple(self): |
| 1062 |
model = ModelForTest() |
| 1063 |
execution_device = torch.device(torch_device) |
| 1064 |
model_device = torch.device("cpu") |
| 1065 |
|
| 1066 |
# test default execution device |
| 1067 |
with align_module_device(model.batchnorm): |
| 1068 |
assert model.linear1.weight.device == model_device |
| 1069 |
assert model.batchnorm.weight.device == model_device |
| 1070 |
assert model.linear2.weight.device == model_device |
| 1071 |
assert model.linear1.weight.device == model_device |
| 1072 |
assert model.batchnorm.weight.device == model_device |
| 1073 |
assert model.linear2.weight.device == model_device |
| 1074 |
|
| 1075 |
# test with explicit execution device |
| 1076 |
with align_module_device(model.batchnorm, execution_device=execution_device): |
| 1077 |
assert model.linear1.weight.device == model_device |
| 1078 |
assert model.batchnorm.weight.device == execution_device |
| 1079 |
assert model.linear2.weight.device == model_device |
| 1080 |
assert model.linear1.weight.device == model_device |
| 1081 |
assert model.batchnorm.weight.device == model_device |
| 1082 |
assert model.linear2.weight.device == model_device |
| 1083 |
|
| 1084 |
def test_align_module_device_offloaded(self): |
| 1085 |
model = ModelForTest() |
| 1086 |
execution_device = torch.device(torch_device) |
| 1087 |
offload_device = torch.device("meta") |
| 1088 |
cpu_offload(model, execution_device=execution_device) |
| 1089 |
|
| 1090 |
# test default execution device |
| 1091 |
with align_module_device(model.batchnorm): |
| 1092 |
assert model.linear1.weight.device == offload_device |
| 1093 |
assert model.batchnorm.weight.device == execution_device |
| 1094 |
assert model.linear2.weight.device == offload_device |
| 1095 |
assert model.linear1.weight.device == offload_device |
| 1096 |
assert model.batchnorm.weight.device == offload_device |
| 1097 |
assert model.linear2.weight.device == offload_device |
| 1098 |
|
| 1099 |
# test with explicit execution device |
| 1100 |
with align_module_device(model.batchnorm, execution_device="cpu"): |
| 1101 |
assert model.linear1.weight.device == offload_device |
| 1102 |
assert model.batchnorm.weight.device == torch.device("cpu") |
| 1103 |
assert model.linear2.weight.device == offload_device |
| 1104 |
assert model.linear1.weight.device == offload_device |
| 1105 |
assert model.batchnorm.weight.device == offload_device |
| 1106 |
assert model.linear2.weight.device == offload_device |
| 1107 |
|
| 1108 |
def test_align_module_device_offloaded_nested(self): |
| 1109 |
model = NestedModelForTest() |
| 1110 |
execution_device = torch.device(torch_device) |
| 1111 |
align_device = torch.device("cpu") |
| 1112 |
cpu_offload(model, execution_device=execution_device) |
| 1113 |
for module in model.modules(): |
| 1114 |
with align_module_device(module, align_device): |
| 1115 |
for param in model.parameters(recurse=False): |
| 1116 |
assert param.device == align_device |
| 1117 |
|
| 1118 |
def test_extract_model_from_parallel_partial_compile(self): |
| 1119 |
"""Partial torch.compile on a submodule should not crash and should preserve the compiled wrapper.""" |
| 1120 |
model = ModelForTest() |
| 1121 |
model.linear2 = torch.compile(model.linear2) |
| 1122 |
|
| 1123 |
# Precondition: top is not compiled, only submodule is |
| 1124 |
assert not hasattr(model, "_orig_mod") |
| 1125 |
assert hasattr(model.linear2, "_orig_mod") |
| 1126 |
|
| 1127 |
# Standard extraction |
| 1128 |
extracted = extract_model_from_parallel(model) |
| 1129 |
x = torch.randn(2, 3) |
| 1130 |
torch.testing.assert_close(model(x), extracted(x)) |
| 1131 |
assert isinstance(extracted, ModelForTest) |
| 1132 |
assert hasattr(extracted.linear2, "_orig_mod") |
| 1133 |
|
| 1134 |
# Extraction with keep_torch_compile=False |
| 1135 |
extracted_no_keep = extract_model_from_parallel(model, keep_torch_compile=False) |
| 1136 |
assert hasattr(extracted_no_keep.linear2, "_orig_mod") |
| 1137 |
torch.testing.assert_close(model(x), extracted_no_keep(x)) |