| 1 |
# Copyright 2021 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 |
import os |
| 15 |
import pickle |
| 16 |
import tempfile |
| 17 |
import unittest |
| 18 |
import warnings |
| 19 |
from collections import UserDict, namedtuple |
| 20 |
from typing import NamedTuple, Optional |
| 21 |
from unittest.mock import Mock, patch |
| 22 |
|
| 23 |
import numpy as np |
| 24 |
import pytest |
| 25 |
import torch |
| 26 |
from torch import nn |
| 27 |
|
| 28 |
from accelerate.big_modeling import cpu_offload_with_hook |
| 29 |
from accelerate.hooks import attach_align_device_hook, remove_hook_from_module |
| 30 |
from accelerate.state import PartialState |
| 31 |
from accelerate.test_utils.testing import ( |
| 32 |
require_huggingface_suite, |
| 33 |
require_non_cpu, |
| 34 |
require_non_torch_xla, |
| 35 |
require_torch_min_version, |
| 36 |
require_tpu, |
| 37 |
require_triton, |
| 38 |
torch_device, |
| 39 |
) |
| 40 |
from accelerate.test_utils.training import RegressionModel |
| 41 |
from accelerate.utils import ( |
| 42 |
CannotPadNestedTensorWarning, |
| 43 |
check_os_kernel, |
| 44 |
clear_environment, |
| 45 |
concatenate, |
| 46 |
convert_dict_to_env_variables, |
| 47 |
convert_outputs_to_fp32, |
| 48 |
convert_to_fp32, |
| 49 |
extract_model_from_parallel, |
| 50 |
find_device, |
| 51 |
has_offloaded_params, |
| 52 |
is_torch_xla_available, |
| 53 |
listify, |
| 54 |
pad_across_processes, |
| 55 |
pad_input_tensors, |
| 56 |
patch_environment, |
| 57 |
purge_accelerate_environment, |
| 58 |
recursively_apply, |
| 59 |
save, |
| 60 |
send_to_device, |
| 61 |
) |
| 62 |
from accelerate.utils.operations import is_namedtuple |
| 63 |
|
| 64 |
|
| 65 |
if is_torch_xla_available(): |
| 66 |
import torch_xla.distributed.spmd as xs |
| 67 |
import torch_xla.runtime as xr |
| 68 |
from torch_xla.experimental.spmd_fully_sharded_data_parallel import SpmdFullyShardedDataParallel as FSDPv2 |
| 69 |
|
| 70 |
ExampleNamedTuple = namedtuple("ExampleNamedTuple", "a b c") |
| 71 |
|
| 72 |
|
| 73 |
class UtilsTester(unittest.TestCase): |
| 74 |
def setUp(self): |
| 75 |
# logging requires initialized state |
| 76 |
PartialState() |
| 77 |
|
| 78 |
def test_send_to_device(self): |
| 79 |
tensor = torch.randn(5, 2) |
| 80 |
device = torch.device(f"{torch_device}:0") |
| 81 |
|
| 82 |
result1 = send_to_device(tensor, device) |
| 83 |
assert torch.equal(result1.cpu(), tensor) |
| 84 |
|
| 85 |
result2 = send_to_device((tensor, [tensor, tensor], 1), device) |
| 86 |
assert isinstance(result2, tuple) |
| 87 |
assert torch.equal(result2[0].cpu(), tensor) |
| 88 |
assert isinstance(result2[1], list) |
| 89 |
assert torch.equal(result2[1][0].cpu(), tensor) |
| 90 |
assert torch.equal(result2[1][1].cpu(), tensor) |
| 91 |
assert result2[2] == 1 |
| 92 |
|
| 93 |
result2 = send_to_device({"a": tensor, "b": [tensor, tensor], "c": 1}, device) |
| 94 |
assert isinstance(result2, dict) |
| 95 |
assert torch.equal(result2["a"].cpu(), tensor) |
| 96 |
assert isinstance(result2["b"], list) |
| 97 |
assert torch.equal(result2["b"][0].cpu(), tensor) |
| 98 |
assert torch.equal(result2["b"][1].cpu(), tensor) |
| 99 |
assert result2["c"] == 1 |
| 100 |
|
| 101 |
result3 = send_to_device(ExampleNamedTuple(a=tensor, b=[tensor, tensor], c=1), device) |
| 102 |
assert isinstance(result3, ExampleNamedTuple) |
| 103 |
assert torch.equal(result3.a.cpu(), tensor) |
| 104 |
assert isinstance(result3.b, list) |
| 105 |
assert torch.equal(result3.b[0].cpu(), tensor) |
| 106 |
assert torch.equal(result3.b[1].cpu(), tensor) |
| 107 |
assert result3.c == 1 |
| 108 |
|
| 109 |
result4 = send_to_device(UserDict({"a": tensor, "b": [tensor, tensor], "c": 1}), device) |
| 110 |
assert isinstance(result4, UserDict) |
| 111 |
assert torch.equal(result4["a"].cpu(), tensor) |
| 112 |
assert isinstance(result4["b"], list) |
| 113 |
assert torch.equal(result4["b"][0].cpu(), tensor) |
| 114 |
assert torch.equal(result4["b"][1].cpu(), tensor) |
| 115 |
assert result4["c"] == 1 |
| 116 |
|
| 117 |
def test_honor_type(self): |
| 118 |
with self.assertRaises(TypeError) as cm: |
| 119 |
_ = recursively_apply(torch.tensor, (torch.tensor(1), 1), error_on_other_type=True) |
| 120 |
assert ( |
| 121 |
str(cm.exception) |
| 122 |
== "Unsupported types (<class 'int'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed." |
| 123 |
) |
| 124 |
|
| 125 |
def test_listify(self): |
| 126 |
tensor = torch.tensor([1, 2, 3, 4, 5]) |
| 127 |
assert listify(tensor) == [1, 2, 3, 4, 5] |
| 128 |
|
| 129 |
tensor = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) |
| 130 |
assert listify(tensor) == [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] |
| 131 |
|
| 132 |
tensor = torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]) |
| 133 |
assert listify(tensor) == [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]] |
| 134 |
|
| 135 |
def test_patch_environment(self): |
| 136 |
with patch_environment(aa=1, BB=2): |
| 137 |
assert os.environ.get("AA") == "1" |
| 138 |
assert os.environ.get("BB") == "2" |
| 139 |
|
| 140 |
assert "AA" not in os.environ |
| 141 |
assert "BB" not in os.environ |
| 142 |
|
| 143 |
def test_patch_environment_key_exists(self): |
| 144 |
# check that patch_environment correctly restores pre-existing env vars |
| 145 |
with patch_environment(aa=1, BB=2): |
| 146 |
assert os.environ.get("AA") == "1" |
| 147 |
assert os.environ.get("BB") == "2" |
| 148 |
|
| 149 |
with patch_environment(Aa=10, bb="20", cC=30): |
| 150 |
assert os.environ.get("AA") == "10" |
| 151 |
assert os.environ.get("BB") == "20" |
| 152 |
assert os.environ.get("CC") == "30" |
| 153 |
|
| 154 |
assert os.environ.get("AA") == "1" |
| 155 |
assert os.environ.get("BB") == "2" |
| 156 |
assert "CC" not in os.environ |
| 157 |
|
| 158 |
assert "AA" not in os.environ |
| 159 |
assert "BB" not in os.environ |
| 160 |
assert "CC" not in os.environ |
| 161 |
|
| 162 |
def test_patch_environment_restores_on_error(self): |
| 163 |
# we need to find an upper-case envvar |
| 164 |
# because `patch_environment upper-cases all keys... |
| 165 |
key, orig_value = next(kv for kv in os.environ.items() if kv[0].isupper()) |
| 166 |
new_value = f"{orig_value}_foofoofoo" |
| 167 |
with pytest.raises(RuntimeError), patch_environment(**{key: new_value}): |
| 168 |
assert os.environ[key] == os.getenv(key) == new_value # noqa: TID251 |
| 169 |
raise RuntimeError("Oopsy daisy!") |
| 170 |
assert os.environ[key] == os.getenv(key) == orig_value # noqa: TID251 |
| 171 |
|
| 172 |
def test_clear_environment(self): |
| 173 |
key, value = os.environ.copy().popitem() |
| 174 |
with pytest.raises(RuntimeError), clear_environment(): |
| 175 |
assert key not in os.environ |
| 176 |
assert not os.getenv(key) # test the environment is actually cleared # noqa: TID251 |
| 177 |
raise RuntimeError("Oopsy daisy!") |
| 178 |
# Test values are restored |
| 179 |
assert os.getenv(key) == os.environ[key] == value # noqa: TID251 |
| 180 |
|
| 181 |
def test_can_undo_convert_outputs(self): |
| 182 |
model = RegressionModel() |
| 183 |
model._original_forward = model.forward |
| 184 |
model.forward = convert_outputs_to_fp32(model.forward) |
| 185 |
model = extract_model_from_parallel(model, keep_fp32_wrapper=False) |
| 186 |
_ = pickle.dumps(model) |
| 187 |
|
| 188 |
@require_non_cpu |
| 189 |
def test_can_undo_fp16_conversion(self): |
| 190 |
model = RegressionModel() |
| 191 |
model._original_forward = model.forward |
| 192 |
model.forward = torch.autocast(device_type=torch_device, dtype=torch.float16)(model.forward) |
| 193 |
model.forward = convert_outputs_to_fp32(model.forward) |
| 194 |
model = extract_model_from_parallel(model, keep_fp32_wrapper=False) |
| 195 |
_ = pickle.dumps(model) |
| 196 |
|
| 197 |
@require_triton |
| 198 |
@require_non_cpu |
| 199 |
def test_dynamo(self): |
| 200 |
model = RegressionModel().to(torch_device) |
| 201 |
model._original_forward = model.forward |
| 202 |
model.forward = torch.autocast(device_type=torch_device, dtype=torch.float16)(model.forward) |
| 203 |
model.forward = convert_outputs_to_fp32(model.forward) |
| 204 |
model.forward = torch.compile(model.forward, backend="inductor") |
| 205 |
inputs = torch.randn(4, 10).to(torch_device) |
| 206 |
_ = model(inputs) |
| 207 |
|
| 208 |
def test_extract_model(self): |
| 209 |
model = RegressionModel() |
| 210 |
# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU |
| 211 |
distributed_model = torch.nn.parallel.DataParallel(model) |
| 212 |
model_unwrapped = extract_model_from_parallel(distributed_model) |
| 213 |
|
| 214 |
assert model == model_unwrapped |
| 215 |
|
| 216 |
@require_tpu |
| 217 |
@require_huggingface_suite |
| 218 |
def test_extract_model_recursive_fsdpv2(self): |
| 219 |
# Specifically tests for FSDPv2 extraction |
| 220 |
# reported in https://github.com/huggingface/transformers/pull/29780 |
| 221 |
xr.use_spmd() |
| 222 |
from transformers import AutoModelForCausalLM |
| 223 |
|
| 224 |
model = AutoModelForCausalLM.from_pretrained("gpt2") |
| 225 |
orig_state_dict_keys = list(model.state_dict().keys()) |
| 226 |
num_devices = xr.global_runtime_device_count() |
| 227 |
# Set environment for FSDPv2 to be active |
| 228 |
xs.set_global_mesh(xs.Mesh(np.array(range(num_devices)), (num_devices, 1), axis_names=("fsdp", "tensor"))) |
| 229 |
|
| 230 |
def nested_wrap(model): |
| 231 |
layer = model.wte |
| 232 |
wrapped_layer = FSDPv2(layer) |
| 233 |
model.wte = wrapped_layer |
| 234 |
return model |
| 235 |
|
| 236 |
wrapped_model = nested_wrap(model) |
| 237 |
unwrapped_model = extract_model_from_parallel(wrapped_model, recursive=True) |
| 238 |
unwrapped_state_dict_keys = list(unwrapped_model.state_dict().keys()) |
| 239 |
for original_key, new_key in zip(orig_state_dict_keys, unwrapped_state_dict_keys): |
| 240 |
assert original_key == new_key, f"Keys did not align: {original_key} != {new_key}" |
| 241 |
|
| 242 |
def test_dynamo_extract_model_keep_torch_compile(self): |
| 243 |
model = RegressionModel() |
| 244 |
compiled_model = torch.compile(model) |
| 245 |
|
| 246 |
# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU |
| 247 |
distributed_model = torch.nn.parallel.DataParallel(model) |
| 248 |
distributed_compiled_model = torch.compile(distributed_model) |
| 249 |
compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model, keep_torch_compile=True) |
| 250 |
|
| 251 |
assert compiled_model._orig_mod == compiled_model_unwrapped._orig_mod |
| 252 |
|
| 253 |
def test_dynamo_extract_model_remove_torch_compile(self): |
| 254 |
model = RegressionModel() |
| 255 |
compiled_model = torch.compile(model) |
| 256 |
|
| 257 |
# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU |
| 258 |
distributed_model = torch.nn.parallel.DataParallel(model) |
| 259 |
distributed_compiled_model = torch.compile(distributed_model) |
| 260 |
compiled_model_unwrapped = extract_model_from_parallel(distributed_compiled_model, keep_torch_compile=False) |
| 261 |
|
| 262 |
assert compiled_model._orig_mod == compiled_model_unwrapped |
| 263 |
|
| 264 |
def test_find_device(self): |
| 265 |
assert find_device([1, "a", torch.tensor([1, 2, 3])]) == torch.device("cpu") |
| 266 |
assert find_device({"a": 1, "b": torch.tensor([1, 2, 3])}) == torch.device("cpu") |
| 267 |
assert find_device([1, "a"]) is None |
| 268 |
|
| 269 |
def test_check_os_kernel_no_warning_when_release_gt_min(self): |
| 270 |
# min version is 5.5 |
| 271 |
with patch("platform.uname", return_value=Mock(release="5.15.0-35-generic", system="Linux")): |
| 272 |
with warnings.catch_warnings(record=True) as w: |
| 273 |
check_os_kernel() |
| 274 |
assert len(w) == 0 |
| 275 |
|
| 276 |
def test_check_os_kernel_no_warning_when_not_linux(self): |
| 277 |
# system must be Linux |
| 278 |
with patch("platform.uname", return_value=Mock(release="5.4.0-35-generic", system="Darwin")): |
| 279 |
with warnings.catch_warnings(record=True) as w: |
| 280 |
check_os_kernel() |
| 281 |
assert len(w) == 0 |
| 282 |
|
| 283 |
def test_check_os_kernel_warning_when_release_lt_min(self): |
| 284 |
# min version is 5.5 |
| 285 |
with patch("platform.uname", return_value=Mock(release="5.4.0-35-generic", system="Linux")): |
| 286 |
with self.assertLogs() as ctx: |
| 287 |
check_os_kernel() |
| 288 |
assert len(ctx.records) == 1 |
| 289 |
assert ctx.records[0].levelname == "WARNING" |
| 290 |
assert "5.4.0" in ctx.records[0].msg |
| 291 |
assert "5.5.0" in ctx.records[0].msg |
| 292 |
|
| 293 |
@require_non_torch_xla |
| 294 |
def test_save_safetensor_shared_memory(self): |
| 295 |
class Model(nn.Module): |
| 296 |
def __init__(self): |
| 297 |
super().__init__() |
| 298 |
self.a = nn.Linear(100, 100) |
| 299 |
self.b = self.a |
| 300 |
|
| 301 |
def forward(self, x): |
| 302 |
return self.b(self.a(x)) |
| 303 |
|
| 304 |
model = Model() |
| 305 |
with tempfile.TemporaryDirectory() as tmp_dir: |
| 306 |
save_path = os.path.join(tmp_dir, "model.safetensors") |
| 307 |
with self.assertLogs(level="WARNING") as log: |
| 308 |
save(model.state_dict(), save_path, safe_serialization=True) |
| 309 |
assert len(log.records) == 1 |
| 310 |
assert "Removed shared tensor" in log.output[0] |
| 311 |
|
| 312 |
@require_torch_min_version(version="1.12") |
| 313 |
def test_pad_across_processes(self): |
| 314 |
from torch.nested import nested_tensor |
| 315 |
|
| 316 |
nt = nested_tensor([[1, 2, 3], [1], [1, 2]]) |
| 317 |
with self.assertWarns(CannotPadNestedTensorWarning): |
| 318 |
nt2 = pad_across_processes(nt) |
| 319 |
assert nt is nt2 |
| 320 |
|
| 321 |
# Basic functionality |
| 322 |
tensor = torch.randn(4, 3, 100) |
| 323 |
padded_tensor = pad_across_processes(tensor, dim=-1) |
| 324 |
assert padded_tensor.shape[-1] == 100 |
| 325 |
|
| 326 |
# dim = -4 is out of bounds |
| 327 |
padded_tensor = pad_across_processes(tensor, dim=-4) |
| 328 |
assert padded_tensor is tensor |
| 329 |
|
| 330 |
def test_slice_and_concatenate(self): |
| 331 |
# First base case: 2 processes, batch size of 1 |
| 332 |
num_processes = 2 |
| 333 |
batch_size = 1 |
| 334 |
batch = torch.rand(batch_size, 4) |
| 335 |
result = pad_input_tensors(batch, batch_size, num_processes) |
| 336 |
# We should expect there to be 2 items now |
| 337 |
assert result.shape == torch.Size([2, 4]) |
| 338 |
|
| 339 |
# Second base case: 2 processes, batch size of 3 |
| 340 |
num_processes = 2 |
| 341 |
batch_size = 3 |
| 342 |
batch = torch.rand(batch_size, 4) |
| 343 |
result = pad_input_tensors(batch, batch_size, num_processes) |
| 344 |
# We should expect there to be 4 items now |
| 345 |
assert result.shape == torch.Size([4, 4]) |
| 346 |
|
| 347 |
# Third base case: 3 processes, batch size of 4 |
| 348 |
num_processes = 3 |
| 349 |
batch_size = 4 |
| 350 |
batch = torch.rand(batch_size, 4, 4) |
| 351 |
result = pad_input_tensors(batch, batch_size, num_processes) |
| 352 |
# We should expect there to be 6 items now |
| 353 |
assert result.shape == torch.Size([6, 4, 4]) |
| 354 |
|
| 355 |
# Fourth base case: 4 processes, batch size of 3 |
| 356 |
num_processes = 4 |
| 357 |
batch_size = 3 |
| 358 |
batch = torch.rand(batch_size, 4, 4) |
| 359 |
result = pad_input_tensors(batch, batch_size, num_processes) |
| 360 |
# We should expect there to be 4 items now |
| 361 |
assert result.shape == torch.Size([4, 4, 4]) |
| 362 |
|
| 363 |
# Fifth base case: 6 processes, batch size of 4 |
| 364 |
num_processes = 6 |
| 365 |
batch_size = 4 |
| 366 |
batch = torch.rand(batch_size, 4, 4) |
| 367 |
result = pad_input_tensors(batch, batch_size, num_processes) |
| 368 |
# We should expect there to be 6 items now |
| 369 |
assert result.shape == torch.Size([6, 4, 4]) |
| 370 |
|
| 371 |
# Sixth base case: 6 processes, batch size of 1 |
| 372 |
num_processes = 6 |
| 373 |
batch_size = 1 |
| 374 |
batch = torch.rand(batch_size, 4, 4) |
| 375 |
result = pad_input_tensors(batch, batch_size, num_processes) |
| 376 |
# We should expect there to be 6 items now |
| 377 |
assert result.shape == torch.Size([6, 4, 4]) |
| 378 |
|
| 379 |
# Seventh base case: 6 processes, batch size of 2 |
| 380 |
num_processes = 6 |
| 381 |
batch_size = 2 |
| 382 |
batch = torch.rand(batch_size, 4, 4) |
| 383 |
result = pad_input_tensors(batch, batch_size, num_processes) |
| 384 |
# We should expect there to be 6 items now |
| 385 |
assert result.shape == torch.Size([6, 4, 4]) |
| 386 |
|
| 387 |
# Eighth base case: 6 processes, batch size of 61 |
| 388 |
num_processes = 6 |
| 389 |
batch_size = 61 |
| 390 |
batch = torch.rand(batch_size, 4, 4) |
| 391 |
result = pad_input_tensors(batch, batch_size, num_processes) |
| 392 |
# We should expect there to be 66 items now |
| 393 |
assert result.shape == torch.Size([66, 4, 4]) |
| 394 |
|
| 395 |
def test_send_to_device_compiles(self): |
| 396 |
compiled_send_to_device = torch.compile(send_to_device, fullgraph=True) |
| 397 |
compiled_send_to_device(torch.zeros([1], dtype=torch.bfloat16), "cpu") |
| 398 |
|
| 399 |
def test_convert_to_fp32(self): |
| 400 |
compiled_convert_to_fp32 = torch.compile(convert_to_fp32, fullgraph=True) |
| 401 |
compiled_convert_to_fp32(torch.zeros([1], dtype=torch.bfloat16)) |
| 402 |
|
| 403 |
def test_named_tuples(self): |
| 404 |
class QuantTensorBase(NamedTuple): |
| 405 |
value: torch.Tensor |
| 406 |
scale: Optional[torch.Tensor] |
| 407 |
zero_point: Optional[torch.Tensor] |
| 408 |
|
| 409 |
class Second(QuantTensorBase): |
| 410 |
pass |
| 411 |
|
| 412 |
a = QuantTensorBase(torch.tensor(1.0), None, None) |
| 413 |
b = Second(torch.tensor(1.0), None, None) |
| 414 |
|
| 415 |
point = namedtuple("Point", ["x", "y"]) |
| 416 |
p = point(11, y=22) |
| 417 |
|
| 418 |
self.assertTrue(is_namedtuple(a)) |
| 419 |
self.assertTrue(is_namedtuple(b)) |
| 420 |
self.assertTrue(is_namedtuple(p)) |
| 421 |
self.assertFalse(is_namedtuple((1, 2))) |
| 422 |
self.assertFalse(is_namedtuple("hey")) |
| 423 |
self.assertFalse(is_namedtuple(object())) |
| 424 |
|
| 425 |
def test_convert_dict_to_env_variables(self): |
| 426 |
env = {"ACCELERATE_DEBUG_MODE": "1", "BAD_ENV_NAME": "<mything", "OTHER_ENV": "2"} |
| 427 |
with self.assertLogs("accelerate.utils.environment", level="WARNING"): |
| 428 |
valid_env_items = convert_dict_to_env_variables(env) |
| 429 |
assert valid_env_items == ["ACCELERATE_DEBUG_MODE=1\n", "OTHER_ENV=2\n"] |
| 430 |
|
| 431 |
def test_has_offloaded_params(self): |
| 432 |
model = RegressionModel() |
| 433 |
assert not has_offloaded_params(model) |
| 434 |
|
| 435 |
attach_align_device_hook(model, offload=False) |
| 436 |
assert not has_offloaded_params(model) |
| 437 |
|
| 438 |
remove_hook_from_module(model) |
| 439 |
model, _ = cpu_offload_with_hook(model) |
| 440 |
assert not has_offloaded_params(model) |
| 441 |
|
| 442 |
remove_hook_from_module(model) |
| 443 |
attach_align_device_hook(model, offload=True) |
| 444 |
assert has_offloaded_params(model) |
| 445 |
|
| 446 |
def test_concatenate(self): |
| 447 |
tensor1 = torch.randn(2, 3) |
| 448 |
tensor2 = torch.randn(2, 3) |
| 449 |
result = concatenate([tensor1, tensor2]) |
| 450 |
assert result.shape == torch.Size([4, 3]) |
| 451 |
assert torch.equal(result[:2], tensor1) |
| 452 |
assert torch.equal(result[2:], tensor2) |
| 453 |
|
| 454 |
single_tensor = torch.randn(3, 4) |
| 455 |
result = concatenate([single_tensor]) |
| 456 |
assert result.shape == torch.Size([3, 4]) |
| 457 |
assert torch.equal(result, single_tensor) |
| 458 |
|
| 459 |
# NOTE: We return as-is if there's just a single batch of data, even if it's not a tensor |
| 460 |
single_value = "test_string" |
| 461 |
result = concatenate([single_value]) |
| 462 |
assert result == single_value |
| 463 |
|
| 464 |
data = [ |
| 465 |
[torch.randn(2, 3), torch.randn(2, 4)], |
| 466 |
[torch.randn(2, 3), torch.randn(2, 4)], |
| 467 |
] |
| 468 |
result = concatenate(data) |
| 469 |
assert isinstance(result, list) |
| 470 |
assert len(result) == 2 |
| 471 |
assert result[0].shape == torch.Size([4, 3]) |
| 472 |
assert result[1].shape == torch.Size([4, 4]) |
| 473 |
|
| 474 |
data = [ |
| 475 |
(torch.randn(2, 3), torch.randn(2, 4)), |
| 476 |
(torch.randn(2, 3), torch.randn(2, 4)), |
| 477 |
] |
| 478 |
result = concatenate(data) |
| 479 |
assert isinstance(result, tuple) |
| 480 |
assert len(result) == 2 |
| 481 |
assert result[0].shape == torch.Size([4, 3]) |
| 482 |
assert result[1].shape == torch.Size([4, 4]) |
| 483 |
|
| 484 |
data = [ |
| 485 |
{"a": torch.randn(2, 3), "b": torch.randn(2, 4)}, |
| 486 |
{"a": torch.randn(2, 3), "b": torch.randn(2, 4)}, |
| 487 |
] |
| 488 |
result = concatenate(data) |
| 489 |
assert isinstance(result, dict) |
| 490 |
assert "a" in result and "b" in result |
| 491 |
assert result["a"].shape == torch.Size([4, 3]) |
| 492 |
assert result["b"].shape == torch.Size([4, 4]) |
| 493 |
|
| 494 |
# NOTE: We can't merge multiple batches of non-tensor data |
| 495 |
data = [ |
| 496 |
{"a": torch.randn(2, 3), "b": torch.randn(2, 4), "c": "test_string1"}, |
| 497 |
{"a": torch.randn(2, 3), "b": torch.randn(2, 4), "c": "test_string2"}, |
| 498 |
] |
| 499 |
with self.assertRaises(TypeError): |
| 500 |
result = concatenate(data) |
| 501 |
|
| 502 |
batch1 = torch.randn(5, 10) |
| 503 |
batch2 = torch.randn(5, 10) |
| 504 |
batch3 = torch.randn(5, 10) |
| 505 |
result = concatenate([batch1, batch2, batch3]) |
| 506 |
assert result.shape == torch.Size([15, 10]) |
| 507 |
assert torch.equal(result[:5], batch1) |
| 508 |
assert torch.equal(result[5:10], batch2) |
| 509 |
assert torch.equal(result[10:], batch3) |
| 510 |
|
| 511 |
# NOTE: We can't merge misaligned batches, the torch.cat will raise a RuntimeError |
| 512 |
batch1 = torch.randn(5, 10) |
| 513 |
batch2 = torch.randn(5, 12) |
| 514 |
with self.assertRaises(RuntimeError): |
| 515 |
result = concatenate([batch1, batch2]) |
| 516 |
|
| 517 |
tensor1 = torch.randn(3, 2, 4) |
| 518 |
tensor2 = torch.randn(3, 2, 4) |
| 519 |
result = concatenate([tensor1, tensor2], dim=1) |
| 520 |
assert result.shape == torch.Size([3, 4, 4]) |
| 521 |
|
| 522 |
data = [ |
| 523 |
{"inputs": [torch.randn(2, 3), torch.randn(2, 4)], "labels": torch.randn(2, 1)}, |
| 524 |
{"inputs": [torch.randn(2, 3), torch.randn(2, 4)], "labels": torch.randn(2, 1)}, |
| 525 |
{"inputs": [torch.randn(2, 3), torch.randn(2, 4)], "labels": torch.randn(2, 1)}, |
| 526 |
] |
| 527 |
result = concatenate(data) |
| 528 |
assert isinstance(result, dict) |
| 529 |
assert isinstance(result["inputs"], list) |
| 530 |
assert result["inputs"][0].shape == torch.Size([6, 3]) |
| 531 |
assert result["inputs"][1].shape == torch.Size([6, 4]) |
| 532 |
assert result["labels"].shape == torch.Size([6, 1]) |
| 533 |
|
| 534 |
|
| 535 |
def set_dummy_accelerate_env_var(): |
| 536 |
"""Set an accelerate env var |
| 537 |
|
| 538 |
This class emulates the behavior of, for instance, transformers.TrainingArguments, which is allowed to set |
| 539 |
accelerate env vars but does not clean them up. E.g. |
| 540 |
|
| 541 |
TrainingArguments(fp16=True, output_dir="/tmp/test") |
| 542 |
|
| 543 |
leaves ACCELERATE_MIXED_PRECISION=fp16 as an env var. |
| 544 |
""" |
| 545 |
os.environ["ACCELERATE_SOME_ENV_VAR"] = "true" |
| 546 |
|
| 547 |
|
| 548 |
@purge_accelerate_environment |
| 549 |
class MyUnittest(unittest.TestCase): |
| 550 |
def test_purge_env_vars_unittest_1(self): |
| 551 |
os.environ.pop("ACCELERATE_SOME_ENV_VAR", None) |
| 552 |
set_dummy_accelerate_env_var() |
| 553 |
assert "ACCELERATE_SOME_ENV_VAR" in os.environ |
| 554 |
|
| 555 |
def test_purge_env_vars_unittest_2(self): |
| 556 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 557 |
|
| 558 |
|
| 559 |
@unittest.skipIf(False, "dummy unittest wrapper") |
| 560 |
@purge_accelerate_environment |
| 561 |
@unittest.skipUnless(True, "dummy unittest wrapper") |
| 562 |
class MyUnittestWithDecorators(unittest.TestCase): |
| 563 |
def test_purge_env_vars_unittest_with_wrapper_1(self): |
| 564 |
os.environ.pop("ACCELERATE_SOME_ENV_VAR", None) |
| 565 |
set_dummy_accelerate_env_var() |
| 566 |
assert "ACCELERATE_SOME_ENV_VAR" in os.environ |
| 567 |
|
| 568 |
def test_purge_env_vars_unittest_with_wrapper_2(self): |
| 569 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 570 |
|
| 571 |
@unittest.skipIf(False, "dummy unittest wrapper") |
| 572 |
def test_purge_env_vars_unittest_with_wrapper_3(self): |
| 573 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 574 |
|
| 575 |
@unittest.skipIf(True, "this is always skipped") |
| 576 |
def test_purge_env_vars_unittest_with_wrapper_4(self): |
| 577 |
# ensure that unittest markers still do their job |
| 578 |
assert False |
| 579 |
|
| 580 |
|
| 581 |
@purge_accelerate_environment |
| 582 |
class _BaseCls(unittest.TestCase): |
| 583 |
def test_purge_env_vars_unittest_with_inheritance_3(self): |
| 584 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 585 |
|
| 586 |
|
| 587 |
class MyUnittestWithInheritance(_BaseCls): |
| 588 |
def test_purge_env_vars_unittest_with_inheritance_1(self): |
| 589 |
os.environ.pop("ACCELERATE_SOME_ENV_VAR", None) |
| 590 |
set_dummy_accelerate_env_var() |
| 591 |
assert "ACCELERATE_SOME_ENV_VAR" in os.environ |
| 592 |
|
| 593 |
def test_purge_env_vars_unittest_with_inheritance_2(self): |
| 594 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 595 |
|
| 596 |
|
| 597 |
@purge_accelerate_environment |
| 598 |
class TestMyPytest: |
| 599 |
def test_purge_env_vars_pytest_1(self): |
| 600 |
os.environ.pop("ACCELERATE_SOME_ENV_VAR", None) |
| 601 |
set_dummy_accelerate_env_var() |
| 602 |
assert "ACCELERATE_SOME_ENV_VAR" in os.environ |
| 603 |
|
| 604 |
def test_purge_env_vars_pytest_2(self): |
| 605 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 606 |
|
| 607 |
|
| 608 |
@pytest.fixture |
| 609 |
def dummy_fixture(): |
| 610 |
pass |
| 611 |
|
| 612 |
|
| 613 |
@pytest.mark.skipif(False, reason="dummy pytest wrapper") |
| 614 |
@pytest.mark.usefixtures("dummy_fixture") |
| 615 |
@purge_accelerate_environment |
| 616 |
@pytest.mark.skipif(False, reason="dummy pytest wrapper") |
| 617 |
@pytest.mark.usefixtures("dummy_fixture") |
| 618 |
class TestPytestWithWrapper: |
| 619 |
def test_purge_env_vars_pytest_with_wrapper_1(self): |
| 620 |
os.environ.pop("ACCELERATE_SOME_ENV_VAR", None) |
| 621 |
set_dummy_accelerate_env_var() |
| 622 |
assert "ACCELERATE_SOME_ENV_VAR" in os.environ |
| 623 |
|
| 624 |
def test_purge_env_vars_pytest_with_wrapper_2(self): |
| 625 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 626 |
|
| 627 |
@pytest.mark.skipif(False, reason="dummy pytest wrapper") |
| 628 |
@pytest.mark.usefixtures("dummy_fixture") |
| 629 |
def test_purge_env_vars_pytest_with_wrapper_3(self): |
| 630 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 631 |
|
| 632 |
@pytest.mark.skipif(True, reason="this is always skipped") |
| 633 |
def test_purge_env_vars_pytest_with_wrapper_4_should_be_skipped(self): |
| 634 |
# ensure that pytest markers still do their job |
| 635 |
assert False |
| 636 |
|
| 637 |
|
| 638 |
@purge_accelerate_environment |
| 639 |
class _PytestBaseCls: |
| 640 |
def test_purge_env_vars_pytest_with_inheritance_3(self): |
| 641 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 642 |
|
| 643 |
|
| 644 |
class TestPytestWithInheritance(_PytestBaseCls): |
| 645 |
def test_purge_env_vars_pytest_with_inheritance_1(self): |
| 646 |
os.environ.pop("ACCELERATE_SOME_ENV_VAR", None) |
| 647 |
set_dummy_accelerate_env_var() |
| 648 |
assert "ACCELERATE_SOME_ENV_VAR" in os.environ |
| 649 |
|
| 650 |
def test_purge_env_vars_pytest_with_inheritance_2(self): |
| 651 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 652 |
|
| 653 |
|
| 654 |
@purge_accelerate_environment |
| 655 |
def test_purge_env_vars_standalone_1(): |
| 656 |
os.environ.pop("ACCELERATE_SOME_ENV_VAR", None) |
| 657 |
set_dummy_accelerate_env_var() |
| 658 |
assert "ACCELERATE_SOME_ENV_VAR" in os.environ |
| 659 |
|
| 660 |
|
| 661 |
def test_purge_env_vars_standalone_2(): |
| 662 |
assert "ACCELERATE_SOME_ENV_VAR" not in os.environ |
| 663 |
|
| 664 |
|
| 665 |
def test_purge_env_vars_restores_previous_values(): |
| 666 |
# Ensure that purge_accelerate_environment restores values of previous accelerate env vars and does not delete |
| 667 |
# untouched env vars. |
| 668 |
@purge_accelerate_environment |
| 669 |
def dummy_func(): |
| 670 |
os.environ["ACCELERATE_SOME_ENV_VAR"] = "456" |
| 671 |
|
| 672 |
os.environ["ACCELERATE_SOME_ENV_VAR"] = "1" |
| 673 |
os.environ["ACCELERATE_ANOTHER_ENV_VAR"] = "2" |
| 674 |
|
| 675 |
dummy_func() |
| 676 |
|
| 677 |
assert os.environ["ACCELERATE_SOME_ENV_VAR"] == "1" |
| 678 |
assert os.environ["ACCELERATE_ANOTHER_ENV_VAR"] == "2" |
| 679 |
|
| 680 |
del os.environ["ACCELERATE_SOME_ENV_VAR"] |
| 681 |
del os.environ["ACCELERATE_ANOTHER_ENV_VAR"] |