Spaces:
Running on Zero

File size: 3,208 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""Frozen feature extraction and Beam-15 decoding."""

import random

import numpy as np
from PIL import Image
import torch

from pipeline import ROOT, read
from .beam import beam_sequences
from .model import load_captioner
from .visual import FrozenVisualModel


def initialize():
    random.seed(17)
    np.random.seed(17)
    torch.manual_seed(17)
    torch.set_num_threads(8)
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False
    torch.backends.cudnn.benchmark = False


def get_vocab(dataset):
    return read(ROOT / 'data' / dataset / 'vocab.json')


def native_captioner(dataset, weights, device):
    vocab = get_vocab(dataset)
    native_to_word = {1 if value == 1 else value - 2: word for word, value in vocab.items() if value == 1 or value >= 4}
    return load_captioner(vocab, weights, device), native_to_word


def image_features(dataset, split, records, image_root, weights, device):
    extractor = FrozenVisualModel(weights, device)
    batch_size = 1 if dataset == 'levir' and split != 'train' else 16
    chunks = []
    for offset in range(0, len(records), batch_size):
        pairs = []
        for record in records[offset:offset + batch_size]:
            tensors = []
            for name in record['media']:
                with Image.open(image_root / name) as image:
                    image = image.convert('RGB')
                    if dataset == 'dubai':
                        image = image.resize((256, 256), Image.Resampling.BILINEAR)
                    tensors.append(extractor.preprocess(image))
            pairs.append(tensors)
        before, after = (torch.stack(period).to(device) for period in zip(*pairs, strict=True))
        features = extractor(before, after)
        if not features.isfinite().all():
            raise RuntimeError(f'{dataset}/{split}: non-finite visual features at offset {offset}')
        chunks.append(features.cpu())
    return torch.cat(chunks)


def features_for(dataset, split, records, args):
    names = [row['name'] for row in records]
    if args.features is not None:
        value = torch.load(args.features / f'{split}.pt', map_location='cpu', mmap=True, weights_only=True)
        if value['names'][:len(names)] != names or value['features'].shape[1:] != (768, 49):
            raise ValueError(f'{dataset}/{split}: feature cache names or dimensions do not match')
        return value['features'][:len(names)]
    if args.images is None or args.visual is None:
        raise ValueError('Pass --features, or both --images and --visual.')
    return image_features(dataset, split, records, args.images, args.visual, args.device)


def decode(words, sequence):
    output = []
    for token in sequence:
        if token == 0:
            break
        output.append(words[token])
    return ' '.join(output)


@torch.no_grad()
def beam(dataset, features, weights, device):
    model, words = native_captioner(dataset, weights, device)
    model.eval()
    captions = []
    for group in features.split(16):
        beams, _ = beam_sequences(model, group.to(device), width=15)
        captions.extend([[decode(words, path) for path in image] for image in beams])
    return captions