Spaces:
Running on Zero
Running on Zero
Download caption/visual.py from thirteen7/Critique-then-Rerank-ZeroGPU: direct link, hf CLI and curl.
- Browser
- Download file 2.2 kB
-
https://huggingface.co/spaces/thirteen7/Critique-then-Rerank-ZeroGPU/resolve/main/caption/visual.py
- Command line
-
hf download hf://spaces/thirteen7/Critique-then-Rerank-ZeroGPU/caption/visual.py
-
curl -L -o visual.py https://huggingface.co/spaces/thirteen7/Critique-then-Rerank-ZeroGPU/resolve/main/caption/visual.py
2.2 kB
| """Frozen CLIP spatial encoding and RSCaMa temporal fusion.""" | |
| import torch | |
| from torch import nn | |
| class VisualEncoder(nn.Module): | |
| def __init__(self, state): | |
| super().__init__() | |
| from clip.model import VisionTransformer | |
| self.visual = VisionTransformer(input_resolution=224, patch_size=32, width=768, | |
| layers=12, heads=12, output_dim=512) | |
| prefix = 'clip_model.visual.' | |
| self.visual.load_state_dict({k[len(prefix):]: value for k, value in state.items() if k.startswith(prefix)}) | |
| def forward(self, image): | |
| v = self.visual | |
| x = v.conv1(image) | |
| x = x.reshape(x.shape[0], x.shape[1], -1).permute(0, 2, 1) | |
| cls = v.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device) | |
| x = torch.cat([cls, x], dim=1) | |
| x = v.ln_pre(x + v.positional_embedding.to(x.dtype)) | |
| x = v.transformer(x.permute(1, 0, 2)).permute(1, 0, 2) | |
| return x[:, 1:, :] | |
| class FrozenVisualModel(nn.Module): | |
| def __init__(self, weights, device='cuda'): | |
| super().__init__() | |
| from clip.clip import _transform | |
| from .cama_reference import install | |
| from vendor.rscama.model_encoder_attMamba import AttentiveEncoder | |
| if torch.device(device).type != 'cuda': | |
| raise ValueError('CaMa image feature extraction requires a CUDA device.') | |
| install() | |
| state = torch.load(weights, map_location='cpu', weights_only=True, mmap=True) | |
| self.encoder = VisualEncoder(state['encoder_dict']) | |
| self.change_fusion = AttentiveEncoder(n_layers=3, feature_size=[7, 7, 768], heads=8, dropout=.1) | |
| result = self.change_fusion.load_state_dict(state['encoder_trans_dict'], strict=False) | |
| if result.unexpected_keys or any(not key.endswith('.embeddings.weight') for key in result.missing_keys): | |
| raise ValueError(f'Incompatible visual checkpoint: {result}') | |
| self.preprocess = _transform(224) | |
| self.to(device).eval().requires_grad_(False) | |
| def forward(self, before, after): | |
| return self.change_fusion(self.encoder(before), self.encoder(after)) | |