Spaces:
Running on Zero

File size: 1,561 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
"""Caption decoder used for Beam-15 inference."""
import torch
from torch import nn

from vendor.rscama.model_decoder import DecoderTransformer


class ChangeCaptioner(nn.Module):
    def __init__(self, vocab):
        super().__init__()
        self.decoder = DecoderTransformer('transformer_decoder', 768, len(vocab), 42, vocab, 8, 1, .1)
        # The training vocabulary uses 0 for BOS/EOS/PAD; the official vocabulary
        # has separate special IDs. This mapping preserves the original logits.
        self.register_buffer('output_ids', torch.tensor([3, 1] + list(range(4, len(vocab)))), persistent=False)

    def logits(self, features, prefix):
        old = torch.where(prefix >= 2, prefix + 2, prefix).clone()
        old[:, 0] = 2
        length = prefix.shape[1]
        causal = torch.triu(torch.full((length, length), float('-inf'), device=prefix.device), 1)
        d = self.decoder
        x = d.position_encoding(d.vocab_embedding(old.T))
        x = d.transformer(x, features.permute(2, 0, 1), tgt_mask=causal, tgt_key_padding_mask=old.eq(0))
        return d.wdc(d.dropout(x)).transpose(0, 1).index_select(-1, self.output_ids)


def load_captioner(vocab, weights, device):
    model = ChangeCaptioner(vocab)
    state = torch.load(weights, map_location='cpu', weights_only=True, mmap=True)
    if 'model' in state:
        model.load_state_dict(state['model'])
    elif 'decoder_dict' in state:
        model.decoder.load_state_dict(state['decoder_dict'])
    else:
        model.decoder.load_state_dict(state)
    return model.to(device)