inference-models 0.18.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. inference_models/__init__.py +36 -0
  2. inference_models/configuration.py +72 -0
  3. inference_models/constants.py +2 -0
  4. inference_models/entities.py +5 -0
  5. inference_models/errors.py +137 -0
  6. inference_models/logger.py +52 -0
  7. inference_models/model_pipelines/__init__.py +0 -0
  8. inference_models/model_pipelines/auto_loaders/__init__.py +0 -0
  9. inference_models/model_pipelines/auto_loaders/core.py +120 -0
  10. inference_models/model_pipelines/auto_loaders/pipelines_registry.py +36 -0
  11. inference_models/model_pipelines/face_and_gaze_detection/__init__.py +0 -0
  12. inference_models/model_pipelines/face_and_gaze_detection/mediapipe_l2cs.py +200 -0
  13. inference_models/models/__init__.py +0 -0
  14. inference_models/models/auto_loaders/__init__.py +0 -0
  15. inference_models/models/auto_loaders/access_manager.py +168 -0
  16. inference_models/models/auto_loaders/auto_negotiation.py +1329 -0
  17. inference_models/models/auto_loaders/auto_resolution_cache.py +129 -0
  18. inference_models/models/auto_loaders/constants.py +7 -0
  19. inference_models/models/auto_loaders/core.py +1341 -0
  20. inference_models/models/auto_loaders/dependency_models.py +52 -0
  21. inference_models/models/auto_loaders/entities.py +57 -0
  22. inference_models/models/auto_loaders/models_registry.py +497 -0
  23. inference_models/models/auto_loaders/presentation_utils.py +333 -0
  24. inference_models/models/auto_loaders/ranking.py +413 -0
  25. inference_models/models/auto_loaders/utils.py +31 -0
  26. inference_models/models/base/__init__.py +0 -0
  27. inference_models/models/base/classification.py +123 -0
  28. inference_models/models/base/depth_estimation.py +62 -0
  29. inference_models/models/base/documents_parsing.py +111 -0
  30. inference_models/models/base/embeddings.py +66 -0
  31. inference_models/models/base/instance_segmentation.py +87 -0
  32. inference_models/models/base/keypoints_detection.py +93 -0
  33. inference_models/models/base/object_detection.py +143 -0
  34. inference_models/models/base/semantic_segmentation.py +74 -0
  35. inference_models/models/base/types.py +5 -0
  36. inference_models/models/clip/__init__.py +0 -0
  37. inference_models/models/clip/clip_onnx.py +148 -0
  38. inference_models/models/clip/clip_pytorch.py +104 -0
  39. inference_models/models/clip/preprocessing.py +162 -0
  40. inference_models/models/common/__init__.py +0 -0
  41. inference_models/models/common/cuda.py +30 -0
  42. inference_models/models/common/model_packages.py +25 -0
  43. inference_models/models/common/onnx.py +379 -0
  44. inference_models/models/common/roboflow/__init__.py +0 -0
  45. inference_models/models/common/roboflow/model_packages.py +361 -0
  46. inference_models/models/common/roboflow/post_processing.py +436 -0
  47. inference_models/models/common/roboflow/pre_processing.py +1332 -0
  48. inference_models/models/common/torch.py +20 -0
  49. inference_models/models/common/trt.py +266 -0
  50. inference_models/models/deep_lab_v3_plus/__init__.py +0 -0
  51. inference_models/models/deep_lab_v3_plus/deep_lab_v3_plus_segmentation_onnx.py +282 -0
  52. inference_models/models/deep_lab_v3_plus/deep_lab_v3_plus_segmentation_torch.py +264 -0
  53. inference_models/models/deep_lab_v3_plus/deep_lab_v3_plus_segmentation_trt.py +313 -0
  54. inference_models/models/depth_anything_v2/__init__.py +0 -0
  55. inference_models/models/depth_anything_v2/depth_anything_v2_hf.py +77 -0
  56. inference_models/models/dinov3/__init__.py +0 -0
  57. inference_models/models/dinov3/dinov3_classification_onnx.py +348 -0
  58. inference_models/models/dinov3/dinov3_classification_torch.py +323 -0
  59. inference_models/models/doctr/__init__.py +0 -0
  60. inference_models/models/doctr/doctr_torch.py +304 -0
  61. inference_models/models/easy_ocr/__init__.py +0 -0
  62. inference_models/models/easy_ocr/easy_ocr_torch.py +222 -0
  63. inference_models/models/florence2/__init__.py +0 -0
  64. inference_models/models/florence2/florence2_hf.py +897 -0
  65. inference_models/models/grounding_dino/__init__.py +0 -0
  66. inference_models/models/grounding_dino/grounding_dino_torch.py +227 -0
  67. inference_models/models/l2cs/__init__.py +0 -0
  68. inference_models/models/l2cs/l2cs_onnx.py +216 -0
  69. inference_models/models/mediapipe_face_detection/__init__.py +0 -0
  70. inference_models/models/mediapipe_face_detection/face_detection.py +203 -0
  71. inference_models/models/moondream2/__init__.py +0 -0
  72. inference_models/models/moondream2/moondream2_hf.py +281 -0
  73. inference_models/models/owlv2/__init__.py +0 -0
  74. inference_models/models/owlv2/cache.py +182 -0
  75. inference_models/models/owlv2/entities.py +112 -0
  76. inference_models/models/owlv2/owlv2_hf.py +695 -0
  77. inference_models/models/owlv2/reference_dataset.py +291 -0
  78. inference_models/models/paligemma/__init__.py +0 -0
  79. inference_models/models/paligemma/paligemma_hf.py +209 -0
  80. inference_models/models/perception_encoder/__init__.py +0 -0
  81. inference_models/models/perception_encoder/perception_encoder_pytorch.py +197 -0
  82. inference_models/models/perception_encoder/vision_encoder/__init__.py +0 -0
  83. inference_models/models/perception_encoder/vision_encoder/config.py +160 -0
  84. inference_models/models/perception_encoder/vision_encoder/pe.py +742 -0
  85. inference_models/models/perception_encoder/vision_encoder/rope.py +344 -0
  86. inference_models/models/perception_encoder/vision_encoder/tokenizer.py +342 -0
  87. inference_models/models/perception_encoder/vision_encoder/transforms.py +33 -0
  88. inference_models/models/qwen25vl/__init__.py +1 -0
  89. inference_models/models/qwen25vl/qwen25vl_hf.py +285 -0
  90. inference_models/models/resnet/__init__.py +0 -0
  91. inference_models/models/resnet/resnet_classification_onnx.py +330 -0
  92. inference_models/models/resnet/resnet_classification_torch.py +305 -0
  93. inference_models/models/resnet/resnet_classification_trt.py +369 -0
  94. inference_models/models/rfdetr/__init__.py +0 -0
  95. inference_models/models/rfdetr/backbone_builder.py +101 -0
  96. inference_models/models/rfdetr/class_remapping.py +41 -0
  97. inference_models/models/rfdetr/common.py +115 -0
  98. inference_models/models/rfdetr/default_labels.py +108 -0
  99. inference_models/models/rfdetr/dinov2_with_windowed_attn.py +1330 -0
  100. inference_models/models/rfdetr/misc.py +26 -0
  101. inference_models/models/rfdetr/ms_deform_attn.py +180 -0
  102. inference_models/models/rfdetr/ms_deform_attn_func.py +60 -0
  103. inference_models/models/rfdetr/position_encoding.py +166 -0
  104. inference_models/models/rfdetr/post_processor.py +83 -0
  105. inference_models/models/rfdetr/projector.py +373 -0
  106. inference_models/models/rfdetr/rfdetr_backbone_pytorch.py +394 -0
  107. inference_models/models/rfdetr/rfdetr_base_pytorch.py +807 -0
  108. inference_models/models/rfdetr/rfdetr_instance_segmentation_onnx.py +206 -0
  109. inference_models/models/rfdetr/rfdetr_instance_segmentation_pytorch.py +373 -0
  110. inference_models/models/rfdetr/rfdetr_instance_segmentation_trt.py +227 -0
  111. inference_models/models/rfdetr/rfdetr_object_detection_onnx.py +244 -0
  112. inference_models/models/rfdetr/rfdetr_object_detection_pytorch.py +470 -0
  113. inference_models/models/rfdetr/rfdetr_object_detection_trt.py +270 -0
  114. inference_models/models/rfdetr/segmentation_head.py +273 -0
  115. inference_models/models/rfdetr/transformer.py +767 -0
  116. inference_models/models/roboflow_instant/__init__.py +0 -0
  117. inference_models/models/roboflow_instant/roboflow_instant_hf.py +141 -0
  118. inference_models/models/sam/__init__.py +0 -0
  119. inference_models/models/sam/cache.py +147 -0
  120. inference_models/models/sam/entities.py +25 -0
  121. inference_models/models/sam/sam_torch.py +675 -0
  122. inference_models/models/sam2/__init__.py +0 -0
  123. inference_models/models/sam2/cache.py +162 -0
  124. inference_models/models/sam2/entities.py +43 -0
  125. inference_models/models/sam2/sam2_torch.py +905 -0
  126. inference_models/models/sam2_rt/__init__.py +0 -0
  127. inference_models/models/sam2_rt/sam2_pytorch.py +119 -0
  128. inference_models/models/smolvlm/__init__.py +0 -0
  129. inference_models/models/smolvlm/smolvlm_hf.py +245 -0
  130. inference_models/models/trocr/__init__.py +0 -0
  131. inference_models/models/trocr/trocr_hf.py +53 -0
  132. inference_models/models/vit/__init__.py +0 -0
  133. inference_models/models/vit/vit_classification_huggingface.py +319 -0
  134. inference_models/models/vit/vit_classification_onnx.py +326 -0
  135. inference_models/models/vit/vit_classification_trt.py +365 -0
  136. inference_models/models/yolact/__init__.py +1 -0
  137. inference_models/models/yolact/yolact_instance_segmentation_onnx.py +336 -0
  138. inference_models/models/yolact/yolact_instance_segmentation_trt.py +361 -0
  139. inference_models/models/yolo_world/__init__.py +1 -0
  140. inference_models/models/yolonas/__init__.py +0 -0
  141. inference_models/models/yolonas/nms.py +44 -0
  142. inference_models/models/yolonas/yolonas_object_detection_onnx.py +204 -0
  143. inference_models/models/yolonas/yolonas_object_detection_trt.py +230 -0
  144. inference_models/models/yolov10/__init__.py +0 -0
  145. inference_models/models/yolov10/yolov10_object_detection_onnx.py +187 -0
  146. inference_models/models/yolov10/yolov10_object_detection_trt.py +215 -0
  147. inference_models/models/yolov11/__init__.py +0 -0
  148. inference_models/models/yolov11/yolov11_onnx.py +28 -0
  149. inference_models/models/yolov11/yolov11_torch_script.py +25 -0
  150. inference_models/models/yolov11/yolov11_trt.py +21 -0
  151. inference_models/models/yolov12/__init__.py +0 -0
  152. inference_models/models/yolov12/yolov12_onnx.py +7 -0
  153. inference_models/models/yolov12/yolov12_torch_script.py +7 -0
  154. inference_models/models/yolov12/yolov12_trt.py +7 -0
  155. inference_models/models/yolov5/__init__.py +0 -0
  156. inference_models/models/yolov5/nms.py +99 -0
  157. inference_models/models/yolov5/yolov5_instance_segmentation_onnx.py +225 -0
  158. inference_models/models/yolov5/yolov5_instance_segmentation_trt.py +255 -0
  159. inference_models/models/yolov5/yolov5_object_detection_onnx.py +192 -0
  160. inference_models/models/yolov5/yolov5_object_detection_trt.py +218 -0
  161. inference_models/models/yolov7/__init__.py +0 -0
  162. inference_models/models/yolov7/yolov7_instance_segmentation_onnx.py +226 -0
  163. inference_models/models/yolov7/yolov7_instance_segmentation_trt.py +253 -0
  164. inference_models/models/yolov8/__init__.py +0 -0
  165. inference_models/models/yolov8/yolov8_classification_onnx.py +181 -0
  166. inference_models/models/yolov8/yolov8_instance_segmentation_onnx.py +239 -0
  167. inference_models/models/yolov8/yolov8_instance_segmentation_torch_script.py +201 -0
  168. inference_models/models/yolov8/yolov8_instance_segmentation_trt.py +268 -0
  169. inference_models/models/yolov8/yolov8_key_points_detection_onnx.py +263 -0
  170. inference_models/models/yolov8/yolov8_key_points_detection_torch_script.py +218 -0
  171. inference_models/models/yolov8/yolov8_key_points_detection_trt.py +287 -0
  172. inference_models/models/yolov8/yolov8_object_detection_onnx.py +213 -0
  173. inference_models/models/yolov8/yolov8_object_detection_torch_script.py +166 -0
  174. inference_models/models/yolov8/yolov8_object_detection_trt.py +231 -0
  175. inference_models/models/yolov9/__init__.py +0 -0
  176. inference_models/models/yolov9/yolov9_onnx.py +7 -0
  177. inference_models/models/yolov9/yolov9_torch_script.py +7 -0
  178. inference_models/models/yolov9/yolov9_trt.py +7 -0
  179. inference_models/runtime_introspection/__init__.py +0 -0
  180. inference_models/runtime_introspection/core.py +410 -0
  181. inference_models/utils/__init__.py +0 -0
  182. inference_models/utils/download.py +608 -0
  183. inference_models/utils/environment.py +28 -0
  184. inference_models/utils/file_system.py +51 -0
  185. inference_models/utils/hashing.py +7 -0
  186. inference_models/utils/imports.py +48 -0
  187. inference_models/utils/onnx_introspection.py +17 -0
  188. inference_models/weights_providers/__init__.py +0 -0
  189. inference_models/weights_providers/core.py +20 -0
  190. inference_models/weights_providers/entities.py +159 -0
  191. inference_models/weights_providers/roboflow.py +601 -0
  192. inference_models-0.18.3.dist-info/METADATA +466 -0
  193. inference_models-0.18.3.dist-info/RECORD +195 -0
  194. inference_models-0.18.3.dist-info/WHEEL +5 -0
  195. inference_models-0.18.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,344 @@
1
+ from math import log, pi
2
+ from typing import Literal, Optional, Union
3
+
4
+ import torch
5
+ from einops import rearrange, repeat
6
+ from torch import Tensor, broadcast_tensors, einsum, nn
7
+ from torch.amp import autocast
8
+ from torch.nn import Module, ModuleList
9
+
10
+ # helper functions
11
+
12
+
13
+ def exists(val):
14
+ return val is not None
15
+
16
+
17
+ def default(val, d):
18
+ return val if exists(val) else d
19
+
20
+
21
+ # broadcat, as tortoise-tts was using it
22
+
23
+
24
+ def broadcat(tensors, dim=-1):
25
+ broadcasted_tensors = broadcast_tensors(*tensors)
26
+ return torch.cat(broadcasted_tensors, dim=dim)
27
+
28
+
29
+ # rotary embedding helper functions
30
+
31
+
32
+ def rotate_half(x):
33
+ x = rearrange(x, "... (d r) -> ... d r", r=2)
34
+ x1, x2 = x.unbind(dim=-1)
35
+ x = torch.stack((-x2, x1), dim=-1)
36
+ return rearrange(x, "... d r -> ... (d r)")
37
+
38
+
39
+ @autocast("cuda", enabled=False)
40
+ def apply_rotary_emb(freqs, t, start_index=0, scale=1.0, seq_dim=-2):
41
+ dtype = t.dtype
42
+
43
+ if t.ndim == 3:
44
+ seq_len = t.shape[seq_dim]
45
+ freqs = freqs[-seq_len:]
46
+
47
+ rot_dim = freqs.shape[-1]
48
+ end_index = start_index + rot_dim
49
+
50
+ assert (
51
+ rot_dim <= t.shape[-1]
52
+ ), f"feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}"
53
+
54
+ t_left, t, t_right = (
55
+ t[..., :start_index],
56
+ t[..., start_index:end_index],
57
+ t[..., end_index:],
58
+ )
59
+ t = (t * freqs.cos() * scale) + (rotate_half(t) * freqs.sin() * scale)
60
+ out = torch.cat((t_left, t, t_right), dim=-1)
61
+
62
+ return out.type(dtype)
63
+
64
+
65
+ # learned rotation helpers
66
+
67
+
68
+ def apply_learned_rotations(rotations, t, start_index=0, freq_ranges=None):
69
+ if exists(freq_ranges):
70
+ rotations = einsum("..., f -> ... f", rotations, freq_ranges)
71
+ rotations = rearrange(rotations, "... r f -> ... (r f)")
72
+
73
+ rotations = repeat(rotations, "... n -> ... (n r)", r=2)
74
+ return apply_rotary_emb(rotations, t, start_index=start_index)
75
+
76
+
77
+ # classes
78
+
79
+
80
+ class RotaryEmbedding(Module):
81
+ def __init__(
82
+ self,
83
+ dim,
84
+ custom_freqs: Optional[Tensor] = None,
85
+ freqs_for: Union[
86
+ Literal["lang"], Literal["pixel"], Literal["constant"]
87
+ ] = "lang",
88
+ theta=10000,
89
+ max_freq=10,
90
+ num_freqs=1,
91
+ learned_freq=False,
92
+ use_xpos=False,
93
+ xpos_scale_base=512,
94
+ interpolate_factor=1.0,
95
+ theta_rescale_factor=1.0,
96
+ seq_before_head_dim=False,
97
+ cache_if_possible=True,
98
+ ):
99
+ super().__init__()
100
+ # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
101
+ # has some connection to NTK literature
102
+ # https://www.reddit.com/r/LocalLLaMA/comments/14lz7j5/ntkaware_scaled_rope_allows_llama_models_to_have/
103
+
104
+ theta *= theta_rescale_factor ** (dim / (dim - 2))
105
+
106
+ self.freqs_for = freqs_for
107
+
108
+ if exists(custom_freqs):
109
+ freqs = custom_freqs
110
+ elif freqs_for == "lang":
111
+ freqs = 1.0 / (
112
+ theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)
113
+ )
114
+ elif freqs_for == "pixel":
115
+ freqs = torch.linspace(1.0, max_freq / 2, dim // 2) * pi
116
+ elif freqs_for == "constant":
117
+ freqs = torch.ones(num_freqs).float()
118
+
119
+ self.cache_if_possible = cache_if_possible
120
+
121
+ self.tmp_store("cached_freqs", None)
122
+ self.tmp_store("cached_scales", None)
123
+
124
+ self.freqs = nn.Parameter(freqs, requires_grad=learned_freq)
125
+
126
+ self.learned_freq = learned_freq
127
+
128
+ # dummy for device
129
+
130
+ self.tmp_store("dummy", torch.tensor(0))
131
+
132
+ # default sequence dimension
133
+
134
+ self.seq_before_head_dim = seq_before_head_dim
135
+ self.default_seq_dim = -3 if seq_before_head_dim else -2
136
+
137
+ # interpolation factors
138
+
139
+ assert interpolate_factor >= 1.0
140
+ self.interpolate_factor = interpolate_factor
141
+
142
+ # xpos
143
+
144
+ self.use_xpos = use_xpos
145
+ if not use_xpos:
146
+ self.tmp_store("scale", None)
147
+ return
148
+
149
+ scale = (torch.arange(0, dim, 2) + 0.4 * dim) / (1.4 * dim)
150
+
151
+ self.scale_base = xpos_scale_base
152
+ self.tmp_store("scale", scale)
153
+
154
+ # add apply_rotary_emb as static method
155
+
156
+ self.apply_rotary_emb = staticmethod(apply_rotary_emb)
157
+
158
+ @property
159
+ def device(self):
160
+ return self.dummy.device
161
+
162
+ def tmp_store(self, key, value):
163
+ self.register_buffer(key, value, persistent=False)
164
+
165
+ def get_seq_pos(self, seq_len, device, dtype, offset=0):
166
+ return (
167
+ torch.arange(seq_len, device=device, dtype=dtype) + offset
168
+ ) / self.interpolate_factor
169
+
170
+ def rotate_queries_or_keys(self, t, seq_dim=None, offset=0):
171
+ seq_dim = default(seq_dim, self.default_seq_dim)
172
+
173
+ assert (
174
+ not self.use_xpos
175
+ ), "you must use `.rotate_queries_and_keys` method instead and pass in both queries and keys, for length extrapolatable rotary embeddings"
176
+
177
+ device, dtype, seq_len = t.device, t.dtype, t.shape[seq_dim]
178
+
179
+ freqs = self.forward(
180
+ self.get_seq_pos(seq_len, device=device, dtype=dtype, offset=offset),
181
+ seq_len=seq_len,
182
+ offset=offset,
183
+ )
184
+
185
+ if seq_dim == -3:
186
+ freqs = rearrange(freqs, "n d -> n 1 d")
187
+
188
+ return apply_rotary_emb(freqs, t, seq_dim=seq_dim)
189
+
190
+ def rotate_queries_with_cached_keys(self, q, k, seq_dim=None, offset=0):
191
+ seq_dim = default(seq_dim, self.default_seq_dim)
192
+
193
+ q_len, k_len = q.shape[seq_dim], k.shape[seq_dim]
194
+ assert q_len <= k_len
195
+
196
+ rotated_q = self.rotate_queries_or_keys(
197
+ q, seq_dim=seq_dim, offset=k_len - q_len + offset
198
+ )
199
+ rotated_k = self.rotate_queries_or_keys(k, seq_dim=seq_dim, offset=offset)
200
+
201
+ rotated_q = rotated_q.type(q.dtype)
202
+ rotated_k = rotated_k.type(k.dtype)
203
+
204
+ return rotated_q, rotated_k
205
+
206
+ def rotate_queries_and_keys(self, q, k, seq_dim=None):
207
+ seq_dim = default(seq_dim, self.default_seq_dim)
208
+
209
+ assert self.use_xpos
210
+ device, dtype, seq_len = q.device, q.dtype, q.shape[seq_dim]
211
+
212
+ seq = self.get_seq_pos(seq_len, dtype=dtype, device=device)
213
+
214
+ freqs = self.forward(seq, seq_len=seq_len)
215
+ scale = self.get_scale(seq, seq_len=seq_len).to(dtype)
216
+
217
+ if seq_dim == -3:
218
+ freqs = rearrange(freqs, "n d -> n 1 d")
219
+ scale = rearrange(scale, "n d -> n 1 d")
220
+
221
+ rotated_q = apply_rotary_emb(freqs, q, scale=scale, seq_dim=seq_dim)
222
+ rotated_k = apply_rotary_emb(freqs, k, scale=scale**-1, seq_dim=seq_dim)
223
+
224
+ rotated_q = rotated_q.type(q.dtype)
225
+ rotated_k = rotated_k.type(k.dtype)
226
+
227
+ return rotated_q, rotated_k
228
+
229
+ def get_scale(self, t: Tensor, seq_len: Optional[int] = None, offset=0):
230
+ assert self.use_xpos
231
+
232
+ should_cache = self.cache_if_possible and exists(seq_len)
233
+
234
+ if (
235
+ should_cache
236
+ and exists(self.cached_scales)
237
+ and (seq_len + offset) <= self.cached_scales.shape[0]
238
+ ):
239
+ return self.cached_scales[offset : (offset + seq_len)]
240
+
241
+ scale = 1.0
242
+ if self.use_xpos:
243
+ power = (t - len(t) // 2) / self.scale_base
244
+ scale = self.scale ** rearrange(power, "n -> n 1")
245
+ scale = torch.cat((scale, scale), dim=-1)
246
+
247
+ if should_cache:
248
+ self.tmp_store("cached_scales", scale)
249
+
250
+ return scale
251
+
252
+ def get_axial_freqs(self, *dims):
253
+ Colon = slice(None)
254
+ all_freqs = []
255
+
256
+ for ind, dim in enumerate(dims):
257
+ if self.freqs_for == "pixel":
258
+ pos = torch.linspace(-1, 1, steps=dim, device=self.device)
259
+ else:
260
+ pos = torch.arange(dim, device=self.device)
261
+
262
+ freqs = self.forward(pos, seq_len=dim)
263
+
264
+ all_axis = [None] * len(dims)
265
+ all_axis[ind] = Colon
266
+
267
+ new_axis_slice = (Ellipsis, *all_axis, Colon)
268
+ all_freqs.append(freqs[new_axis_slice])
269
+
270
+ all_freqs = broadcast_tensors(*all_freqs)
271
+ return torch.cat(all_freqs, dim=-1)
272
+
273
+ @autocast("cuda", enabled=False)
274
+ def forward(self, t: Tensor, seq_len=None, offset=0):
275
+ should_cache = (
276
+ self.cache_if_possible
277
+ and not self.learned_freq
278
+ and exists(seq_len)
279
+ and self.freqs_for != "pixel"
280
+ )
281
+
282
+ if (
283
+ should_cache
284
+ and exists(self.cached_freqs)
285
+ and (offset + seq_len) <= self.cached_freqs.shape[0]
286
+ ):
287
+ return self.cached_freqs[offset : (offset + seq_len)].detach()
288
+
289
+ freqs = self.freqs
290
+
291
+ freqs = einsum("..., f -> ... f", t.type(freqs.dtype), freqs)
292
+ freqs = repeat(freqs, "... n -> ... (n r)", r=2)
293
+
294
+ if should_cache:
295
+ self.tmp_store("cached_freqs", freqs.detach())
296
+
297
+ return freqs
298
+
299
+
300
+ class Rope2D:
301
+ """Helper class to apply RoPE2D as well as interpolate on the fly."""
302
+
303
+ def __init__(self, dim, use_cls_token=False):
304
+ self.dim = dim
305
+ self.use_cls_token = use_cls_token
306
+ self.grid_size = None
307
+ self.freq = None
308
+
309
+ def init_tensors(self):
310
+ self.rope = RotaryEmbedding(self.dim // 2)
311
+
312
+ def update_grid(self, device, grid_h, grid_w):
313
+ if self.grid_size != (grid_h, grid_w):
314
+ self.grid_size = (grid_h, grid_w)
315
+
316
+ self.rope = self.rope.to(device)
317
+
318
+ if self.use_cls_token:
319
+ # +1 to leave space for the cls token to be (0, 0)
320
+ grid_y_range = torch.arange(grid_h, device=device) + 1
321
+ grid_x_range = torch.arange(grid_w, device=device) + 1
322
+ else:
323
+ grid_y_range = torch.arange(grid_h, device=device)
324
+ grid_x_range = torch.arange(grid_w, device=device)
325
+
326
+ freqs_y = self.rope(grid_y_range)[:, None].expand(grid_h, grid_w, -1)
327
+ freqs_x = self.rope(grid_x_range)[None, :].expand(grid_h, grid_w, -1)
328
+ freq = torch.cat([freqs_x, freqs_y], dim=-1).reshape(grid_h * grid_w, -1)
329
+
330
+ if self.use_cls_token:
331
+ freq = torch.cat(
332
+ [torch.zeros(1, freq.shape[-1], device=device), freq], dim=0
333
+ )
334
+
335
+ self.freq = freq[None, ...]
336
+
337
+ self.freq = self.freq.to(device)
338
+
339
+ def __call__(self, q, k):
340
+ # batch, heads, seq, dim = q.shape
341
+ q = apply_rotary_emb(self.freq[:, None, :, :], q)
342
+ k = apply_rotary_emb(self.freq[:, None, :, :], k)
343
+
344
+ return q, k
@@ -0,0 +1,342 @@
1
+ """CLIP tokenizer
2
+
3
+ Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
4
+ """
5
+
6
+ import gzip
7
+ import html
8
+ import os
9
+ import random
10
+ import string
11
+ from functools import lru_cache, partial
12
+ from typing import Callable, List, Optional, Union
13
+
14
+ import ftfy
15
+ import numpy as np
16
+ import regex as re
17
+ import torch
18
+
19
+ # https://stackoverflow.com/q/62691279
20
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
21
+
22
+ DEFAULT_CONTEXT_LENGTH = 77 # default context length for OpenAI CLIP
23
+
24
+
25
+ @lru_cache()
26
+ def default_bpe():
27
+ return os.path.join(
28
+ os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz"
29
+ )
30
+
31
+
32
+ @lru_cache()
33
+ def bytes_to_unicode():
34
+ """
35
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
36
+ The reversible bpe codes work on unicode strings.
37
+ This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
38
+ When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
39
+ This is a significant percentage of your normal, say, 32K bpe vocab.
40
+ To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
41
+ And avoids mapping to whitespace/control characters the bpe code barfs on.
42
+ """
43
+ bs = (
44
+ list(range(ord("!"), ord("~") + 1))
45
+ + list(range(ord("¡"), ord("¬") + 1))
46
+ + list(range(ord("®"), ord("ÿ") + 1))
47
+ )
48
+ cs = bs[:]
49
+ n = 0
50
+ for b in range(2**8):
51
+ if b not in bs:
52
+ bs.append(b)
53
+ cs.append(2**8 + n)
54
+ n += 1
55
+ cs = [chr(n) for n in cs]
56
+ return dict(zip(bs, cs))
57
+
58
+
59
+ def get_pairs(word):
60
+ """Return set of symbol pairs in a word.
61
+ Word is represented as tuple of symbols (symbols being variable-length strings).
62
+ """
63
+ pairs = set()
64
+ prev_char = word[0]
65
+ for char in word[1:]:
66
+ pairs.add((prev_char, char))
67
+ prev_char = char
68
+ return pairs
69
+
70
+
71
+ def basic_clean(text):
72
+ text = ftfy.fix_text(text)
73
+ text = html.unescape(html.unescape(text))
74
+ return text.strip()
75
+
76
+
77
+ def whitespace_clean(text):
78
+ text = re.sub(r"\s+", " ", text)
79
+ text = text.strip()
80
+ return text
81
+
82
+
83
+ def _clean_canonicalize(x):
84
+ # basic, remove whitespace, remove punctuation, lower case
85
+ return canonicalize_text(basic_clean(x))
86
+
87
+
88
+ def _clean_lower(x):
89
+ # basic, remove whitespace, lower case
90
+ return whitespace_clean(basic_clean(x)).lower()
91
+
92
+
93
+ def _clean_whitespace(x):
94
+ # basic, remove whitespace
95
+ return whitespace_clean(basic_clean(x))
96
+
97
+
98
+ def get_clean_fn(type: str):
99
+ if type == "canonicalize":
100
+ return _clean_canonicalize
101
+ elif type == "lower":
102
+ return _clean_lower
103
+ elif type == "whitespace":
104
+ return _clean_whitespace
105
+ else:
106
+ assert False, f"Invalid clean function ({type})."
107
+
108
+
109
+ def canonicalize_text(text, *, keep_punctuation_exact_string=None):
110
+ """Returns canonicalized `text` (lowercase and punctuation removed).
111
+
112
+ From: https://github.com/google-research/big_vision/blob/53f18caf27a9419231bbf08d3388b07671616d3d/big_vision/evaluators/proj/image_text/prompt_engineering.py#L94
113
+
114
+ Args:
115
+ text: string to be canonicalized.
116
+ keep_punctuation_exact_string: If provided, then this exact string kept.
117
+ For example providing '{}' will keep any occurrences of '{}' (but will
118
+ still remove '{' and '}' that appear separately).
119
+ """
120
+ text = text.replace("_", " ")
121
+ if keep_punctuation_exact_string:
122
+ text = keep_punctuation_exact_string.join(
123
+ part.translate(str.maketrans("", "", string.punctuation))
124
+ for part in text.split(keep_punctuation_exact_string)
125
+ )
126
+ else:
127
+ text = text.translate(str.maketrans("", "", string.punctuation))
128
+ text = text.lower()
129
+ text = re.sub(r"\s+", " ", text)
130
+ return text.strip()
131
+
132
+
133
+ class SimpleTokenizer(object):
134
+ def __init__(
135
+ self,
136
+ bpe_path: str = default_bpe(),
137
+ additional_special_tokens: Optional[List[str]] = None,
138
+ context_length: Optional[int] = DEFAULT_CONTEXT_LENGTH,
139
+ clean: str = "lower",
140
+ reduction_mask: str = "",
141
+ ):
142
+ self.byte_encoder = bytes_to_unicode()
143
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
144
+ merges = gzip.open(bpe_path).read().decode("utf-8").split("\n")
145
+ merges = merges[1 : 49152 - 256 - 2 + 1]
146
+ merges = [tuple(merge.split()) for merge in merges]
147
+ vocab = list(bytes_to_unicode().values())
148
+ vocab = vocab + [v + "</w>" for v in vocab]
149
+ for merge in merges:
150
+ vocab.append("".join(merge))
151
+ special_tokens = ["<start_of_text>", "<end_of_text>"]
152
+ if additional_special_tokens:
153
+ special_tokens += additional_special_tokens
154
+ vocab.extend(special_tokens)
155
+ self.encoder = dict(zip(vocab, range(len(vocab))))
156
+ self.decoder = {v: k for k, v in self.encoder.items()}
157
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
158
+ self.cache = {t: t for t in special_tokens}
159
+ special = "|".join(special_tokens)
160
+ self.pat = re.compile(
161
+ special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
162
+ re.IGNORECASE,
163
+ )
164
+ self.vocab_size = len(self.encoder)
165
+ self.all_special_ids = [self.encoder[t] for t in special_tokens]
166
+ self.sot_token_id = self.all_special_ids[0]
167
+ self.eot_token_id = self.all_special_ids[1]
168
+ self.context_length = context_length
169
+ self.clean_fn = get_clean_fn(clean)
170
+ self.reduction_fn = (
171
+ get_reduction_mask_fn(reduction_mask) if reduction_mask else None
172
+ )
173
+
174
+ def bpe(self, token):
175
+ if token in self.cache:
176
+ return self.cache[token]
177
+ word = tuple(token[:-1]) + (token[-1] + "</w>",)
178
+ pairs = get_pairs(word)
179
+
180
+ if not pairs:
181
+ return token + "</w>"
182
+
183
+ while True:
184
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
185
+ if bigram not in self.bpe_ranks:
186
+ break
187
+ first, second = bigram
188
+ new_word = []
189
+ i = 0
190
+ while i < len(word):
191
+ try:
192
+ j = word.index(first, i)
193
+ new_word.extend(word[i:j])
194
+ i = j
195
+ except:
196
+ new_word.extend(word[i:])
197
+ break
198
+
199
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
200
+ new_word.append(first + second)
201
+ i += 2
202
+ else:
203
+ new_word.append(word[i])
204
+ i += 1
205
+ new_word = tuple(new_word)
206
+ word = new_word
207
+ if len(word) == 1:
208
+ break
209
+ else:
210
+ pairs = get_pairs(word)
211
+ word = " ".join(word)
212
+ self.cache[token] = word
213
+ return word
214
+
215
+ def encode(self, text):
216
+ bpe_tokens = []
217
+ text = self.clean_fn(text)
218
+ for token in re.findall(self.pat, text):
219
+ token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
220
+ bpe_tokens.extend(
221
+ self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
222
+ )
223
+ return bpe_tokens
224
+
225
+ def decode(self, tokens):
226
+ text = "".join([self.decoder[token] for token in tokens])
227
+ text = (
228
+ bytearray([self.byte_decoder[c] for c in text])
229
+ .decode("utf-8", errors="replace")
230
+ .replace("</w>", " ")
231
+ )
232
+ return text
233
+
234
+ def __call__(
235
+ self, texts: Union[str, List[str]], context_length: Optional[int] = None
236
+ ) -> torch.LongTensor:
237
+ """Returns the tokenized representation of given input string(s)
238
+
239
+ Parameters
240
+ ----------
241
+ texts : Union[str, List[str]]
242
+ An input string or a list of input strings to tokenize
243
+ context_length : int
244
+ The context length to use; all CLIP models use 77 as the context length
245
+
246
+ Returns
247
+ -------
248
+ A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
249
+ """
250
+ if isinstance(texts, str):
251
+ texts = [texts]
252
+
253
+ context_length = context_length or self.context_length
254
+ assert context_length, "Please set a valid context length"
255
+
256
+ if self.reduction_fn is not None:
257
+ # use reduction strategy for tokenize if set, otherwise default to truncation below
258
+ return self.reduction_fn(
259
+ texts,
260
+ context_length=context_length,
261
+ sot_token_id=self.sot_token_id,
262
+ eot_token_id=self.eot_token_id,
263
+ encode_fn=self.encode,
264
+ )
265
+
266
+ all_tokens = [
267
+ [self.sot_token_id] + self.encode(text) + [self.eot_token_id]
268
+ for text in texts
269
+ ]
270
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
271
+
272
+ for i, tokens in enumerate(all_tokens):
273
+ if len(tokens) > context_length:
274
+ tokens = tokens[:context_length] # Truncate
275
+ tokens[-1] = self.eot_token_id
276
+ result[i, : len(tokens)] = torch.tensor(tokens)
277
+
278
+ return result
279
+
280
+
281
+ def random_mask_tokenize(
282
+ texts: Union[str, List[str]],
283
+ context_length: int,
284
+ sot_token_id: int,
285
+ eot_token_id: int,
286
+ encode_fn: Callable,
287
+ shuffle: bool = False,
288
+ ):
289
+ all_tokens = [encode_fn(text) for text in texts]
290
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
291
+
292
+ for i, tokens in enumerate(all_tokens):
293
+ tokens = torch.tensor(tokens)
294
+ num_tokens = len(tokens)
295
+ if num_tokens > context_length - 2: # 2 for sot and eot token
296
+ num_keep = context_length - 2
297
+ indices = torch.randperm(len(tokens))
298
+ indices = indices[:num_keep]
299
+ if not shuffle:
300
+ indices = indices.msort()
301
+ tokens = tokens[indices]
302
+ num_tokens = num_keep
303
+ result[i, 0] = sot_token_id
304
+ result[i, 1 : num_tokens + 1] = tokens
305
+ result[i, num_tokens + 1] = eot_token_id
306
+
307
+ return result
308
+
309
+
310
+ def simple_mask_tokenize(
311
+ texts: Union[str, List[str]],
312
+ context_length: int,
313
+ sot_token_id: int,
314
+ eot_token_id: int,
315
+ encode_fn: Callable,
316
+ ):
317
+ all_tokens = [encode_fn(text) for text in texts]
318
+ result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
319
+
320
+ for i, tokens in enumerate(all_tokens):
321
+ num_tokens = len(tokens)
322
+ if num_tokens > context_length - 2: # 2 for sot and eot token
323
+ num_keep = context_length - 2
324
+ start_index = random.randint(0, num_tokens - num_keep) # high is incl
325
+ tokens = tokens[start_index : start_index + num_keep]
326
+ tokens = [sot_token_id] + tokens + [eot_token_id]
327
+ result[i, : len(tokens)] = torch.tensor(tokens)
328
+
329
+ return result
330
+
331
+
332
+ def get_reduction_mask_fn(type: str):
333
+ """Choose strategy for dropping (masking) tokens to achieve target context length"""
334
+ assert type in ("simple", "random", "shuffle")
335
+ if type == "simple":
336
+ return simple_mask_tokenize # randomly select block [start:end]
337
+ elif type == "random":
338
+ return random_mask_tokenize # randomly drop tokens (keep order)
339
+ elif type == "shuffle":
340
+ return partial(
341
+ random_mask_tokenize, shuffle=True
342
+ ) # randomly drop tokens (shuffle order)