Spaces:
Running on Zero

File size: 1,962 Bytes
a369496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The LEVIR control's cumulative-log-probability native beam decoder."""
import torch

MAX_TOKENS = 42


def beam_sequences(model, features, width, length_penalty=0.0):
    batch = len(features)
    device = features.device
    prefixes = torch.zeros((batch, width, 1), device=device, dtype=torch.long)
    scores = torch.full((batch, width), -torch.inf, device=device)
    scores[:, 0] = 0
    ended = torch.zeros_like(scores, dtype=torch.bool)
    lengths = torch.zeros_like(scores, dtype=torch.long)
    repeated = features.repeat_interleave(width, 0)
    parent_batch = torch.arange(batch, device=device)[:, None]
    for _ in range(MAX_TOKENS):
        next_logp = model.logits(repeated, prefixes.flatten(0, 1))[:, -1].log_softmax(-1)
        next_logp = next_logp.reshape(batch, width, -1)
        next_logp = next_logp.masked_fill(ended[..., None], -torch.inf)
        next_logp[..., 0] = torch.where(ended, 0.0, next_logp[..., 0])
        vocabulary_size = next_logp.shape[-1]
        cumulative = scores[..., None] + next_logp
        candidate_lengths = lengths + (~ended).long()
        ranked = cumulative
        if length_penalty:
            ranked = cumulative / candidate_lengths.clamp_min(1)[..., None].pow(length_penalty)
        _, expansion = ranked.flatten(1).topk(width, dim=1)
        scores = cumulative.flatten(1).gather(1, expansion)
        parent = expansion.div(vocabulary_size, rounding_mode="floor")
        word = expansion % vocabulary_size
        prefixes = torch.cat((prefixes[parent_batch, parent], word[..., None]), dim=-1)
        lengths = candidate_lengths[parent_batch, parent]
        ended = ended[parent_batch, parent] | word.eq(0)
        if bool(ended.all()):
            break
    assert torch.isfinite(scores).all()
    beams = [
        [sequence[:sequence.index(0)] if 0 in sequence else sequence for sequence in paths]
        for paths in prefixes[:, :, 1:].tolist()
    ]
    return beams, scores.tolist()