Spaces:
Running on Zero

File size: 2,204 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
"""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)

    @torch.no_grad()
    def forward(self, before, after):
        return self.change_fusion(self.encoder(before), self.encoder(after))