pytorch-lightning
56 строк · 2.1 Кб
1# Copyright The Lightning AI team.
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
15import pytest
16import torch
17import torch.nn as nn
18from lightning.fabric import Fabric
19
20from tests_fabric.helpers.runif import RunIf
21
22
23class SimpleModel(nn.Module):
24def __init__(self):
25super().__init__()
26self.layer = nn.Linear(2, 2)
27self.tied_layer = nn.Linear(2, 2)
28self.tied_layer.weight = self.layer.weight
29self.register_buffer("buffer", torch.ones(3))
30
31
32@pytest.mark.parametrize("strategy", ["ddp_spawn", pytest.param("ddp_fork", marks=RunIf(skip_windows=True))])
33def test_memory_sharing_disabled(strategy):
34"""Test that the multiprocessing launcher disables memory sharing on model parameters and buffers to avoid race
35conditions on model updates."""
36tensor = torch.rand(4)
37model = SimpleModel()
38assert not tensor.is_shared()
39assert not model.layer.weight.is_shared()
40assert model.layer.weight.data_ptr() == model.tied_layer.weight.data_ptr()
41
42fabric = Fabric(accelerator="cpu", devices=2, strategy=strategy)
43fabric.launch(_test_memory_sharing_disabled, tensor, model)
44
45
46def _test_memory_sharing_disabled(fabric, tensor, model):
47is_spawn = fabric.strategy.launcher._start_method == "spawn"
48assert not is_spawn or tensor.is_shared()
49assert not model.layer.weight.is_shared()
50assert not model.tied_layer.weight.is_shared()
51assert not model.buffer.is_shared()
52
53# weights remain tied
54assert model.layer.weight.data_ptr() == model.tied_layer.weight.data_ptr()
55assert torch.equal(model.layer.weight.data, model.tied_layer.weight.data)
56fabric.barrier()
57