(self, image: torch.Tensor, num_tokens: int)
| 267 | return points |
| 268 | |
| 269 | def forward(self, image: torch.Tensor, num_tokens: int) -> Dict[str, torch.Tensor]: |
| 270 | original_height, original_width = image.shape[-2:] |
| 271 | |
| 272 | # Resize to expected resolution defined by num_tokens |
| 273 | resize_factor = ((num_tokens * 14 ** 2) / (original_height * original_width)) ** 0.5 |
| 274 | resized_width, resized_height = int(original_width * resize_factor), int(original_height * resize_factor) |
| 275 | image = F.interpolate(image, (resized_height, resized_width), mode="bicubic", align_corners=False, antialias=True) |
| 276 | |
| 277 | # Apply image transformation for DINOv2 |
| 278 | image = (image - self.image_mean) / self.image_std |
| 279 | image_14 = F.interpolate(image, (resized_height // 14 * 14, resized_width // 14 * 14), mode="bilinear", align_corners=False, antialias=True) |
| 280 | |
| 281 | # Get intermediate layers from the backbone |
| 282 | features = self.backbone.get_intermediate_layers(image_14, self.intermediate_layers, return_class_token=True) |
| 283 | |
| 284 | # Predict points (and mask) |
| 285 | output = self.head(features, image) |
| 286 | points, mask = output |
| 287 | |
| 288 | # Make sure fp32 precision for output |
| 289 | with torch.autocast(device_type=image.device.type, dtype=torch.float32): |
| 290 | # Resize to original resolution |
| 291 | points = F.interpolate(points, (original_height, original_width), mode='bilinear', align_corners=False, antialias=False) |
| 292 | mask = F.interpolate(mask, (original_height, original_width), mode='bilinear', align_corners=False, antialias=False) |
| 293 | |
| 294 | # Post-process points and mask |
| 295 | points, mask = points.permute(0, 2, 3, 1), mask.squeeze(1) |
| 296 | points = self._remap_points(points) # slightly improves the performance in case of very large output values |
| 297 | |
| 298 | return_dict = {'points': points, 'mask': mask} |
| 299 | return return_dict |
| 300 | |
| 301 | @torch.inference_mode() |
| 302 | def infer( |
no test coverage detected