File size: 4,263 Bytes
f0d6538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
from typing import Dict
import torch
import math
from torch.distributed.optim import ZeroRedundancyOptimizer

# -----------------------------  configurable hyper-params  -----------------------------
total_steps = 50000  # how many optimiser.step() calls you expect
warmup_steps = 200  # ≈ 1-3 % of total_steps is typical
lr_max = 3e-4  # peak LR  (your “LRmax”)
lr_min = 3e-5  # final LR (usually 0.05-0.1 × lr_max)
hold_steps = 0  # optional: keep lr_min flat for the last N steps


# ---------------------------------------------------------------------------------------

def lr_lambda(current_step: int):
    """
    0-----warm-up----------cosine----------flat--> 1   (returns *multiplicative* factor)
    """
    if current_step < warmup_steps:  # linear warm-up
        return float(current_step) / float(max(1, warmup_steps))

    progress = (current_step - warmup_steps) / float(max(1, total_steps - warmup_steps - hold_steps))
    progress = min(progress, 1.0)  # clip in case total_steps not precise

    if current_step < total_steps - hold_steps:  # cosine decay
        cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
        return cosine * (lr_max - lr_min) / lr_max + lr_min / lr_max

    return lr_min / lr_max  # flat tail


def get_lr_lambda(constant: bool):
    if constant:
        return lambda _: lr_max
    else:
        return lr_lambda


def build_optimizer(rank, world_size, module, dp_group, zero_redundant=False):
    master_params = []
    param_to_master_param = {}
    name_to_param_and_master_param = {}
    for name, param in module.named_parameters():        
        # Master gradient 
        print(f"[Rank-{rank}] GRAD_ACC, param name: {name} size: {param.shape} require_grad: {param.requires_grad}")
        #p = param.detach().clone().float().requires_grad_()
        p = torch.empty_like(param, dtype=torch.float32)
        # Allocation of parameter's so called "main_grad"
        # In TE Linear core (functors) they are just accumulated directly.
        param.main_grad = p 
        master_params.append(p)
        param_to_master_param[param] = p
        name_to_param_and_master_param[name] = (param, p)

    if world_size > 1 or zero_redundant:
        optimizer = ZeroRedundancyOptimizer(
            module.parameters(), # Still using old module's params.
            optimizer_class=torch.optim.AdamW,
            lr=lr_max,
            weight_decay=0.1,
            betas=(0.9, 0.95),
            process_group=dp_group,
        )
    else:
        optimizer = torch.optim.AdamW(master_params, lr=lr_max, betas=(0.9, 0.95), weight_decay=0.1)

    # opt_param_scheduler = get_optimizer_param_scheduler(optimizer)
    print(
        f"Allocated CUDA Memory after configure optimizer: {torch.cuda.memory_allocated() / 1000.0 / 1000 / 1000} GB")
    return optimizer, master_params, param_to_master_param, name_to_param_and_master_param

# This shall be booked mainly for optimizer to work. 
def copy_back_grads(name_to_param_and_master_param):
    with torch.no_grad():
        for name, (p_bf16, p32_as_grad) in name_to_param_and_master_param.items():
            if p_bf16.grad is None:
                p_bf16.grad = p32_as_grad.bfloat16().clone()
            else:
                p_bf16.grad.copy_(p32_as_grad.bfloat16())
            #assert p_bf16.grad.type() == 'torch.cuda.HalfTensor'
            #assert p_bf16.grad.type() == 'torch.cuda.BFloat16Tensor'

def zero_out_master_grads(name_to_param_and_master_param):
    print(f"Zeroing out accumulated master grad")
    with torch.no_grad():
        for name, (p_bf16, p32_grad) in name_to_param_and_master_param.items():
            if p_bf16.grad is not None:
                p_bf16.grad = None
            p32_grad.zero_()

def sample_check_pow2_grad(module):
    grads = []
    total_grad = 0.0
    for n, param in module.named_parameters():
        if param.main_grad is not None:
            copied = param.main_grad.clone().detach()
        else:
            copied = param.grad.clone().detach()
        total_grad += copied.pow(2).sum()
        #assert param.grad.type() == 'torch.cuda.FloatTensor'
        print(f"{n} param shape: {copied.shape} grad mean: {copied.mean()}  pow_2_sum: {copied.pow(2).sum()}")
        grads.append(copied)