expert_utils.py 1.57 KB
Newer Older
Rick Ho's avatar
Rick Ho committed
1
2
3
4
5
6
7
8
9
10
11
12
import torch


def get_expert_param_size(e):
    return sum(map(lambda x: x.numel(), e.parameters()))
    

def get_expert_params(e, out):
    offset = 0
    for n, p in e.named_parameters():
        seg = out[offset:offset + p.numel()]
        offset += p.numel()
Rick Ho's avatar
Rick Ho committed
13
        seg.copy_(p.data.flatten())
Rick Ho's avatar
Rick Ho committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29


def stash_expert_params(e, params):
    if not hasattr(e, 'expert_param_stash'):
        setattr(e, 'expert_param_stash', dict())
    offset = 0
    for n, p in e.named_parameters():
        if n not in e.expert_param_stash:
            e.expert_param_stash[n] = p.data.clone()
        with torch.no_grad():
            seg = params[offset:offset + p.numel()]
            offset += p.numel()
            p.copy_(seg.reshape(p.shape))


def pop_expert_params(e):
Rick Ho's avatar
Rick Ho committed
30
31
    if not hasattr(e, 'expert_param_stash'):
        return
zms1999's avatar
zms1999 committed
32
33
    if not e.expert_param_stash:
        return
Rick Ho's avatar
Rick Ho committed
34
35
36
37
38
39
40
41
42
43
44
45
    for n, p in e.named_parameters():
        with torch.no_grad():
            p.copy_(e.expert_param_stash[n])
    e.expert_param_stash.clear()


def collect_expert_grads(e, grads):
    offset = 0
    for _, p in e.named_parameters():
        seg = grads[offset:offset + p.numel()]
        offset += p.numel()
        if p.grad is not None:
Rick Ho's avatar
Rick Ho committed
46
            seg.copy_(p.grad.flatten())
Rick Ho's avatar
Rick Ho committed
47
48
49
50
51
52
53
54
55
56
57
            p.grad = None
        else:
            seg.zero_()


def set_grads(e, grads):
    offset = 0
    for n, p in e.named_parameters():
        seg = grads[offset:offset + p.numel()]
        offset += p.numel()
        if p.grad is None:
zms1999's avatar
zms1999 committed
58
            p.grad = seg.clone().reshape(p.shape)
Rick Ho's avatar
Rick Ho committed
59
        else:
Rick Ho's avatar
Rick Ho committed
60
            p.grad += seg.reshape(p.shape)