Jooju2872 commited on
Commit
8223e95
·
verified ·
1 Parent(s): bb51079

Upload HfMoondream

Browse files
Files changed (13) hide show
  1. config.json +13 -0
  2. config.py +86 -0
  3. generation_config.json +4 -0
  4. hf_moondream.py +142 -0
  5. image_crops.py +208 -0
  6. layers.py +63 -0
  7. model.safetensors +3 -0
  8. moondream.py +717 -0
  9. region.py +89 -0
  10. rope.py +48 -0
  11. text.py +205 -0
  12. utils.py +41 -0
  13. vision.py +147 -0
config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "HfMoondream"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "hf_moondream.HfConfig",
7
+ "AutoModelForCausalLM": "hf_moondream.HfMoondream"
8
+ },
9
+ "config": {},
10
+ "model_type": "moondream1",
11
+ "torch_dtype": "float16",
12
+ "transformers_version": "4.45.2"
13
+ }
config.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import Dict, List, Optional
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class TextConfig:
7
+ dim: int = 2048
8
+ ff_dim: int = 8192
9
+ n_layers: int = 24
10
+ vocab_size: int = 51200
11
+ max_context: int = 2048
12
+ n_heads: int = 32
13
+ n_kv_heads: int = 32
14
+ prefix_attn: int = 730
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class VisionConfig:
19
+ enc_dim: int = 1152
20
+ enc_patch_size: int = 14
21
+ enc_n_layers: int = 27
22
+ enc_ff_dim: int = 4304
23
+ enc_n_heads: int = 16
24
+ proj_out_dim: int = 2048
25
+ crop_size: int = 378
26
+ in_channels: int = 3
27
+ max_crops: int = 12
28
+ overlap_margin: int = 4
29
+ proj_inner_dim: int = 8192
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class RegionConfig:
34
+ dim: int = 2048
35
+ coord_feat_dim: int = 256
36
+ coord_out_dim: int = 1024
37
+ size_feat_dim: int = 512
38
+ size_out_dim: int = 2048
39
+ inner_dim: int = 8192
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class TokenizerConfig:
44
+ bos_id: int = 50256
45
+ eos_id: int = 50256
46
+ templates: Dict[str, Optional[Dict[str, List[int]]]] = field(
47
+ default_factory=lambda: {
48
+ "caption": {
49
+ "short": [198, 198, 16438, 8305, 25],
50
+ "normal": [198, 198, 24334, 1159, 25],
51
+ "long": [198, 198, 14617, 8305, 25],
52
+ },
53
+ "query": {"prefix": [198, 198, 24361, 25], "suffix": [198, 198, 33706, 25]},
54
+ "detect": {"prefix": [198, 198, 47504, 25], "suffix": [628]},
55
+ "point": {"prefix": [198, 198, 12727, 25], "suffix": [628]},
56
+ }
57
+ )
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class MoondreamConfig:
62
+ text: TextConfig = TextConfig()
63
+ vision: VisionConfig = VisionConfig()
64
+ region: RegionConfig = RegionConfig()
65
+ tokenizer: TokenizerConfig = TokenizerConfig()
66
+
67
+ @classmethod
68
+ def from_dict(cls, config_dict: dict):
69
+ text_config = TextConfig(**config_dict.get("text", {}))
70
+ vision_config = VisionConfig(**config_dict.get("vision", {}))
71
+ region_config = RegionConfig(**config_dict.get("region", {}))
72
+ tokenizer_config = TokenizerConfig(**config_dict.get("tokenizer", {}))
73
+ return cls(
74
+ text=text_config,
75
+ vision=vision_config,
76
+ region=region_config,
77
+ tokenizer=tokenizer_config,
78
+ )
79
+
80
+ def to_dict(self):
81
+ return {
82
+ "text": self.text.__dict__,
83
+ "vision": self.vision.__dict__,
84
+ "region": self.region.__dict__,
85
+ "tokenizer": self.tokenizer.__dict__,
86
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.45.2"
4
+ }
hf_moondream.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel, PretrainedConfig
2
+
3
+ from .config import MoondreamConfig
4
+ from .moondream import MoondreamModel
5
+
6
+ # Files sometimes don't get loaded without these...
7
+ from .image_crops import *
8
+ from .vision import *
9
+ from .text import *
10
+ from .region import *
11
+ from .utils import *
12
+
13
+
14
+ def extract_question(text):
15
+ prefix = "<image>\n\nQuestion: "
16
+ suffix = "\n\nAnswer:"
17
+
18
+ if text.startswith(prefix) and text.endswith(suffix):
19
+ return text[len(prefix) : -len(suffix)]
20
+ else:
21
+ return None
22
+
23
+
24
+ class HfConfig(PretrainedConfig):
25
+ _auto_class = "AutoConfig"
26
+ model_type = "moondream1"
27
+
28
+ def __init__(self, **kwargs):
29
+ super().__init__(**kwargs)
30
+ self.config = {}
31
+
32
+
33
+ class HfMoondream(PreTrainedModel):
34
+ _auto_class = "AutoModelForCausalLM"
35
+ config_class = HfConfig
36
+
37
+ def __init__(self, config):
38
+ super().__init__(config)
39
+ self.model = MoondreamModel(
40
+ MoondreamConfig.from_dict(config.config), setup_caches=False
41
+ )
42
+ self._is_kv_cache_setup = False
43
+
44
+ def _setup_caches(self):
45
+ if not self._is_kv_cache_setup:
46
+ self.model._setup_caches()
47
+ self._is_kv_cache_setup = True
48
+
49
+ @property
50
+ def encode_image(self):
51
+ self._setup_caches()
52
+ return self.model.encode_image
53
+
54
+ @property
55
+ def query(self):
56
+ self._setup_caches()
57
+ return self.model.query
58
+
59
+ @property
60
+ def caption(self):
61
+ self._setup_caches()
62
+ return self.model.caption
63
+
64
+ @property
65
+ def detect(self):
66
+ self._setup_caches()
67
+ return self.model.detect
68
+
69
+ @property
70
+ def point(self):
71
+ self._setup_caches()
72
+ return self.model.point
73
+
74
+ @property
75
+ def detect_gaze(self):
76
+ self._setup_caches()
77
+ return self.model.detect_gaze
78
+
79
+ def answer_question(
80
+ self,
81
+ image_embeds,
82
+ question,
83
+ tokenizer=None,
84
+ chat_history="",
85
+ result_queue=None,
86
+ max_new_tokens=256,
87
+ **kwargs
88
+ ):
89
+ answer = self.query(image_embeds, question)["answer"].strip()
90
+
91
+ if result_queue is not None:
92
+ result_queue.put(answer)
93
+ return answer
94
+
95
+ def batch_answer(self, images, prompts, tokenizer=None, **kwargs):
96
+ answers = []
97
+ for image, prompt in zip(images, prompts):
98
+ answers.append(self.query(image, prompt)["answer"].strip())
99
+ return answers
100
+
101
+ def _unsupported_exception(self):
102
+ raise NotImplementedError(
103
+ "This method is not supported in the latest version of moondream. "
104
+ "Consider upgrading to the updated API spec, or alternately pin "
105
+ "to 'revision=2024-08-26'."
106
+ )
107
+
108
+ def generate(self, image_embeds, prompt, tokenizer, max_new_tokens=128, **kwargs):
109
+ """
110
+ Function definition remains unchanged for backwards compatibility.
111
+ Be aware that tokenizer, max_new_takens, and kwargs are ignored.
112
+ """
113
+ prompt_extracted = extract_question(prompt)
114
+ if prompt_extracted is not None:
115
+ answer = self.model.query(
116
+ image=image_embeds, question=prompt_extracted, stream=False
117
+ )["answer"]
118
+ else:
119
+ image_embeds = self.encode_image(image_embeds)
120
+ prompt_tokens = torch.tensor(
121
+ [self.model.tokenizer.encode(prompt).ids],
122
+ device=self.device,
123
+ )
124
+
125
+ def generator():
126
+ for token in self.model._generate_text(
127
+ prompt_tokens,
128
+ image_embeds.kv_cache,
129
+ image_embeds.pos,
130
+ max_new_tokens,
131
+ ):
132
+ yield token
133
+
134
+ answer = "".join(list(generator()))
135
+
136
+ return [answer]
137
+
138
+ def get_input_embeddings(self):
139
+ return super().get_input_embeddings()
140
+
141
+ def input_embeds(self, *args, **kwargs):
142
+ self._unsupported_exception()
image_crops.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ import pyvips
5
+
6
+ from typing import TypedDict
7
+
8
+
9
+ def select_tiling(
10
+ height: int, width: int, crop_size: int, max_crops: int
11
+ ) -> tuple[int, int]:
12
+ """
13
+ Determine the optimal number of tiles to cover an image with overlapping crops.
14
+ """
15
+ if height <= crop_size or width <= crop_size:
16
+ return (1, 1)
17
+
18
+ # Minimum required tiles in each dimension
19
+ min_h = math.ceil(height / crop_size)
20
+ min_w = math.ceil(width / crop_size)
21
+
22
+ # If minimum required tiles exceed max_crops, return proportional distribution
23
+ if min_h * min_w > max_crops:
24
+ ratio = math.sqrt(max_crops / (min_h * min_w))
25
+ return (max(1, math.floor(min_h * ratio)), max(1, math.floor(min_w * ratio)))
26
+
27
+ # Perfect aspect-ratio tiles that satisfy max_crops
28
+ h_tiles = math.floor(math.sqrt(max_crops * height / width))
29
+ w_tiles = math.floor(math.sqrt(max_crops * width / height))
30
+
31
+ # Ensure we meet minimum tile requirements
32
+ h_tiles = max(h_tiles, min_h)
33
+ w_tiles = max(w_tiles, min_w)
34
+
35
+ # If we exceeded max_crops, scale down the larger dimension
36
+ if h_tiles * w_tiles > max_crops:
37
+ if w_tiles > h_tiles:
38
+ w_tiles = math.floor(max_crops / h_tiles)
39
+ else:
40
+ h_tiles = math.floor(max_crops / w_tiles)
41
+
42
+ return (max(1, h_tiles), max(1, w_tiles))
43
+
44
+
45
+ class OverlapCropOutput(TypedDict):
46
+ crops: np.ndarray
47
+ tiling: tuple[int, int]
48
+
49
+
50
+ def overlap_crop_image(
51
+ image: np.ndarray,
52
+ overlap_margin: int,
53
+ max_crops: int,
54
+ base_size: tuple[int, int] = (378, 378),
55
+ patch_size: int = 14,
56
+ ) -> OverlapCropOutput:
57
+ """
58
+ Process an image using an overlap-and-resize cropping strategy with margin handling.
59
+
60
+ This function takes an input image and creates multiple overlapping crops with
61
+ consistent margins. It produces:
62
+ 1. A single global crop resized to base_size
63
+ 2. Multiple overlapping local crops that maintain high resolution details
64
+ 3. A patch ordering matrix that tracks correspondence between crops
65
+
66
+ The overlap strategy ensures:
67
+ - Smooth transitions between adjacent crops
68
+ - No loss of information at crop boundaries
69
+ - Proper handling of features that cross crop boundaries
70
+ - Consistent patch indexing across the full image
71
+
72
+ Args:
73
+ image (np.ndarray): Input image as numpy array with shape (H,W,C)
74
+ base_size (tuple[int,int]): Target size for crops, default (378,378)
75
+ patch_size (int): Size of patches in pixels, default 14
76
+ overlap_margin (int): Margin size in patch units, default 4
77
+ max_crops (int): Maximum number of crops allowed, default 12
78
+
79
+ Returns:
80
+ OverlapCropOutput: Dictionary containing:
81
+ - crops: A numpy array containing the global crop of the full image (index 0)
82
+ followed by the overlapping cropped regions (indices 1+)
83
+ - tiling: Tuple of (height,width) tile counts
84
+ """
85
+ original_h, original_w = image.shape[:2]
86
+
87
+ # Convert margin from patch units to pixels
88
+ margin_pixels = patch_size * overlap_margin
89
+ total_margin_pixels = margin_pixels * 2 # Both sides
90
+
91
+ # Calculate crop parameters
92
+ crop_patches = base_size[0] // patch_size # patches per crop dimension
93
+ crop_window_patches = crop_patches - (2 * overlap_margin) # usable patches
94
+ crop_window_size = crop_window_patches * patch_size # usable size in pixels
95
+
96
+ # Determine tiling
97
+ tiling = select_tiling(
98
+ original_h - total_margin_pixels,
99
+ original_w - total_margin_pixels,
100
+ crop_window_size,
101
+ max_crops,
102
+ )
103
+
104
+ # Pre-allocate crops.
105
+ n_crops = tiling[0] * tiling[1] + 1 # 1 = global crop
106
+ crops = np.zeros(
107
+ (n_crops, base_size[0], base_size[1], image.shape[2]), dtype=np.uint8
108
+ )
109
+
110
+ # Resize image to fit tiling
111
+ target_size = (
112
+ tiling[0] * crop_window_size + total_margin_pixels,
113
+ tiling[1] * crop_window_size + total_margin_pixels,
114
+ )
115
+
116
+ # Convert to vips for resizing
117
+ vips_image = pyvips.Image.new_from_array(image)
118
+ scale_x = target_size[1] / image.shape[1]
119
+ scale_y = target_size[0] / image.shape[0]
120
+ resized = vips_image.resize(scale_x, vscale=scale_y)
121
+ image = resized.numpy()
122
+
123
+ # Create global crop
124
+ scale_x = base_size[1] / vips_image.width
125
+ scale_y = base_size[0] / vips_image.height
126
+ global_vips = vips_image.resize(scale_x, vscale=scale_y)
127
+ crops[0] = global_vips.numpy()
128
+
129
+ for i in range(tiling[0]):
130
+ for j in range(tiling[1]):
131
+ # Calculate crop coordinates
132
+ y0 = i * crop_window_size
133
+ x0 = j * crop_window_size
134
+
135
+ # Extract crop with padding if needed
136
+ y_end = min(y0 + base_size[0], image.shape[0])
137
+ x_end = min(x0 + base_size[1], image.shape[1])
138
+
139
+ crop_region = image[y0:y_end, x0:x_end]
140
+ crops[
141
+ 1 + i * tiling[1] + j, : crop_region.shape[0], : crop_region.shape[1]
142
+ ] = crop_region
143
+
144
+ return {"crops": crops, "tiling": tiling}
145
+
146
+
147
+ def reconstruct_from_crops(
148
+ crops: torch.Tensor,
149
+ tiling: tuple[int, int],
150
+ overlap_margin: int,
151
+ patch_size: int = 14,
152
+ ) -> torch.Tensor:
153
+ """
154
+ Reconstruct the original image from overlapping crops into a single seamless image.
155
+
156
+ Takes a list of overlapping image crops along with their positional metadata and
157
+ reconstructs them into a single coherent image by carefully stitching together
158
+ non-overlapping regions. Handles both numpy arrays and PyTorch tensors.
159
+
160
+ Args:
161
+ crops: List of image crops as numpy arrays or PyTorch tensors with shape
162
+ (H,W,C)
163
+ tiling: Tuple of (height,width) indicating crop grid layout
164
+ patch_size: Size in pixels of each patch, default 14
165
+ overlap_margin: Number of overlapping patches on each edge, default 4
166
+
167
+ Returns:
168
+ Reconstructed image as numpy array or PyTorch tensor matching input type,
169
+ with shape (H,W,C) where H,W are the original image dimensions
170
+ """
171
+ tiling_h, tiling_w = tiling
172
+ crop_height, crop_width = crops[0].shape[:2]
173
+ margin_pixels = overlap_margin * patch_size
174
+
175
+ # Calculate output size (only adding margins once)
176
+ output_h = (crop_height - 2 * margin_pixels) * tiling_h + 2 * margin_pixels
177
+ output_w = (crop_width - 2 * margin_pixels) * tiling_w + 2 * margin_pixels
178
+
179
+ reconstructed = torch.zeros(
180
+ (output_h, output_w, crops[0].shape[2]),
181
+ device=crops[0].device,
182
+ dtype=crops[0].dtype,
183
+ )
184
+
185
+ for i, crop in enumerate(crops):
186
+ tile_y = i // tiling_w
187
+ tile_x = i % tiling_w
188
+
189
+ # For each tile, determine which part to keep
190
+ # Keep left margin only for first column
191
+ x_start = 0 if tile_x == 0 else margin_pixels
192
+ # Keep right margin only for last column
193
+ x_end = crop_width if tile_x == tiling_w - 1 else crop_width - margin_pixels
194
+ # Keep top margin only for first row
195
+ y_start = 0 if tile_y == 0 else margin_pixels
196
+ # Keep bottom margin only for last row
197
+ y_end = crop_height if tile_y == tiling_h - 1 else crop_height - margin_pixels
198
+
199
+ # Calculate where this piece belongs in the output
200
+ out_x = tile_x * (crop_width - 2 * margin_pixels)
201
+ out_y = tile_y * (crop_height - 2 * margin_pixels)
202
+
203
+ # Place the piece
204
+ reconstructed[
205
+ out_y + y_start : out_y + y_end, out_x + x_start : out_x + x_end
206
+ ] = crop[y_start:y_end, x_start:x_end]
207
+
208
+ return reconstructed
layers.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Literal
3
+
4
+ import torch
5
+ from torch.nn import functional as F
6
+
7
+
8
+ def gelu_approx(x):
9
+ return F.gelu(x, approximate="tanh")
10
+
11
+
12
+ @dataclass
13
+ class LinearWeights:
14
+ weight: torch.Tensor
15
+ bias: torch.Tensor
16
+
17
+
18
+ def linear(x: torch.Tensor, w: LinearWeights) -> torch.Tensor:
19
+ return F.linear(x, w.weight, w.bias)
20
+
21
+
22
+ @dataclass
23
+ class LayerNormWeights:
24
+ weight: torch.Tensor
25
+ bias: torch.Tensor
26
+
27
+
28
+ def layer_norm(x: torch.Tensor, w: LayerNormWeights) -> torch.Tensor:
29
+ return F.layer_norm(x, w.bias.shape, w.weight, w.bias)
30
+
31
+
32
+ @dataclass
33
+ class MLPWeights:
34
+ fc1: LinearWeights
35
+ fc2: LinearWeights
36
+ act: Literal["gelu_approx"] = "gelu_approx"
37
+
38
+
39
+ def mlp(x: torch.Tensor, w: MLPWeights) -> torch.Tensor:
40
+ x = w.fc1(x)
41
+ x = gelu_approx(x)
42
+ x = w.fc2(x)
43
+ return x
44
+
45
+
46
+ @dataclass
47
+ class AttentionWeights:
48
+ qkv: LinearWeights
49
+ proj: LinearWeights
50
+
51
+
52
+ def attn(x: torch.Tensor, w: AttentionWeights, n_heads: int) -> torch.Tensor:
53
+ bsz, q_len, d_model = x.shape
54
+ head_dim = d_model // n_heads
55
+
56
+ q, k, v = [
57
+ t.view(bsz, q_len, n_heads, head_dim).transpose(1, 2)
58
+ for t in linear(x, w.qkv).chunk(3, dim=-1)
59
+ ]
60
+ out = F.scaled_dot_product_attention(q, k, v)
61
+ out = out.transpose(1, 2).reshape(bsz, q_len, d_model)
62
+ out = linear(out, w.proj)
63
+ return out
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:23e2e6498a058d12832e119dc97a1d2f14936b4ccf77b8492bc0fefba49ea8bb
3
+ size 3854538376
moondream.py ADDED
@@ -0,0 +1,717 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import random
4
+
5
+ from typing import Literal, Tuple, TypedDict, Union, Dict, Any, Optional, List
6
+ from PIL import Image
7
+ from dataclasses import dataclass
8
+ from tokenizers import Tokenizer
9
+
10
+ from .config import MoondreamConfig
11
+ from .image_crops import reconstruct_from_crops
12
+ from .vision import vision_encoder, vision_projection, prepare_crops, build_vision_model
13
+ from .text import build_text_model, text_encoder, lm_head, text_decoder
14
+ from .region import decode_coordinate, encode_coordinate, decode_size, encode_size
15
+ from .utils import remove_outlier_points
16
+
17
+
18
+ TextSamplingSettings = TypedDict(
19
+ "TextSamplingSettings",
20
+ {
21
+ "max_tokens": int,
22
+ "temperature": float,
23
+ "top_p": float,
24
+ },
25
+ total=False,
26
+ )
27
+
28
+ ObjectSamplingSettings = TypedDict(
29
+ "ObjectSamplingSettings",
30
+ {"max_objects": int},
31
+ total=False,
32
+ )
33
+
34
+ DEFAULT_MAX_TOKENS = 768
35
+ DEFAULT_TEMPERATURE = 0.5
36
+ DEFAULT_TOP_P = 0.3
37
+ DEFAULT_MAX_OBJECTS = 50
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class EncodedImage:
42
+ pos: int
43
+ caches: List[Tuple[torch.Tensor, torch.Tensor]]
44
+
45
+
46
+ class KVCache(nn.Module):
47
+
48
+ def __init__(self, n_heads, n_kv_heads, max_context, dim, device, dtype):
49
+ super().__init__()
50
+ cache_shape = (1, n_kv_heads, max_context, dim // n_heads)
51
+ self.register_buffer(
52
+ "k_cache", torch.zeros(*cache_shape, device=device, dtype=dtype)
53
+ )
54
+ self.register_buffer(
55
+ "v_cache", torch.zeros(*cache_shape, device=device, dtype=dtype)
56
+ )
57
+
58
+ def update(self, pos_ids, k, v):
59
+ kout, vout = self.k_cache, self.v_cache
60
+ kout[:, :, pos_ids, :] = k
61
+ vout[:, :, pos_ids, :] = v
62
+ return kout, vout
63
+
64
+
65
+ class MoondreamModel(nn.Module):
66
+ def __init__(self, config: MoondreamConfig, dtype=torch.float16, setup_caches=True):
67
+ super().__init__()
68
+ self.config = config
69
+
70
+ self.tokenizer = Tokenizer.from_pretrained(
71
+ "vikhyatk/moondream2", revision="2025-01-09"
72
+ )
73
+ self.vision = build_vision_model(config.vision, dtype)
74
+ self.text = build_text_model(config.text, dtype)
75
+
76
+ # Region Model
77
+ self.region = nn.ModuleDict(
78
+ {
79
+ "coord_encoder": nn.Linear(
80
+ config.region.coord_feat_dim, config.region.dim, dtype=dtype
81
+ ),
82
+ "coord_decoder": nn.ModuleDict(
83
+ {
84
+ "fc1": nn.Linear(
85
+ config.region.dim, config.region.inner_dim, dtype=dtype
86
+ ),
87
+ "fc2": nn.Linear(
88
+ config.region.inner_dim,
89
+ config.region.coord_out_dim,
90
+ dtype=dtype,
91
+ ),
92
+ }
93
+ ),
94
+ "size_encoder": nn.Linear(
95
+ config.region.size_feat_dim, config.region.dim, dtype=dtype
96
+ ),
97
+ "size_decoder": nn.ModuleDict(
98
+ {
99
+ "fc1": nn.Linear(
100
+ config.region.dim, config.region.inner_dim, dtype=dtype
101
+ ),
102
+ "fc2": nn.Linear(
103
+ config.region.inner_dim,
104
+ config.region.size_out_dim,
105
+ dtype=dtype,
106
+ ),
107
+ }
108
+ ),
109
+ }
110
+ )
111
+ self.region.coord_features = nn.Parameter(
112
+ torch.empty(config.region.coord_feat_dim // 2, 1, dtype=dtype).T
113
+ )
114
+ self.region.size_features = nn.Parameter(
115
+ torch.empty(config.region.size_feat_dim // 2, 2, dtype=dtype).T
116
+ )
117
+
118
+ attn_mask = torch.tril(
119
+ torch.ones(
120
+ 1, 1, config.text.max_context, config.text.max_context, dtype=torch.bool
121
+ )
122
+ )
123
+ patch_w = config.vision.crop_size // config.vision.enc_patch_size
124
+ prefix_attn_len = 1 + patch_w**2
125
+ attn_mask[..., :prefix_attn_len, :prefix_attn_len] = 1
126
+ self.register_buffer("attn_mask", attn_mask, persistent=False)
127
+
128
+ # Initialize KV caches.
129
+ if setup_caches:
130
+ self._setup_caches()
131
+
132
+ def _setup_caches(self):
133
+ c = self.config.text
134
+ for b in self.text.blocks:
135
+ b.kv_cache = KVCache(
136
+ c.n_heads,
137
+ c.n_kv_heads,
138
+ c.max_context,
139
+ c.dim,
140
+ device=self.device,
141
+ dtype=self.vision.pos_emb.dtype,
142
+ )
143
+
144
+ @property
145
+ def device(self):
146
+ return self.vision.pos_emb.device
147
+
148
+ def _vis_enc(self, x: torch.Tensor):
149
+ return vision_encoder(x, self.vision, self.config.vision)
150
+
151
+ def _vis_proj(self, g: torch.Tensor, r: torch.Tensor):
152
+ return vision_projection(g, r, self.vision, self.config.vision)
153
+
154
+ def _prefill(self, x: torch.Tensor, attn_mask: torch.Tensor, pos_ids: torch.Tensor):
155
+ return text_decoder(x, self.text, attn_mask, pos_ids, self.config.text)
156
+
157
+ def _decode_one_tok(
158
+ self, x: torch.Tensor, attn_mask: torch.Tensor, pos_ids: torch.Tensor
159
+ ):
160
+ hidden = text_decoder(x, self.text, attn_mask, pos_ids, self.config.text)
161
+ logits = lm_head(hidden, self.text)
162
+ return logits, hidden
163
+
164
+ def compile(self):
165
+ # TODO: vision_projection is not being compiled
166
+ self._vis_enc = torch.compile(self._vis_enc, fullgraph=True)
167
+ self._prefill = torch.compile(self._prefill, fullgraph=True)
168
+ self._decode_one_tok = torch.compile(
169
+ self._decode_one_tok, fullgraph=True, mode="reduce-overhead"
170
+ )
171
+
172
+ def _run_vision_encoder(self, image: Image.Image) -> torch.Tensor:
173
+ all_crops, tiling = prepare_crops(image, self.config.vision, device=self.device)
174
+ torch._dynamo.mark_dynamic(all_crops, 0)
175
+
176
+ outputs = self._vis_enc(all_crops)
177
+
178
+ global_features = outputs[0]
179
+ local_features = outputs[1:].view(
180
+ -1,
181
+ self.config.vision.enc_n_layers,
182
+ self.config.vision.enc_n_layers,
183
+ self.config.vision.enc_dim,
184
+ )
185
+
186
+ reconstructed = reconstruct_from_crops(
187
+ local_features,
188
+ tiling,
189
+ patch_size=1,
190
+ overlap_margin=self.config.vision.overlap_margin,
191
+ )
192
+
193
+ return self._vis_proj(global_features, reconstructed)
194
+
195
+ def encode_image(self, image: Union[Image.Image, EncodedImage]) -> EncodedImage:
196
+ if isinstance(image, EncodedImage):
197
+ return image
198
+ elif not isinstance(image, Image.Image):
199
+ raise ValueError("image must be a PIL Image or EncodedImage")
200
+
201
+ # Run through text model in addition to the vision encoder, to minimize
202
+ # re-computation if multiple queries are performed on this image.
203
+ with torch.inference_mode():
204
+ img_emb = self._run_vision_encoder(image)
205
+ bos_emb = text_encoder(
206
+ torch.tensor([[self.config.tokenizer.bos_id]], device=self.device),
207
+ self.text,
208
+ )
209
+ inputs_embeds = torch.cat([bos_emb, img_emb[None]], dim=1)
210
+ mask = self.attn_mask[:, :, 0 : inputs_embeds.size(1), :]
211
+ pos_ids = torch.arange(inputs_embeds.size(1), dtype=torch.long)
212
+ self._prefill(inputs_embeds, mask, pos_ids)
213
+
214
+ return EncodedImage(
215
+ pos=inputs_embeds.size(1),
216
+ caches=[
217
+ (
218
+ b.kv_cache.k_cache[:, :, : inputs_embeds.size(1), :].clone(),
219
+ b.kv_cache.v_cache[:, :, : inputs_embeds.size(1), :].clone(),
220
+ )
221
+ for b in self.text.blocks
222
+ ],
223
+ )
224
+
225
+ def _apply_top_p(self, probs: torch.Tensor, top_p: float):
226
+ probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
227
+ probs_sum = torch.cumsum(probs_sort, dim=-1)
228
+ mask = probs_sum - probs_sort > top_p
229
+ probs_sort[mask] = 0.0
230
+ probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
231
+ next_probs = torch.zeros_like(probs)
232
+ next_probs.scatter_(dim=-1, index=probs_idx, src=probs_sort)
233
+ return next_probs
234
+
235
+ def _prefill_prompt(
236
+ self, prompt_tokens: torch.Tensor, pos: int, temperature: float, top_p: float
237
+ ):
238
+ with torch.inference_mode():
239
+ prompt_emb = text_encoder(prompt_tokens, self.text)
240
+ torch._dynamo.mark_dynamic(prompt_emb, 1)
241
+ mask = self.attn_mask[:, :, pos : pos + prompt_emb.size(1), :]
242
+ pos_ids = torch.arange(pos, pos + prompt_emb.size(1), dtype=torch.long)
243
+ hidden = self._prefill(prompt_emb, mask, pos_ids)
244
+ logits = lm_head(hidden, self.text)
245
+
246
+ if temperature == 0:
247
+ next_token = torch.argmax(logits, dim=-1).unsqueeze(1)
248
+ else:
249
+ probs = torch.softmax(logits / temperature, dim=-1)
250
+ probs = self._apply_top_p(probs, top_p)
251
+ next_token = torch.multinomial(probs, num_samples=1)
252
+
253
+ pos = pos + prompt_emb.size(1)
254
+ return logits, hidden, next_token, pos
255
+
256
+ def _generate_text(
257
+ self,
258
+ prompt_tokens: torch.Tensor,
259
+ pos: int,
260
+ settings: Optional[TextSamplingSettings] = None,
261
+ ):
262
+ max_tokens = (
263
+ settings.get("max_tokens", DEFAULT_MAX_TOKENS)
264
+ if settings
265
+ else DEFAULT_MAX_TOKENS
266
+ )
267
+ temperature = (
268
+ settings.get("temperature", DEFAULT_TEMPERATURE)
269
+ if settings
270
+ else DEFAULT_TEMPERATURE
271
+ )
272
+ top_p = settings.get("top_p", DEFAULT_TOP_P) if settings else DEFAULT_TOP_P
273
+
274
+ _, _, next_token, pos = self._prefill_prompt(
275
+ prompt_tokens, pos, temperature, top_p
276
+ )
277
+
278
+ def generator(next_token, pos):
279
+ mask = torch.zeros(1, 1, 2048, device=self.device, dtype=torch.bool)
280
+ mask[:, :, :pos] = 1
281
+ pos_ids = torch.tensor([pos], device=self.device, dtype=torch.long)
282
+ generated_tokens = 0
283
+
284
+ # For properly handling token streaming with Unicode
285
+ token_cache = []
286
+ print_len = 0
287
+
288
+ while (
289
+ next_token_id := next_token.item()
290
+ ) != self.config.tokenizer.eos_id and generated_tokens < max_tokens:
291
+ # Add token to our cache
292
+ token_cache.append(next_token_id)
293
+
294
+ # Decode all tokens collected so far
295
+ text = self.tokenizer.decode(token_cache)
296
+
297
+ # After a newline, we flush the cache completely
298
+ if text.endswith("\n"):
299
+ printable_text = text[print_len:]
300
+ token_cache = []
301
+ print_len = 0
302
+ if printable_text:
303
+ yield printable_text
304
+ # If the last token is a CJK character, we can safely print it
305
+ elif len(text) > 0 and _is_cjk_char(ord(text[-1])):
306
+ printable_text = text[print_len:]
307
+ print_len += len(printable_text)
308
+ if printable_text:
309
+ yield printable_text
310
+ # Otherwise, only print up to the last space to avoid cutting words
311
+ else:
312
+ last_space_idx = text.rfind(" ", print_len)
313
+ if last_space_idx >= print_len:
314
+ printable_text = text[print_len : last_space_idx + 1]
315
+ print_len += len(printable_text)
316
+ if printable_text:
317
+ yield printable_text
318
+
319
+ with torch.inference_mode():
320
+ next_emb = text_encoder(next_token, self.text)
321
+ mask[:, :, pos], pos_ids[0] = 1, pos
322
+ logits, _ = self._decode_one_tok(next_emb, mask, pos_ids)
323
+ pos += 1
324
+
325
+ if temperature == 0:
326
+ next_token = torch.argmax(logits, dim=-1).unsqueeze(1) # (1, 1)
327
+ else:
328
+ probs = torch.softmax(logits / temperature, dim=-1) # (1, V)
329
+ probs = self._apply_top_p(probs, top_p)
330
+ next_token = torch.multinomial(probs, num_samples=1) # (1, 1)
331
+
332
+ generated_tokens += 1
333
+
334
+ # Flush any remaining text in the cache
335
+ if token_cache:
336
+ text = self.tokenizer.decode(token_cache)
337
+ printable_text = text[print_len:]
338
+ if printable_text:
339
+ yield printable_text
340
+
341
+ return generator(next_token, pos)
342
+
343
+ def query(
344
+ self,
345
+ image: Union[Image.Image, EncodedImage],
346
+ question: str,
347
+ stream: bool = False,
348
+ settings: Optional[TextSamplingSettings] = None,
349
+ ):
350
+ if self.config.tokenizer.templates["query"] is None:
351
+ raise NotImplementedError("Model does not support querying.")
352
+
353
+ image = self.encode_image(image)
354
+ self.load_encoded_image(image)
355
+
356
+ prompt_tokens = torch.tensor(
357
+ [
358
+ self.config.tokenizer.templates["query"]["prefix"]
359
+ + self.tokenizer.encode(" " + question).ids
360
+ + self.config.tokenizer.templates["query"]["suffix"]
361
+ ],
362
+ device=self.device,
363
+ )
364
+
365
+ def generator():
366
+ for token in self._generate_text(prompt_tokens, image.pos, settings):
367
+ yield token
368
+
369
+ if stream:
370
+ return {"answer": generator()}
371
+ else:
372
+ return {"answer": "".join(list(generator()))}
373
+
374
+ def load_encoded_image(self, encoded_image: EncodedImage):
375
+ for b, (k, v) in zip(self.text.blocks, encoded_image.caches):
376
+ b.kv_cache.k_cache[:, :, : k.size(2), :] = k
377
+ b.kv_cache.v_cache[:, :, : v.size(2), :] = v
378
+
379
+ def caption(
380
+ self,
381
+ image: Union[Image.Image, EncodedImage],
382
+ length: Literal["normal", "short", "long"] = "normal",
383
+ stream: bool = False,
384
+ settings: Optional[TextSamplingSettings] = None,
385
+ ):
386
+ if self.config.tokenizer.templates["caption"] is None:
387
+ raise NotImplementedError("Model does not support captioning.")
388
+ if length not in self.config.tokenizer.templates["caption"]:
389
+ raise ValueError(f"Model does not support caption length '{length}'.")
390
+
391
+ image = self.encode_image(image)
392
+ self.load_encoded_image(image)
393
+
394
+ prompt_tokens = torch.tensor(
395
+ [self.config.tokenizer.templates["caption"][length]], device=self.device
396
+ )
397
+
398
+ def generator():
399
+ for token in self._generate_text(prompt_tokens, image.pos, settings):
400
+ yield token
401
+
402
+ if stream:
403
+ return {"caption": generator()}
404
+ else:
405
+ return {"caption": "".join(list(generator()))}
406
+
407
+ def _generate_points(
408
+ self,
409
+ hidden: torch.Tensor,
410
+ next_token: torch.Tensor,
411
+ pos: int,
412
+ include_size: bool = True,
413
+ max_objects: int = DEFAULT_MAX_OBJECTS,
414
+ ):
415
+ out = []
416
+ mask = torch.zeros(1, 1, 2048, device=self.device, dtype=torch.bool)
417
+ mask[:, :, :pos] = 1
418
+ pos_ids = torch.tensor([pos], device=self.device, dtype=torch.long)
419
+
420
+ with torch.inference_mode():
421
+ while (
422
+ next_token.item() != self.config.tokenizer.eos_id
423
+ and len(out) < max_objects
424
+ ):
425
+ x_logits = decode_coordinate(hidden, self.region)
426
+ x_center = torch.argmax(x_logits, dim=-1) / x_logits.size(-1)
427
+ next_emb = encode_coordinate(
428
+ x_center.to(dtype=x_logits.dtype), self.region
429
+ ).unsqueeze(0)
430
+
431
+ # Decode y-coordinate
432
+ mask[:, :, pos], pos_ids[0] = 1, pos
433
+ _, hidden = self._decode_one_tok(next_emb, mask, pos_ids)
434
+ pos += 1
435
+ y_logits = decode_coordinate(hidden, self.region)
436
+ y_center = torch.argmax(y_logits, dim=-1) / y_logits.size(-1)
437
+ next_emb = encode_coordinate(
438
+ y_center.to(dtype=y_logits.dtype), self.region
439
+ ).unsqueeze(0)
440
+
441
+ # Decode size
442
+ if include_size:
443
+ mask[:, :, pos], pos_ids[0] = 1, pos
444
+ logits, hidden = self._decode_one_tok(next_emb, mask, pos_ids)
445
+ pos += 1
446
+ size_logits = decode_size(hidden, self.region)
447
+
448
+ # Get bin indices from the logits
449
+ w_bin = torch.argmax(size_logits[0], dim=-1)
450
+ h_bin = torch.argmax(size_logits[1], dim=-1)
451
+
452
+ # Convert from bin indices to actual size values using the inverse of the log-scale mapping
453
+ # Formula: size = 2^((bin / 1023.0) * 10.0 - 10.0)
454
+ w = torch.pow(2.0, (w_bin.float() / 1023.0) * 10.0 - 10.0)
455
+ h = torch.pow(2.0, (h_bin.float() / 1023.0) * 10.0 - 10.0)
456
+
457
+ next_emb = (
458
+ encode_size(
459
+ torch.tensor(
460
+ [w, h], device=self.device, dtype=size_logits.dtype
461
+ ),
462
+ self.region,
463
+ )
464
+ .unsqueeze(0)
465
+ .unsqueeze(0)
466
+ )
467
+
468
+ # Add object
469
+ out.append(
470
+ {
471
+ "x_min": x_center.item() - w.item() / 2,
472
+ "y_min": y_center.item() - h.item() / 2,
473
+ "x_max": x_center.item() + w.item() / 2,
474
+ "y_max": y_center.item() + h.item() / 2,
475
+ }
476
+ )
477
+ else:
478
+ out.append({"x": x_center.item(), "y": y_center.item()})
479
+
480
+ # Decode next token (x-coordinate, or eos)
481
+ mask[:, :, pos], pos_ids[0] = 1, pos
482
+ logits, hidden = self._decode_one_tok(next_emb, mask, pos_ids)
483
+ pos += 1
484
+ next_token = torch.argmax(logits, dim=-1)
485
+
486
+ return out
487
+
488
+ def detect(
489
+ self,
490
+ image: Union[Image.Image, EncodedImage],
491
+ object: str,
492
+ settings: Optional[ObjectSamplingSettings] = None,
493
+ ):
494
+ if self.config.tokenizer.templates["detect"] is None:
495
+ raise NotImplementedError("Model does not support object detection.")
496
+
497
+ image = self.encode_image(image)
498
+ self.load_encoded_image(image)
499
+
500
+ prompt_tokens = torch.tensor(
501
+ [
502
+ self.config.tokenizer.templates["detect"]["prefix"]
503
+ + self.tokenizer.encode(" " + object).ids
504
+ + self.config.tokenizer.templates["detect"]["suffix"]
505
+ ],
506
+ device=self.device,
507
+ )
508
+
509
+ _, hidden, next_token, pos = self._prefill_prompt(
510
+ prompt_tokens, image.pos, temperature=0, top_p=0
511
+ )
512
+ hidden = hidden[:, -1:, :]
513
+
514
+ max_objects = (
515
+ settings.get("max_objects", DEFAULT_MAX_OBJECTS)
516
+ if settings
517
+ else DEFAULT_MAX_OBJECTS
518
+ )
519
+ objects = self._generate_points(
520
+ hidden, next_token, pos, include_size=True, max_objects=max_objects
521
+ )
522
+
523
+ return {"objects": objects}
524
+
525
+ def point(
526
+ self,
527
+ image: Union[Image.Image, EncodedImage],
528
+ object: str,
529
+ settings: Optional[ObjectSamplingSettings] = None,
530
+ ):
531
+ if self.config.tokenizer.templates["point"] is None:
532
+ raise NotImplementedError("Model does not support pointing.")
533
+
534
+ image = self.encode_image(image)
535
+ self.load_encoded_image(image)
536
+
537
+ prompt_tokens = torch.tensor(
538
+ [
539
+ self.config.tokenizer.templates["point"]["prefix"]
540
+ + self.tokenizer.encode(" " + object).ids
541
+ + self.config.tokenizer.templates["point"]["suffix"]
542
+ ],
543
+ device=self.device,
544
+ )
545
+
546
+ _, hidden, next_token, pos = self._prefill_prompt(
547
+ prompt_tokens, image.pos, temperature=0, top_p=0
548
+ )
549
+ hidden = hidden[:, -1:, :]
550
+
551
+ max_objects = (
552
+ settings.get("max_objects", DEFAULT_MAX_OBJECTS)
553
+ if settings
554
+ else DEFAULT_MAX_OBJECTS
555
+ )
556
+ objects = self._generate_points(
557
+ hidden, next_token, pos, include_size=False, max_objects=max_objects
558
+ )
559
+
560
+ return {"points": objects}
561
+
562
+ def _detect_gaze(
563
+ self,
564
+ image: EncodedImage,
565
+ source: Tuple[float, float],
566
+ force_detect: bool = False,
567
+ ):
568
+ with torch.inference_mode():
569
+ before_emb = text_encoder(
570
+ torch.tensor(
571
+ [self.tokenizer.encode("\n\nPoint:").ids], device=self.device
572
+ ),
573
+ self.text,
574
+ )
575
+ after_emb = text_encoder(
576
+ torch.tensor(
577
+ [self.tokenizer.encode(" gaze\n\n").ids], device=self.device
578
+ ),
579
+ self.text,
580
+ )
581
+ x_emb = encode_coordinate(
582
+ torch.tensor([[[source[0]]]], device=self.device, dtype=torch.float16),
583
+ self.region,
584
+ )
585
+ y_emb = encode_coordinate(
586
+ torch.tensor([[[source[1]]]], device=self.device, dtype=torch.float16),
587
+ self.region,
588
+ )
589
+
590
+ prompt_emb = torch.cat([before_emb, x_emb, y_emb, after_emb], dim=1)
591
+
592
+ self.load_encoded_image(image)
593
+
594
+ mask = self.attn_mask[:, :, image.pos : image.pos + prompt_emb.size(1), :]
595
+ pos_ids = torch.arange(
596
+ image.pos, image.pos + prompt_emb.size(1), dtype=torch.long
597
+ )
598
+ hidden = self._prefill(prompt_emb, mask, pos_ids)
599
+ logits = lm_head(hidden, self.text)
600
+ next_token = torch.argmax(logits, dim=-1)
601
+ pos = image.pos + prompt_emb.size(1)
602
+ hidden = hidden[:, -1:, :]
603
+
604
+ if force_detect:
605
+ next_token = torch.tensor([[0]], device=self.device)
606
+
607
+ if next_token.item() == self.config.tokenizer.eos_id:
608
+ return None
609
+
610
+ gaze = self._generate_points(
611
+ hidden, next_token, pos, include_size=False, max_objects=1
612
+ )
613
+ return gaze[0]
614
+
615
+ def detect_gaze(
616
+ self,
617
+ image: Union[Image.Image, EncodedImage],
618
+ eye: Optional[Tuple[float, float]] = None,
619
+ face: Optional[Dict[str, float]] = None,
620
+ unstable_settings: Dict[str, Any] = {},
621
+ ):
622
+ if "force_detect" in unstable_settings:
623
+ force_detect = unstable_settings["force_detect"]
624
+ else:
625
+ force_detect = False
626
+
627
+ if "prioritize_accuracy" in unstable_settings:
628
+ prioritize_accuracy = unstable_settings["prioritize_accuracy"]
629
+ else:
630
+ prioritize_accuracy = False
631
+
632
+ if not prioritize_accuracy:
633
+ if eye is None:
634
+ raise ValueError("eye must be provided when prioritize_accuracy=False")
635
+ image = self.encode_image(image)
636
+ return {"gaze": self._detect_gaze(image, eye, force_detect=force_detect)}
637
+ else:
638
+ if (
639
+ not isinstance(image, Image.Image)
640
+ and "flip_enc_img" not in unstable_settings
641
+ ):
642
+ raise ValueError(
643
+ "image must be a PIL Image when prioritize_accuracy=True, "
644
+ "or flip_enc_img must be provided"
645
+ )
646
+ if face is None:
647
+ raise ValueError("face must be provided when prioritize_accuracy=True")
648
+
649
+ encoded_image = self.encode_image(image)
650
+ if (
651
+ isinstance(image, Image.Image)
652
+ and "flip_enc_img" not in unstable_settings
653
+ ):
654
+ flipped_pil = image.copy()
655
+ flipped_pil = flipped_pil.transpose(method=Image.FLIP_LEFT_RIGHT)
656
+ encoded_flipped_image = self.encode_image(flipped_pil)
657
+ else:
658
+ encoded_flipped_image = unstable_settings["flip_enc_img"]
659
+
660
+ N = 10
661
+
662
+ detections = [
663
+ self._detect_gaze(
664
+ encoded_image,
665
+ (
666
+ random.uniform(face["x_min"], face["x_max"]),
667
+ random.uniform(face["y_min"], face["y_max"]),
668
+ ),
669
+ force_detect=force_detect,
670
+ )
671
+ for _ in range(N)
672
+ ]
673
+ detections = [
674
+ (gaze["x"], gaze["y"]) for gaze in detections if gaze is not None
675
+ ]
676
+ flipped_detections = [
677
+ self._detect_gaze(
678
+ encoded_flipped_image,
679
+ (
680
+ 1 - random.uniform(face["x_min"], face["x_max"]),
681
+ random.uniform(face["y_min"], face["y_max"]),
682
+ ),
683
+ force_detect=force_detect,
684
+ )
685
+ for _ in range(N)
686
+ ]
687
+ detections.extend(
688
+ [
689
+ (1 - gaze["x"], gaze["y"])
690
+ for gaze in flipped_detections
691
+ if gaze is not None
692
+ ]
693
+ )
694
+
695
+ if len(detections) < N:
696
+ return {"gaze": None}
697
+
698
+ detections = remove_outlier_points(detections)
699
+ mean_gaze = (
700
+ sum(gaze[0] for gaze in detections) / len(detections),
701
+ sum(gaze[1] for gaze in detections) / len(detections),
702
+ )
703
+
704
+ return {"gaze": {"x": mean_gaze[0], "y": mean_gaze[1]}}
705
+
706
+
707
+ def _is_cjk_char(cp):
708
+ """Checks whether CP is the codepoint of a CJK character."""
709
+ # This defines a "chinese character" as anything in the CJK Unicode block:
710
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
711
+ if (
712
+ (cp >= 0x4E00 and cp <= 0x9FFF)
713
+ or (cp >= 0x3400 and cp <= 0x4DBF)
714
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
715
+ ):
716
+ return True
717
+ return False
region.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import math
4
+
5
+ from .layers import linear, mlp
6
+
7
+
8
+ def fourier_features(x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
9
+ """
10
+ Applies Fourier feature mapping to input tensor x using frequency matrix w. This
11
+ projects inputs through sinusoidal functions to create higher dimensional features
12
+ that help mitigate spectral bias - the tendency of neural networks to learn
13
+ low-frequency functions more easily than high-frequency ones. By explicitly
14
+ mapping inputs to higher frequencies through sin/cos transformations, we enable
15
+ better learning of fine details and higher frequency patterns.
16
+
17
+ Args:
18
+ x: Input tensor to transform
19
+ w: Matrix of frequencies for the Fourier features transformation
20
+
21
+ Returns:
22
+ Concatenated cosine and sine transformed features as a tensor
23
+ """
24
+ f = 2 * math.pi * x @ w
25
+ return torch.cat([f.cos(), f.sin()], dim=-1)
26
+
27
+
28
+ def encode_coordinate(coord: torch.Tensor, w: nn.Module) -> torch.Tensor:
29
+ """
30
+ Takes as input a tensor containing a single float coordinate value (x or y)
31
+ and encodes it into hidden states for input to the text model.
32
+
33
+ Args:
34
+ coord: Tensor with single float coordinate value
35
+
36
+ Returns:
37
+ Encoded hidden states tensor for input to text model
38
+ """
39
+ return linear(fourier_features(coord, w.coord_features), w.coord_encoder)
40
+
41
+
42
+ def decode_coordinate(hidden_state: torch.Tensor, w: nn.Module) -> torch.Tensor:
43
+ """
44
+ Takes as input the last hidden state from the text model and outputs a single logit
45
+ representing either an x or y coordinate prediction.
46
+
47
+ Args:
48
+ hidden_state: The final hidden state tensor from the text model.
49
+
50
+ Returns:
51
+ A single logit representing the predicted coordinate value (x or y)
52
+ """
53
+ return mlp(hidden_state, w.coord_decoder)
54
+
55
+
56
+ def encode_size(size: torch.Tensor, w: nn.Module) -> torch.Tensor:
57
+ """
58
+ Takes a tensor containing width and height values and encodes them into
59
+ hidden states for input to the text model.
60
+
61
+ Args:
62
+ size: Tensor with two floats for width and height
63
+
64
+ Returns:
65
+ Encoded hidden states tensor for input to text model
66
+ """
67
+ return linear(fourier_features(size, w.size_features), w.size_encoder)
68
+
69
+
70
+ def decode_size(hidden_state: torch.Tensor, w: nn.Module) -> torch.Tensor:
71
+ """
72
+ Takes as input the last hidden state from the text model and outputs logits
73
+ for 1024 bins representing width and height in log-scale.
74
+
75
+ The bins are distributed according to the formula:
76
+ bin = (log2(size) + 10.0) / 10.0 * 1023.0
77
+ where size values are clamped to be at least 1/1024.
78
+
79
+ To convert from bin back to size:
80
+ size = 2^((bin / 1023.0) * 10.0 - 10.0)
81
+
82
+ Args:
83
+ hidden_state: The final hidden state tensor from the text model.
84
+
85
+ Returns:
86
+ A tensor containing logits for 1024 bins for width and height.
87
+ Shape is (2, 1024) where the first dimension corresponds to width and height.
88
+ """
89
+ return mlp(hidden_state, w.size_decoder).view(2, -1)
rope.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ethically sourced from https://github.com/xjdr-alt/entropix
2
+
3
+ import torch
4
+
5
+
6
+ def precompute_freqs_cis(
7
+ dim: int,
8
+ end: int,
9
+ theta: float = 10000.0,
10
+ use_scaled: bool = False,
11
+ dtype: torch.dtype = torch.float32,
12
+ ) -> torch.Tensor:
13
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=dtype)[: (dim // 2)] / dim))
14
+ t = torch.arange(end, dtype=dtype).unsqueeze(1)
15
+ freqs = t * freqs.unsqueeze(0)
16
+ freqs = torch.exp(1j * freqs)
17
+ return torch.stack([freqs.real, freqs.imag], dim=-1)
18
+
19
+
20
+ def apply_rotary_emb(
21
+ x: torch.Tensor,
22
+ freqs_cis: torch.Tensor,
23
+ position_ids: torch.Tensor,
24
+ num_heads: int,
25
+ rot_dim: int = 32,
26
+ interleave: bool = False,
27
+ ) -> torch.Tensor:
28
+ assert rot_dim == freqs_cis.shape[-2] * 2
29
+ assert num_heads == x.shape[1]
30
+
31
+ x_rot, x_pass = x[..., :rot_dim], x[..., rot_dim:]
32
+
33
+ if interleave:
34
+ xq_r = x_rot.float().reshape(*x_rot.shape[:-1], -1, 2)[..., 0]
35
+ xq_i = x_rot.float().reshape(*x_rot.shape[:-1], -1, 2)[..., 1]
36
+ else:
37
+ d_q = x_rot.shape[-1] // 2
38
+ xq_r, xq_i = x_rot[..., :d_q], x_rot[..., d_q:]
39
+
40
+ freqs_cos = freqs_cis[..., 0][position_ids, :].unsqueeze(0).unsqueeze(0)
41
+ freqs_sin = freqs_cis[..., 1][position_ids, :].unsqueeze(0).unsqueeze(0)
42
+
43
+ # Complex multiplication: (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
44
+ xq_out_r = xq_r * freqs_cos - xq_i * freqs_sin
45
+ xq_out_i = xq_r * freqs_sin + xq_i * freqs_cos
46
+ xq_out = torch.stack((xq_out_r, xq_out_i), dim=-1).flatten(-2)
47
+
48
+ return torch.cat([xq_out.to(x.dtype), x_pass], dim=-1)
text.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+ from torch.nn import functional as F
5
+
6
+ from .layers import layer_norm, mlp
7
+ from .rope import apply_rotary_emb, precompute_freqs_cis
8
+ from .config import TextConfig
9
+
10
+
11
+ def text_encoder(input_ids: torch.Tensor, w: nn.Module):
12
+ return F.embedding(input_ids, w.wte)
13
+
14
+
15
+ def attn(
16
+ x: torch.Tensor,
17
+ w: nn.Module,
18
+ freqs_cis: torch.Tensor,
19
+ kv_cache: nn.Module,
20
+ attn_mask: torch.Tensor,
21
+ n_heads: int,
22
+ n_kv_heads: int,
23
+ position_ids: torch.Tensor,
24
+ ):
25
+ bsz, q_len, d_model = x.shape
26
+ head_dim = d_model // n_heads
27
+
28
+ qkv_out = w.qkv(x) # shape: (bsz, q_len, (n_heads + 2*n_kv_heads)*head_dim)
29
+ q_dim = n_heads * head_dim
30
+ kv_dim = n_kv_heads * head_dim
31
+
32
+ q = qkv_out[..., :q_dim].view(bsz, q_len, n_heads, head_dim).transpose(1, 2)
33
+ k = (
34
+ qkv_out[..., q_dim : q_dim + kv_dim]
35
+ .view(bsz, q_len, n_kv_heads, head_dim)
36
+ .transpose(1, 2)
37
+ )
38
+ v = (
39
+ qkv_out[..., q_dim + kv_dim :]
40
+ .view(bsz, q_len, n_kv_heads, head_dim)
41
+ .transpose(1, 2)
42
+ )
43
+
44
+ q = apply_rotary_emb(q, freqs_cis, position_ids, n_heads)
45
+ k = apply_rotary_emb(k, freqs_cis, position_ids, n_kv_heads)
46
+
47
+ if kv_cache is not None:
48
+ k, v = kv_cache.update(position_ids, k, v)
49
+
50
+ out = F.scaled_dot_product_attention(
51
+ q, k, v, attn_mask=attn_mask, enable_gqa=n_heads != n_kv_heads
52
+ )
53
+ out = out.transpose(1, 2).reshape(bsz, q_len, d_model)
54
+ out = w.proj(out)
55
+ return out
56
+
57
+
58
+ def _attn(
59
+ x: torch.Tensor,
60
+ w: torch.Tensor,
61
+ freqs_cis: torch.Tensor,
62
+ attn_mask: torch.Tensor,
63
+ n_heads: int,
64
+ n_kv_heads: int,
65
+ ):
66
+ bsz, q_len, d_model = x.shape
67
+ head_dim = d_model // n_heads
68
+ pos = 0
69
+
70
+ qkv_out = w.qkv(x) # shape: (bsz, q_len, (n_heads + 2*n_kv_heads)*head_dim)
71
+ q_dim = n_heads * head_dim
72
+ kv_dim = n_kv_heads * head_dim
73
+
74
+ q = qkv_out[..., :q_dim].view(bsz, q_len, n_heads, head_dim).transpose(1, 2)
75
+ k = (
76
+ qkv_out[..., q_dim : q_dim + kv_dim]
77
+ .view(bsz, q_len, n_kv_heads, head_dim)
78
+ .transpose(1, 2)
79
+ )
80
+ v = (
81
+ qkv_out[..., q_dim + kv_dim :]
82
+ .view(bsz, q_len, n_kv_heads, head_dim)
83
+ .transpose(1, 2)
84
+ )
85
+
86
+ position_ids = torch.arange(pos, pos + q_len, dtype=torch.long)
87
+ q = apply_rotary_emb(q, freqs_cis, position_ids, n_heads)
88
+ k = apply_rotary_emb(k, freqs_cis, position_ids, n_kv_heads)
89
+ out = F.scaled_dot_product_attention(
90
+ q, k, v, attn_mask=attn_mask, enable_gqa=n_heads != n_kv_heads
91
+ )
92
+ out = out.transpose(1, 2).reshape(bsz, q_len, d_model)
93
+ out = w.proj(out)
94
+ return out
95
+
96
+
97
+ def _produce_hidden(inputs_embeds: torch.Tensor, w: nn.Module, config: TextConfig):
98
+ hidden_BTC = inputs_embeds
99
+
100
+ bsz, q_len, d_model = inputs_embeds.shape
101
+ attn_mask = torch.zeros(q_len, q_len)
102
+ attn_mask[:730, :730] = 1
103
+ for i in range(730, q_len):
104
+ attn_mask[i, : i + 1] = 1
105
+ attn_mask = attn_mask.to(dtype=torch.bool)
106
+
107
+ for i, block in enumerate(w.blocks):
108
+ l_in = layer_norm(hidden_BTC, block.ln)
109
+ l_attn = _attn(
110
+ x=l_in,
111
+ w=block.attn,
112
+ freqs_cis=w.freqs_cis,
113
+ attn_mask=attn_mask,
114
+ n_heads=config.n_heads,
115
+ n_kv_heads=config.n_kv_heads,
116
+ )
117
+ l_mlp = mlp(l_in, block.mlp)
118
+ hidden_BTC = hidden_BTC + l_attn + l_mlp
119
+
120
+ return hidden_BTC
121
+
122
+
123
+ def text_decoder(
124
+ x: torch.Tensor,
125
+ w: nn.Module,
126
+ attn_mask: torch.Tensor,
127
+ position_ids: torch.Tensor,
128
+ config: TextConfig,
129
+ ):
130
+ for i, block in enumerate(w.blocks):
131
+ l_in = layer_norm(x, block.ln)
132
+ l_attn = attn(
133
+ l_in,
134
+ block.attn,
135
+ freqs_cis=w.freqs_cis,
136
+ kv_cache=block.kv_cache,
137
+ attn_mask=attn_mask,
138
+ n_heads=config.n_heads,
139
+ n_kv_heads=config.n_kv_heads,
140
+ position_ids=position_ids,
141
+ )
142
+ l_mlp = mlp(l_in, block.mlp)
143
+ x = x + l_attn + l_mlp
144
+
145
+ return x
146
+
147
+
148
+ def lm_head(hidden_BTC: torch.Tensor, w: nn.Module):
149
+ hidden_BC = hidden_BTC[:, -1, :]
150
+ hidden_BC = layer_norm(hidden_BC, w.post_ln)
151
+ logits = w.lm_head(hidden_BC)
152
+ return logits
153
+
154
+
155
+ def _lm_head(hidden_BTC: torch.Tensor, w: nn.Module):
156
+ hidden_BTC = layer_norm(hidden_BTC, w.post_ln)
157
+ logits = w.lm_head(hidden_BTC)
158
+ return logits
159
+
160
+
161
+ def build_text_model(config: TextConfig, dtype: torch.dtype) -> nn.Module:
162
+ qkv_dim = int(config.dim * (1 + 2 * config.n_kv_heads / config.n_heads))
163
+
164
+ text = nn.ModuleDict(
165
+ {
166
+ "blocks": nn.ModuleList(
167
+ [
168
+ nn.ModuleDict(
169
+ {
170
+ "ln": nn.LayerNorm(config.dim, dtype=dtype),
171
+ "attn": nn.ModuleDict(
172
+ {
173
+ "qkv": nn.Linear(config.dim, qkv_dim, dtype=dtype),
174
+ "proj": nn.Linear(
175
+ config.dim, config.dim, dtype=dtype
176
+ ),
177
+ }
178
+ ),
179
+ "mlp": nn.ModuleDict(
180
+ {
181
+ "fc1": nn.Linear(
182
+ config.dim, config.ff_dim, dtype=dtype
183
+ ),
184
+ "fc2": nn.Linear(
185
+ config.ff_dim, config.dim, dtype=dtype
186
+ ),
187
+ }
188
+ ),
189
+ }
190
+ )
191
+ for _ in range(config.n_layers)
192
+ ]
193
+ ),
194
+ "post_ln": nn.LayerNorm(config.dim, dtype=dtype),
195
+ "lm_head": nn.Linear(config.dim, config.vocab_size, dtype=dtype),
196
+ }
197
+ )
198
+ text.wte = nn.Parameter(torch.empty(config.vocab_size, config.dim, dtype=dtype))
199
+ text.register_buffer(
200
+ "freqs_cis",
201
+ precompute_freqs_cis(config.dim // (2 * config.n_heads), config.max_context),
202
+ persistent=False,
203
+ )
204
+
205
+ return text
utils.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+
4
+ def remove_outlier_points(points_tuples, k_nearest=2, threshold=2.0):
5
+ """
6
+ Robust outlier detection for list of (x,y) tuples.
7
+ Only requires numpy.
8
+
9
+ Args:
10
+ points_tuples: list of (x,y) tuples
11
+ k_nearest: number of neighbors to consider
12
+ threshold: multiplier for median distance
13
+
14
+ Returns:
15
+ list: filtered list of (x,y) tuples with outliers removed
16
+ list: list of booleans indicating which points were kept (True = kept)
17
+ """
18
+ points = np.array(points_tuples)
19
+ n_points = len(points)
20
+
21
+ # Calculate pairwise distances manually
22
+ dist_matrix = np.zeros((n_points, n_points))
23
+ for i in range(n_points):
24
+ for j in range(i + 1, n_points):
25
+ # Euclidean distance between points i and j
26
+ dist = np.sqrt(np.sum((points[i] - points[j]) ** 2))
27
+ dist_matrix[i, j] = dist
28
+ dist_matrix[j, i] = dist
29
+
30
+ # Get k nearest neighbors' distances
31
+ k = min(k_nearest, n_points - 1)
32
+ neighbor_distances = np.partition(dist_matrix, k, axis=1)[:, :k]
33
+ avg_neighbor_dist = np.mean(neighbor_distances, axis=1)
34
+
35
+ # Calculate mask using median distance
36
+ median_dist = np.median(avg_neighbor_dist)
37
+ mask = avg_neighbor_dist <= threshold * median_dist
38
+
39
+ # Return filtered tuples and mask
40
+ filtered_tuples = [t for t, m in zip(points_tuples, mask) if m]
41
+ return filtered_tuples
vision.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+
6
+ from typing import Union, Tuple
7
+ from PIL import Image
8
+
9
+ from .layers import attn, layer_norm, linear, mlp
10
+ from .image_crops import overlap_crop_image
11
+ from .config import VisionConfig
12
+
13
+ if torch.backends.mps.is_available():
14
+ # Non-divisible input sizes are not implemented on MPS device yet.
15
+ # https://github.com/pytorch/pytorch/issues/96056
16
+ def adaptive_avg_pool2d(input, output_size):
17
+ return F.adaptive_avg_pool2d(input.to("cpu"), output_size).to("mps")
18
+
19
+ else:
20
+ adaptive_avg_pool2d = F.adaptive_avg_pool2d
21
+
22
+ DeviceLike = Union[str, torch.device, int]
23
+
24
+
25
+ def prepare_crops(
26
+ image: Image.Image, config: VisionConfig, device: DeviceLike
27
+ ) -> Tuple[torch.Tensor, Tuple[int, int]]:
28
+ np_image = np.array(image.convert("RGB"))
29
+ overlap_crops = overlap_crop_image(
30
+ np_image, max_crops=config.max_crops, overlap_margin=config.overlap_margin
31
+ )
32
+ all_crops = overlap_crops["crops"]
33
+ all_crops = np.transpose(all_crops, (0, 3, 1, 2))
34
+ all_crops = (
35
+ torch.from_numpy(all_crops)
36
+ .to(device=device, dtype=torch.float16)
37
+ .div_(255.0)
38
+ .sub_(0.5)
39
+ .div_(0.5)
40
+ )
41
+ return all_crops, overlap_crops["tiling"]
42
+
43
+
44
+ def create_patches(x, patch_size):
45
+ # Original shape: [B, C, H, W]
46
+ B, C, H, W = x.shape
47
+ P1 = P2 = patch_size
48
+
49
+ # Step 1: Split H and W dimensions into patches
50
+ # [B, C, H/P1, P1, W/P2, P2]
51
+ x = x.reshape(B, C, H // P1, P1, W // P2, P2)
52
+
53
+ # Step 2: Rearrange dimensions to match target shape
54
+ # [B, H/P1, W/P2, C, P1, P2]
55
+ x = x.permute(0, 2, 4, 1, 3, 5)
56
+
57
+ # Step 3: Combine dimensions to get final shape
58
+ # [B, (H/P1)*(W/P2), C*P1*P2]
59
+ x = x.reshape(B, (H // P1) * (W // P2), C * P1 * P2)
60
+
61
+ return x
62
+
63
+
64
+ def vision_encoder(input_BCHW: torch.Tensor, w: nn.Module, config: VisionConfig):
65
+ x = create_patches(input_BCHW, config.enc_patch_size)
66
+
67
+ x = linear(x, w.patch_emb)
68
+ x = x + w.pos_emb
69
+ for block in w.blocks:
70
+ x = x + attn(layer_norm(x, block.ln1), block.attn, n_heads=config.enc_n_heads)
71
+ x = x + mlp(layer_norm(x, block.ln2), block.mlp)
72
+ x = layer_norm(x, w.post_ln)
73
+
74
+ return x
75
+
76
+
77
+ def vision_projection(
78
+ global_features: torch.Tensor,
79
+ reconstructed: torch.Tensor,
80
+ w: nn.Module,
81
+ config: VisionConfig,
82
+ ):
83
+ reconstructed = reconstructed.permute(2, 0, 1)
84
+ reconstructed = adaptive_avg_pool2d(
85
+ reconstructed, output_size=(config.enc_n_layers, config.enc_n_layers)
86
+ )
87
+ reconstructed = reconstructed.permute(1, 2, 0).view(729, config.enc_dim)
88
+ final_features = torch.cat([global_features, reconstructed], dim=-1)
89
+ return mlp(final_features, w.proj_mlp)
90
+
91
+
92
+ def build_vision_model(config: VisionConfig, dtype: torch.dtype):
93
+ patch_dim = config.enc_patch_size * config.enc_patch_size * config.in_channels
94
+ grid_size = config.crop_size // config.enc_patch_size
95
+ num_patches = grid_size * grid_size
96
+
97
+ vision = nn.ModuleDict(
98
+ {
99
+ "patch_emb": nn.Linear(patch_dim, config.enc_dim, dtype=dtype),
100
+ "blocks": nn.ModuleList(
101
+ [
102
+ nn.ModuleDict(
103
+ {
104
+ "ln1": nn.LayerNorm(config.enc_dim, dtype=dtype),
105
+ "attn": nn.ModuleDict(
106
+ {
107
+ "qkv": nn.Linear(
108
+ config.enc_dim, 3 * config.enc_dim, dtype=dtype
109
+ ),
110
+ "proj": nn.Linear(
111
+ config.enc_dim, config.enc_dim, dtype=dtype
112
+ ),
113
+ }
114
+ ),
115
+ "ln2": nn.LayerNorm(config.enc_dim, dtype=dtype),
116
+ "mlp": nn.ModuleDict(
117
+ {
118
+ "fc1": nn.Linear(
119
+ config.enc_dim, config.enc_ff_dim, dtype=dtype
120
+ ),
121
+ "fc2": nn.Linear(
122
+ config.enc_ff_dim, config.enc_dim, dtype=dtype
123
+ ),
124
+ }
125
+ ),
126
+ }
127
+ )
128
+ for _ in range(config.enc_n_layers)
129
+ ]
130
+ ),
131
+ "post_ln": nn.LayerNorm(config.enc_dim, dtype=dtype),
132
+ "proj_mlp": nn.ModuleDict(
133
+ {
134
+ "fc1": nn.Linear(
135
+ config.enc_dim * 2, config.proj_inner_dim, dtype=dtype
136
+ ),
137
+ "fc2": nn.Linear(
138
+ config.proj_inner_dim, config.proj_out_dim, dtype=dtype
139
+ ),
140
+ }
141
+ ),
142
+ }
143
+ )
144
+ vision.pos_emb = nn.Parameter(
145
+ torch.zeros(1, num_patches, config.enc_dim, dtype=dtype)
146
+ )
147
+ return vision