expert_utils.py 1.52 KB
Newer Older
Rick Ho's avatar
Rick Ho committed
1
2
3
4
5
6
7
8
import torch


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

def get_expert_params(e, out):
Rick Ho's avatar
Rick Ho committed
9
    print('gep to {}'.format(out))
Rick Ho's avatar
Rick Ho committed
10
11
12
13
    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
14
        seg.copy_(p.data.flatten())
Rick Ho's avatar
Rick Ho committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30


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
31
32
    if not hasattr(e, 'expert_param_stash'):
        return
Rick Ho's avatar
Rick Ho committed
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
    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:
            seg.copy_(p.grad)
            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:
            p.grad = seg.clone()
        else:
            p.grad += seg