Spaces:
Running on Zero
Running on Zero
Download caption/runner.py from thirteen7/Critique-then-Rerank-ZeroGPU: direct link, hf CLI and curl.
- Browser
- Download file 3.21 kB
-
https://huggingface.co/spaces/thirteen7/Critique-then-Rerank-ZeroGPU/resolve/main/caption/runner.py
- Command line
-
hf download hf://spaces/thirteen7/Critique-then-Rerank-ZeroGPU/caption/runner.py
-
curl -L -o runner.py https://huggingface.co/spaces/thirteen7/Critique-then-Rerank-ZeroGPU/resolve/main/caption/runner.py
3.21 kB
| """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) | |
| 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 | |