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