misc.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import warnings
  6. import numpy as np
  7. import torch
  8. from PIL import Image
  9. def get_sdpa_settings():
  10. if torch.cuda.is_available():
  11. old_gpu = torch.cuda.get_device_properties(0).major < 7
  12. # only use Flash Attention on Ampere (8.0) or newer GPUs
  13. use_flash_attn = torch.cuda.get_device_properties(0).major >= 8
  14. if not use_flash_attn:
  15. warnings.warn(
  16. "Flash Attention is disabled as it requires a GPU with Ampere (8.0) CUDA capability.",
  17. category=UserWarning,
  18. stacklevel=2,
  19. )
  20. # keep math kernel for PyTorch versions before 2.2 (Flash Attention v2 is only
  21. # available on PyTorch 2.2+, while Flash Attention v1 cannot handle all cases)
  22. pytorch_version = tuple(int(v) for v in torch.__version__.split(".")[:2])
  23. if pytorch_version < (2, 2):
  24. warnings.warn(
  25. f"You are using PyTorch {torch.__version__} without Flash Attention v2 support. "
  26. "Consider upgrading to PyTorch 2.2+ for Flash Attention v2 (which could be faster).",
  27. category=UserWarning,
  28. stacklevel=2,
  29. )
  30. math_kernel_on = pytorch_version < (2, 2) or not use_flash_attn
  31. else:
  32. old_gpu = True
  33. use_flash_attn = False
  34. math_kernel_on = True
  35. return old_gpu, use_flash_attn, math_kernel_on
  36. def mask_to_box(masks: torch.Tensor):
  37. """
  38. compute bounding box given an input mask
  39. Inputs:
  40. - masks: [B, 1, H, W] boxes, dtype=torch.Tensor
  41. Returns:
  42. - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor
  43. """
  44. B, _, h, w = masks.shape
  45. device = masks.device
  46. xs = torch.arange(w, device=device, dtype=torch.int32)
  47. ys = torch.arange(h, device=device, dtype=torch.int32)
  48. grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy")
  49. grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w)
  50. grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w)
  51. min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1)
  52. max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1)
  53. min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1)
  54. max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1)
  55. bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1)
  56. return bbox_coords
  57. def _load_img_as_tensor(img_path, image_size):
  58. img_pil = Image.open(img_path)
  59. img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size)))
  60. if img_np.dtype == np.uint8: # np.uint8 is expected for JPEG images
  61. img_np = img_np / 255.0
  62. else:
  63. raise RuntimeError(f"Unknown image dtype: {img_np.dtype} on {img_path}")
  64. img = torch.from_numpy(img_np).permute(2, 0, 1)
  65. video_width, video_height = img_pil.size # the original video size
  66. return img, video_height, video_width
  67. def concat_points(old_point_inputs, new_points, new_labels):
  68. """Add new points and labels to previous point inputs (add at the end)."""
  69. if old_point_inputs is None:
  70. points, labels = new_points, new_labels
  71. else:
  72. points = torch.cat([old_point_inputs["point_coords"], new_points], dim=1)
  73. labels = torch.cat([old_point_inputs["point_labels"], new_labels], dim=1)
  74. return {"point_coords": points, "point_labels": labels}