Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

modeling_vision.py 2.1 KB

You have to be logged in to leave a comment. Sign In
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
  1. from transformers import CLIPVisionModel
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from dataclasses import dataclass
  6. @dataclass
  7. class VisionEncoderConfig:
  8. n_embd: int = 2048
  9. vision_tower_name: str = 'openai/clip-vit-large-patch14-336'
  10. grid_size: int = -1 # -1: no grid pooling, 0: take cls token, 1: global avg pooling, 2, 3, 4, ...: grid pooling
  11. class VisionEncoder(nn.Module):
  12. def __init__(self, args):
  13. super().__init__()
  14. self.args = args
  15. self.vit = CLIPVisionModel.from_pretrained(args.vision_tower_name)
  16. self.proj = nn.Linear(self.vit.config.hidden_size, args.n_embd, bias=False)
  17. def encode_images(self, images):
  18. B, N, C, H, W = images.shape
  19. images = images.view(B*N, C, H, W)
  20. image_features = self.vit(images).last_hidden_state
  21. L, D = image_features.shape[1], image_features.shape[2]
  22. # rerange [B*N, L, D] -> [B, N, L, D]
  23. image_features = image_features.view(B, N, L, D)[:, 0, :, :]
  24. image_features = self.grid_pooling(image_features)
  25. return self.proj(image_features)
  26. def grid_pooling(self, image_features):
  27. if self.args.grid_size == -1: # no grid pooling
  28. return image_features
  29. if self.args.grid_size == 0: # take cls token
  30. return image_features[:, 0:1, :]
  31. if self.args.grid_size == 1: # global avg pooling
  32. return image_features.mean(dim=1, keepdim=True)
  33. cls_features = image_features[:, 0:1, :]
  34. image_features = image_features[:, 1:, :] #drop cls token
  35. B, L, D = image_features.shape
  36. H_or_W = int(L**0.5)
  37. image_features = image_features.view(B, H_or_W, H_or_W, D)
  38. grid_stride = H_or_W // self.args.grid_size
  39. image_features = F.avg_pool2d(image_features.permute(0, 3, 1, 2),
  40. padding=0,
  41. kernel_size=grid_stride,
  42. stride=grid_stride)
  43. image_features = image_features.permute(0, 2, 3, 1).view(B, -1, D)
  44. return torch.cat((cls_features, image_features), dim=1)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...