build_sam.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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 logging
  6. import os
  7. import torch
  8. from hydra import compose
  9. from hydra.utils import instantiate
  10. from omegaconf import OmegaConf
  11. import sam2
  12. # Check if the user is running Python from the parent directory of the sam2 repo
  13. # (i.e. the directory where this repo is cloned into) -- this is not supported since
  14. # it could shadow the sam2 package and cause issues.
  15. if os.path.isdir(os.path.join(sam2.__path__[0], "sam2")):
  16. # If the user has "sam2/sam2" in their path, they are likey importing the repo itself
  17. # as "sam2" rather than importing the "sam2" python package (i.e. "sam2/sam2" directory).
  18. # This typically happens because the user is running Python from the parent directory
  19. # that contains the sam2 repo they cloned.
  20. raise RuntimeError(
  21. "You're likely running Python from the parent directory of the sam2 repository "
  22. "(i.e. the directory where https://github.com/facebookresearch/sam2 is cloned into). "
  23. "This is not supported since the `sam2` Python package could be shadowed by the "
  24. "repository name (the repository is also named `sam2` and contains the Python package "
  25. "in `sam2/sam2`). Please run Python from another directory (e.g. from the repo dir "
  26. "rather than its parent dir, or from your home directory) after installing SAM 2."
  27. )
  28. HF_MODEL_ID_TO_FILENAMES = {
  29. "facebook/sam2-hiera-tiny": (
  30. "configs/sam2/sam2_hiera_t.yaml",
  31. "sam2_hiera_tiny.pt",
  32. ),
  33. "facebook/sam2-hiera-small": (
  34. "configs/sam2/sam2_hiera_s.yaml",
  35. "sam2_hiera_small.pt",
  36. ),
  37. "facebook/sam2-hiera-base-plus": (
  38. "configs/sam2/sam2_hiera_b+.yaml",
  39. "sam2_hiera_base_plus.pt",
  40. ),
  41. "facebook/sam2-hiera-large": (
  42. "configs/sam2/sam2_hiera_l.yaml",
  43. "sam2_hiera_large.pt",
  44. ),
  45. "facebook/sam2.1-hiera-tiny": (
  46. "configs/sam2.1/sam2.1_hiera_t.yaml",
  47. "sam2.1_hiera_tiny.pt",
  48. ),
  49. "facebook/sam2.1-hiera-small": (
  50. "configs/sam2.1/sam2.1_hiera_s.yaml",
  51. "sam2.1_hiera_small.pt",
  52. ),
  53. "facebook/sam2.1-hiera-base-plus": (
  54. "configs/sam2.1/sam2.1_hiera_b+.yaml",
  55. "sam2.1_hiera_base_plus.pt",
  56. ),
  57. "facebook/sam2.1-hiera-large": (
  58. "configs/sam2.1/sam2.1_hiera_l.yaml",
  59. "sam2.1_hiera_large.pt",
  60. ),
  61. }
  62. def build_sam2(
  63. config_file,
  64. ckpt_path=None,
  65. device="cuda",
  66. mode="eval",
  67. hydra_overrides_extra=[],
  68. apply_postprocessing=True,
  69. **kwargs,
  70. ):
  71. if apply_postprocessing:
  72. hydra_overrides_extra = hydra_overrides_extra.copy()
  73. hydra_overrides_extra += [
  74. # dynamically fall back to multi-mask if the single mask is not stable
  75. "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
  76. "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
  77. "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
  78. ]
  79. # Read config and init model
  80. cfg = compose(config_name=config_file, overrides=hydra_overrides_extra)
  81. OmegaConf.resolve(cfg)
  82. model = instantiate(cfg.model, _recursive_=True)
  83. _load_checkpoint(model, ckpt_path)
  84. model = model.to(device)
  85. if mode == "eval":
  86. model.eval()
  87. return model
  88. def build_sam2_video_predictor(
  89. config_file,
  90. ckpt_path=None,
  91. device="cuda",
  92. mode="eval",
  93. hydra_overrides_extra=[],
  94. apply_postprocessing=True,
  95. vos_optimized=False,
  96. **kwargs,
  97. ):
  98. hydra_overrides = [
  99. "++model._target_=sam2.sam2_video_predictor.SAM2VideoPredictor",
  100. ]
  101. if vos_optimized:
  102. hydra_overrides = [
  103. "++model._target_=sam2.sam2_video_predictor.SAM2VideoPredictorVOS",
  104. "++model.compile_image_encoder=True", # Let sam2_base handle this
  105. ]
  106. if apply_postprocessing:
  107. hydra_overrides_extra = hydra_overrides_extra.copy()
  108. hydra_overrides_extra += [
  109. # dynamically fall back to multi-mask if the single mask is not stable
  110. "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
  111. "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
  112. "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
  113. # the sigmoid mask logits on interacted frames with clicks in the memory encoder so that the encoded masks are exactly as what users see from clicking
  114. "++model.binarize_mask_from_pts_for_mem_enc=true",
  115. # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution)
  116. "++model.fill_hole_area=8",
  117. ]
  118. hydra_overrides.extend(hydra_overrides_extra)
  119. # Read config and init model
  120. cfg = compose(config_name=config_file, overrides=hydra_overrides)
  121. OmegaConf.resolve(cfg)
  122. model = instantiate(cfg.model, _recursive_=True)
  123. _load_checkpoint(model, ckpt_path)
  124. model = model.to(device)
  125. if mode == "eval":
  126. model.eval()
  127. return model
  128. def _hf_download(model_id):
  129. from huggingface_hub import hf_hub_download
  130. config_name, checkpoint_name = HF_MODEL_ID_TO_FILENAMES[model_id]
  131. ckpt_path = hf_hub_download(repo_id=model_id, filename=checkpoint_name)
  132. return config_name, ckpt_path
  133. def build_sam2_hf(model_id, **kwargs):
  134. config_name, ckpt_path = _hf_download(model_id)
  135. return build_sam2(config_file=config_name, ckpt_path=ckpt_path, **kwargs)
  136. def build_sam2_video_predictor_hf(model_id, **kwargs):
  137. config_name, ckpt_path = _hf_download(model_id)
  138. return build_sam2_video_predictor(
  139. config_file=config_name, ckpt_path=ckpt_path, **kwargs
  140. )
  141. def _load_checkpoint(model, ckpt_path):
  142. if ckpt_path is not None:
  143. sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"]
  144. missing_keys, unexpected_keys = model.load_state_dict(sd)
  145. if missing_keys:
  146. logging.error(missing_keys)
  147. raise RuntimeError()
  148. if unexpected_keys:
  149. logging.error(unexpected_keys)
  150. raise RuntimeError()
  151. logging.info("Loaded checkpoint sucessfully")