test_cpu_adam.py 3.36 KB
Newer Older
LuGY's avatar
LuGY committed
1
2
import math
import torch
3
4

from colossalai.testing import parameterize
LuGY's avatar
LuGY committed
5

6

LuGY's avatar
LuGY committed
7
8
9
10
11
12
13
14
15
16
17
18
19
def torch_adam_update(
    step,
    lr,
    beta1,
    beta2,
    eps,
    weight_decay,
    param,
    grad,
    exp_avg,
    exp_avg_sq,
    use_adamw,
):
20
21
    bias_correction1 = 1 - beta1**step
    bias_correction2 = 1 - beta2**step
LuGY's avatar
LuGY committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

    if weight_decay != 0:
        if use_adamw:
            # Perform stepweight decay
            param.mul_(1 - lr * weight_decay)
        else:
            grad = grad.add(param, alpha=weight_decay)

    # Decay the first and second moment running average coefficient
    exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
    exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
    denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(eps)

    step_size = lr / bias_correction1

    param.addcdiv_(exp_avg, denom, value=-step_size)


40
41
42
43
44
45
46
47
48
49
50
51
def assertLess(data_diff, threshold, msg):
    assert data_diff < threshold, msg


def assertTrue(condition, msg):
    assert condition, msg


@parameterize('adamw', [True, False])
@parameterize('step', [1, 2])
@parameterize('p_dtype', [torch.float, torch.half])
@parameterize('g_dtype', [torch.float, torch.half])
52
def test_cpu_adam(adamw, step, p_dtype, g_dtype):
53
54
55
56
    lr = 1e-3
    beta1, beta2 = 0.9, 0.999
    eps = 1e-8
    weight_decay = 0
57

58
59
    for i in range(1024):
        p_data = torch.rand(64, dtype=p_dtype)
LuGY's avatar
LuGY committed
60
        p_data_copy = p_data.clone().float()
61
        p_grad = torch.rand(64, dtype=g_dtype)
LuGY's avatar
LuGY committed
62
        p_grad_copy = p_grad.clone().float()
63
        exp_avg = torch.rand(p_data.shape)
LuGY's avatar
LuGY committed
64
        exp_avg_copy = exp_avg.clone()
65
        exp_avg_sq = torch.rand(p_data.shape)
LuGY's avatar
LuGY committed
66
67
        exp_avg_sq_copy = exp_avg_sq.clone()

68
69
        try:
            import cpu_adam
70
            cpu_adam_op = cpu_adam.CPUAdamOptimizer(lr, beta1, beta2, eps, weight_decay, adamw)
71
        except:
72
            raise ImportError("Import cpu adam error, please install colossal from source code")
73

74
        cpu_adam_op.step(
LuGY's avatar
LuGY committed
75
76
77
78
79
80
81
            step,
            lr,
            beta1,
            beta2,
            eps,
            weight_decay,
            True,
82
83
            p_data.view(-1),    # fp32 data
            p_grad.view(-1),    # fp32 grad
LuGY's avatar
LuGY committed
84
85
            exp_avg.view(-1),
            exp_avg_sq.view(-1),
86
            -1,
LuGY's avatar
LuGY committed
87
88
89
90
91
92
93
94
95
        )

        torch_adam_update(
            step,
            lr,
            beta1,
            beta2,
            eps,
            weight_decay,
96
97
            p_data_copy,    # fp32 data
            p_grad_copy,    # fp32 grad
LuGY's avatar
LuGY committed
98
99
            exp_avg_copy,
            exp_avg_sq_copy,
100
            adamw,
LuGY's avatar
LuGY committed
101
102
103
        )
        var = p_data_copy - p_data
        data_diff = torch.max(torch.abs(var))
104
105
        threshold = 1e-3
        assertLess(
LuGY's avatar
LuGY committed
106
107
            data_diff,
            threshold,
108
            f"p_data diff {data_diff}. failed check, step {step}, lr {lr}, eps "
109
            f"{eps} beta1 {beta1} beta2 {beta2} weight_decay {weight_decay} p_dtype {p_dtype}, g_dtype {g_dtype}",
LuGY's avatar
LuGY committed
110
111
        )
        max_grad_diff = torch.max(torch.abs(p_grad_copy - p_grad))
112
        assertTrue(max_grad_diff < threshold, f"diff {max_grad_diff}")
LuGY's avatar
LuGY committed
113
        max_exp_avg_diff = torch.max(torch.abs(exp_avg_copy - exp_avg))
114
        assertTrue(max_exp_avg_diff < threshold, f"max_exp_avg_diff {max_exp_avg_diff}")
LuGY's avatar
LuGY committed
115
        max_exp_avg_sq_diff = torch.max(torch.abs(exp_avg_sq_copy - exp_avg_sq))
116
        assertTrue(max_exp_avg_sq_diff < threshold, f"max_exp_avg_sq_diff {max_exp_avg_sq_diff}")