pytorch-lightning

Форк
0
/
test_multiprocessing_integration.py 
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

15
import pytest
16
import torch
17
import torch.nn as nn
18
from lightning.fabric import Fabric
19

20
from tests_fabric.helpers.runif import RunIf
21

22

23
class SimpleModel(nn.Module):
24
    def __init__(self):
25
        super().__init__()
26
        self.layer = nn.Linear(2, 2)
27
        self.tied_layer = nn.Linear(2, 2)
28
        self.tied_layer.weight = self.layer.weight
29
        self.register_buffer("buffer", torch.ones(3))
30

31

32
@pytest.mark.parametrize("strategy", ["ddp_spawn", pytest.param("ddp_fork", marks=RunIf(skip_windows=True))])
33
def test_memory_sharing_disabled(strategy):
34
    """Test that the multiprocessing launcher disables memory sharing on model parameters and buffers to avoid race
35
    conditions on model updates."""
36
    tensor = torch.rand(4)
37
    model = SimpleModel()
38
    assert not tensor.is_shared()
39
    assert not model.layer.weight.is_shared()
40
    assert model.layer.weight.data_ptr() == model.tied_layer.weight.data_ptr()
41

42
    fabric = Fabric(accelerator="cpu", devices=2, strategy=strategy)
43
    fabric.launch(_test_memory_sharing_disabled, tensor, model)
44

45

46
def _test_memory_sharing_disabled(fabric, tensor, model):
47
    is_spawn = fabric.strategy.launcher._start_method == "spawn"
48
    assert not is_spawn or tensor.is_shared()
49
    assert not model.layer.weight.is_shared()
50
    assert not model.tied_layer.weight.is_shared()
51
    assert not model.buffer.is_shared()
52

53
    # weights remain tied
54
    assert model.layer.weight.data_ptr() == model.tied_layer.weight.data_ptr()
55
    assert torch.equal(model.layer.weight.data, model.tied_layer.weight.data)
56
    fabric.barrier()
57

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.