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