File size: 2,916 Bytes
7b6f2cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Extract readout training features from one padded forward per direction."""
import torch

from training.portuguese_readout import Features, features


@torch.no_grad()
def batch_features(engine, examples):
    if len(examples) == 1:
        return [features(engine, *examples[0])]
    first = examples[0][0]
    route = (first['source_lang'], first['target_lang'])
    if any((row['source_lang'], row['target_lang']) != route for row, _ in examples):
        raise ValueError('A readout feature batch must have one translation direction')
    lengths = [ids.shape[1]-1 for _, (ids, _) in examples]
    prefixes = [int((labels[0] != -100).nonzero()[0].item()) for _, (_, labels) in examples]
    inputs = torch.zeros((len(examples), max(lengths)), dtype=torch.long)
    mask = torch.zeros_like(inputs)
    for index, (_, (ids, _)) in enumerate(examples):
        length = lengths[index]
        inputs[index, :length] = ids[0, :-1]
        mask[index, :length] = 1
    engine.native_portuguese.select(*route)
    router = engine.decoder_router
    router.select(*route)
    router.bank.set_source_boundaries(tuple(zip(prefixes, lengths, strict=True)))
    states = engine.model.model(inputs, attention_mask=mask, use_cache=False)[0]
    hidden = torch.cat([states[i, prefix-1:length] for i, (prefix, length) in
                        enumerate(zip(prefixes, lengths, strict=True))])
    targets = torch.cat([labels[0, prefix:] for (_, (_, labels)), prefix in
                         zip(examples, prefixes, strict=True)]).unsqueeze(1)
    logits = engine.model.lm_head(hidden).float()
    positive = logits.gather(1, targets)
    logits.scatter_(1, targets, float('-inf'))
    negatives, choices = logits.topk(64, dim=-1)
    scores = torch.cat((positive, negatives), dim=1)
    candidates = torch.cat((targets, choices), dim=1)
    splits = [length - prefix + 1 for length, prefix in zip(lengths, prefixes, strict=True)]
    return [Features(state, score, ids) for state, score, ids in
            zip(hidden.float().split(splits), scores.split(splits), candidates.split(splits), strict=True)]


@torch.no_grad()
def pack_frozen_tiles(engine):
    """Build one up and down projection per frozen sparse expansion."""
    packed = []
    for expansion in engine.decoder_router.expansions.values():
        gates, ups, downs = [], [], []
        for record in sorted(expansion.store.catalog.values(), key=lambda row: row['key']):
            if record['layer'] != expansion.layer:
                continue
            values = expansion.store.weights(record)
            gate, up = values['up'].chunk(2, dim=0)
            gates.append(gate)
            ups.append(up)
            downs.append(values['down'])
        if gates:
            expansion.packed_frozen = (torch.cat(gates + ups, dim=0), torch.cat(downs, dim=1))
            expansion.cache.clear()
            packed.append(expansion)
    return packed