"tests/vscode:/vscode.git/clone" did not exist on "6160a1d6a721f7fea8b85684ebc3f22600359aa3"
test_param_op.py 2.52 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
from colossalai.gemini.paramhooks import BaseParamHookMgr
from torch import nn
import torch
import torch.nn.functional as F
import copy


class SubNet(nn.Module):

    def __init__(self, out_features) -> None:
        super().__init__()
        self.bias = nn.Parameter(torch.zeros(out_features))

    def forward(self, x, weight):
        return F.linear(x, weight, self.bias)


class Net(nn.Module):

    def __init__(self, checkpoint=False) -> None:
        super().__init__()
        self.fc1 = nn.Linear(5, 5)
        self.sub_fc = SubNet(5)
        self.fc2 = nn.Linear(5, 1)

    def forward(self, x):
        x = self.fc1(x)
        x = self.sub_fc(x, self.fc1.weight)
        x = self.fc1(x)
        x = self.fc2(x)
        return x


def net_data():
    return (torch.randn(2, 5, dtype=torch.float, device='cuda'),)


def allclose(tensor_a: torch.Tensor, tensor_b: torch.Tensor, loose=False) -> bool:
    if loose:
        return torch.allclose(tensor_a, tensor_b, atol=1e-3, rtol=1e-3)
    return torch.allclose(tensor_a, tensor_b)


def test_base_param_hook():
    torch.manual_seed(0)
    model = Net(checkpoint=True).cuda()
    model.train()
    inputs = net_data()

    def run_model(model, inputs, use_param_hook=False):
        if use_param_hook:

            class HooKWrapper:

                def __init__(self) -> None:
                    self.hook_triggered_times = 0

                def wrapper_func(self):

                    def hook(param, grad) -> torch.Tensor or None:
                        self.hook_triggered_times += 1
                        return grad

                    return hook

            hookwrapper = HooKWrapper()
            param_list = [p for p in model.parameters()]
            hook_mgr = BaseParamHookMgr(param_list)
            hook_mgr.register_backward_hooks(hookwrapper.wrapper_func())

        model.zero_grad(set_to_none=True)

        with torch.cuda.amp.autocast():
            y = model(*inputs)
            loss = y.sum()
        loss.backward()

        if use_param_hook:
            hook_mgr.remove_hooks()
            return hookwrapper.hook_triggered_times

    model_copy = copy.deepcopy(model)

    run_model(model, inputs, False)
    ret2 = run_model(model_copy, inputs, True)

    # Make sure param hook has only be fired once in case of parameter sharing
    assert ret2 == len(list(model.parameters()))

    for p, p_copy in zip(model.parameters(), model_copy.parameters()):
        assert allclose(p.grad, p_copy.grad), f"{p.grad} vs {p_copy.grad}"


if __name__ == '__main__':
    test_base_param_hook()