sam3_video_predictor.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
  2. # pyre-unsafe
  3. import datetime
  4. import gc
  5. import multiprocessing as mp
  6. import os
  7. import queue
  8. import socket
  9. import sys
  10. import time
  11. import uuid
  12. from contextlib import closing
  13. from typing import List, Optional
  14. import psutil
  15. import torch
  16. from sam3.logger import get_logger
  17. logger = get_logger(__name__)
  18. class Sam3VideoPredictor:
  19. # a global dictionary that holds all inference states for this model (key is session_id)
  20. _ALL_INFERENCE_STATES = {}
  21. def __init__(
  22. self,
  23. checkpoint_path=None,
  24. bpe_path=None,
  25. has_presence_token=True,
  26. geo_encoder_use_img_cross_attn=True,
  27. strict_state_dict_loading=True,
  28. async_loading_frames=False,
  29. video_loader_type="cv2",
  30. apply_temporal_disambiguation: bool = True,
  31. ):
  32. self.async_loading_frames = async_loading_frames
  33. self.video_loader_type = video_loader_type
  34. from sam3.model_builder import build_sam3_video_model
  35. self.model = (
  36. build_sam3_video_model(
  37. checkpoint_path=checkpoint_path,
  38. bpe_path=bpe_path,
  39. has_presence_token=has_presence_token,
  40. geo_encoder_use_img_cross_attn=geo_encoder_use_img_cross_attn,
  41. strict_state_dict_loading=strict_state_dict_loading,
  42. apply_temporal_disambiguation=apply_temporal_disambiguation,
  43. )
  44. .cuda()
  45. .eval()
  46. )
  47. @torch.inference_mode()
  48. def handle_request(self, request):
  49. """Dispatch a request based on its type."""
  50. request_type = request["type"]
  51. if request_type == "start_session":
  52. return self.start_session(
  53. resource_path=request["resource_path"],
  54. session_id=request.get("session_id", None),
  55. )
  56. elif request_type == "add_prompt":
  57. return self.add_prompt(
  58. session_id=request["session_id"],
  59. frame_idx=request["frame_index"],
  60. text=request.get("text", None),
  61. points=request.get("points", None),
  62. point_labels=request.get("point_labels", None),
  63. bounding_boxes=request.get("bounding_boxes", None),
  64. bounding_box_labels=request.get("bounding_box_labels", None),
  65. obj_id=request.get("obj_id", None),
  66. )
  67. elif request_type == "remove_object":
  68. return self.remove_object(
  69. session_id=request["session_id"],
  70. obj_id=request["obj_id"],
  71. is_user_action=request.get("is_user_action", True),
  72. )
  73. elif request_type == "reset_session":
  74. return self.reset_session(session_id=request["session_id"])
  75. elif request_type == "close_session":
  76. return self.close_session(session_id=request["session_id"])
  77. else:
  78. raise RuntimeError(f"invalid request type: {request_type}")
  79. @torch.inference_mode()
  80. def handle_stream_request(self, request):
  81. """Dispatch a stream request based on its type."""
  82. request_type = request["type"]
  83. if request_type == "propagate_in_video":
  84. yield from self.propagate_in_video(
  85. session_id=request["session_id"],
  86. propagation_direction=request.get("propagation_direction", "both"),
  87. start_frame_idx=request.get("start_frame_index", None),
  88. max_frame_num_to_track=request.get("max_frame_num_to_track", None),
  89. )
  90. else:
  91. raise RuntimeError(f"invalid request type: {request_type}")
  92. def start_session(self, resource_path, session_id=None):
  93. """
  94. Start a new inference session on an image or a video. Here `resource_path`
  95. can be either a path to an image file (for image inference) or an MP4 file
  96. or directory with JPEG video frames (for video inference).
  97. If `session_id` is defined, it will be used as identifier for the
  98. session. If it is not defined, the start_session function will create
  99. a session id and return it.
  100. """
  101. # get an initial inference_state from the model
  102. inference_state = self.model.init_state(
  103. resource_path=resource_path,
  104. async_loading_frames=self.async_loading_frames,
  105. video_loader_type=self.video_loader_type,
  106. )
  107. if not session_id:
  108. session_id = str(uuid.uuid4())
  109. self._ALL_INFERENCE_STATES[session_id] = {
  110. "state": inference_state,
  111. "session_id": session_id,
  112. "start_time": time.time(),
  113. }
  114. logger.debug(
  115. f"started new session {session_id}; {self._get_session_stats()}; "
  116. f"{self._get_torch_and_gpu_properties()}"
  117. )
  118. return {"session_id": session_id}
  119. def add_prompt(
  120. self,
  121. session_id: str,
  122. frame_idx: int,
  123. text: Optional[str] = None,
  124. points: Optional[List[List[float]]] = None,
  125. point_labels: Optional[List[int]] = None,
  126. bounding_boxes: Optional[List[List[float]]] = None,
  127. bounding_box_labels: Optional[List[int]] = None,
  128. obj_id: Optional[int] = None,
  129. ):
  130. """Add text, box and/or point prompt on a specific video frame."""
  131. logger.debug(
  132. f"add prompt on frame {frame_idx} in session {session_id}: "
  133. f"{text=}, {points=}, {point_labels=}, "
  134. f"{bounding_boxes=}, {bounding_box_labels=}"
  135. )
  136. session = self._get_session(session_id)
  137. inference_state = session["state"]
  138. frame_idx, outputs = self.model.add_prompt(
  139. inference_state=inference_state,
  140. frame_idx=frame_idx,
  141. text_str=text,
  142. points=points,
  143. point_labels=point_labels,
  144. boxes_xywh=bounding_boxes,
  145. box_labels=bounding_box_labels,
  146. obj_id=obj_id,
  147. )
  148. return {"frame_index": frame_idx, "outputs": outputs}
  149. def remove_object(
  150. self,
  151. session_id: str,
  152. obj_id: int,
  153. is_user_action: bool = True,
  154. ):
  155. """Remove an object from tracking."""
  156. logger.debug(
  157. f"remove object {obj_id} in session {session_id}: {is_user_action=}"
  158. )
  159. session = self._get_session(session_id)
  160. inference_state = session["state"]
  161. self.model.remove_object(
  162. inference_state=inference_state,
  163. obj_id=obj_id,
  164. is_user_action=is_user_action,
  165. )
  166. return {"is_success": True}
  167. def propagate_in_video(
  168. self,
  169. session_id,
  170. propagation_direction,
  171. start_frame_idx,
  172. max_frame_num_to_track,
  173. ):
  174. """Propagate the added prompts to get grounding results on all video frames."""
  175. logger.debug(
  176. f"propagate in video in session {session_id}: "
  177. f"{propagation_direction=}, {start_frame_idx=}, {max_frame_num_to_track=}"
  178. )
  179. try:
  180. session = self._get_session(session_id)
  181. inference_state = session["state"]
  182. if propagation_direction not in ["both", "forward", "backward"]:
  183. raise ValueError(
  184. f"invalid propagation direction: {propagation_direction}"
  185. )
  186. # First doing the forward propagation
  187. if propagation_direction in ["both", "forward"]:
  188. for frame_idx, outputs in self.model.propagate_in_video(
  189. inference_state=inference_state,
  190. start_frame_idx=start_frame_idx,
  191. max_frame_num_to_track=max_frame_num_to_track,
  192. reverse=False,
  193. ):
  194. yield {"frame_index": frame_idx, "outputs": outputs}
  195. # Then doing the backward propagation (reverse in time)
  196. if propagation_direction in ["both", "backward"]:
  197. for frame_idx, outputs in self.model.propagate_in_video(
  198. inference_state=inference_state,
  199. start_frame_idx=start_frame_idx,
  200. max_frame_num_to_track=max_frame_num_to_track,
  201. reverse=True,
  202. ):
  203. yield {"frame_index": frame_idx, "outputs": outputs}
  204. finally:
  205. # Log upon completion (so that e.g. we can see if two propagations happen in parallel).
  206. # Using `finally` here to log even when the tracking is aborted with GeneratorExit.
  207. logger.debug(
  208. f"propagation ended in session {session_id}; {self._get_session_stats()}"
  209. )
  210. def reset_session(self, session_id):
  211. """Reset the session to its initial state (as when it's initial opened)."""
  212. logger.debug(f"reset session {session_id}")
  213. session = self._get_session(session_id)
  214. inference_state = session["state"]
  215. self.model.reset_state(inference_state)
  216. return {"is_success": True}
  217. def close_session(self, session_id):
  218. """
  219. Close a session. This method is idempotent and can be called multiple
  220. times on the same "session_id".
  221. """
  222. session = self._ALL_INFERENCE_STATES.pop(session_id, None)
  223. if session is None:
  224. logger.warning(
  225. f"cannot close session {session_id} as it does not exist (it might have expired); "
  226. f"{self._get_session_stats()}"
  227. )
  228. else:
  229. del session
  230. gc.collect()
  231. logger.info(f"removed session {session_id}; {self._get_session_stats()}")
  232. return {"is_success": True}
  233. def _get_session(self, session_id):
  234. session = self._ALL_INFERENCE_STATES.get(session_id, None)
  235. if session is None:
  236. raise RuntimeError(
  237. f"Cannot find session {session_id}; it might have expired"
  238. )
  239. return session
  240. def _get_session_stats(self):
  241. """Get a statistics string for live sessions and their GPU usage."""
  242. # print both the session ids and their video frame numbers
  243. live_session_strs = [
  244. f"'{session_id}' ({session['state']['num_frames']} frames)"
  245. for session_id, session in self._ALL_INFERENCE_STATES.items()
  246. ]
  247. session_stats_str = (
  248. f"live sessions: [{', '.join(live_session_strs)}], GPU memory: "
  249. f"{torch.cuda.memory_allocated() // 1024**2} MiB used and "
  250. f"{torch.cuda.memory_reserved() // 1024**2} MiB reserved"
  251. f" (max over time: {torch.cuda.max_memory_allocated() // 1024**2} MiB used "
  252. f"and {torch.cuda.max_memory_reserved() // 1024**2} MiB reserved)"
  253. )
  254. return session_stats_str
  255. def _get_torch_and_gpu_properties(self):
  256. """Get a string for PyTorch and GPU properties (for logging and debugging)."""
  257. torch_and_gpu_str = (
  258. f"torch: {torch.__version__} with CUDA arch {torch.cuda.get_arch_list()}, "
  259. f"GPU device: {torch.cuda.get_device_properties(torch.cuda.current_device())}"
  260. )
  261. return torch_and_gpu_str
  262. def shutdown(self):
  263. """Shutdown the predictor and clear all sessions."""
  264. self._ALL_INFERENCE_STATES.clear()
  265. class Sam3VideoPredictorMultiGPU(Sam3VideoPredictor):
  266. def __init__(self, *model_args, gpus_to_use=None, **model_kwargs):
  267. if gpus_to_use is None:
  268. # if not specified, use only the current GPU by default
  269. gpus_to_use = [torch.cuda.current_device()]
  270. IS_MAIN_PROCESS = os.getenv("IS_MAIN_PROCESS", "1") == "1"
  271. if IS_MAIN_PROCESS:
  272. gpus_to_use = sorted(set(gpus_to_use))
  273. logger.info(f"using the following GPU IDs: {gpus_to_use}")
  274. assert len(gpus_to_use) > 0 and all(isinstance(i, int) for i in gpus_to_use)
  275. assert all(0 <= i < torch.cuda.device_count() for i in gpus_to_use)
  276. os.environ["MASTER_ADDR"] = "localhost"
  277. os.environ["MASTER_PORT"] = f"{self._find_free_port()}"
  278. os.environ["RANK"] = "0"
  279. os.environ["WORLD_SIZE"] = f"{len(gpus_to_use)}"
  280. self.gpus_to_use = gpus_to_use
  281. self.rank = int(os.environ["RANK"])
  282. self.world_size = int(os.environ["WORLD_SIZE"])
  283. self.rank_str = f"rank={self.rank} with world_size={self.world_size}"
  284. self.device = torch.device(f"cuda:{self.gpus_to_use[self.rank]}")
  285. torch.cuda.set_device(self.device)
  286. self.has_shutdown = False
  287. if self.rank == 0:
  288. logger.info("\n\n\n\t*** START loading model on all ranks ***\n\n")
  289. logger.info(f"loading model on {self.rank_str} -- this could take a while ...")
  290. super().__init__(*model_args, **model_kwargs)
  291. logger.info(f"loading model on {self.rank_str} -- DONE locally")
  292. if self.world_size > 1 and self.rank == 0:
  293. # start the worker processes *after* the model is loaded in the main process
  294. # so that the main process can run torch.compile and fill the cache first
  295. self._start_worker_processes(*model_args, **model_kwargs)
  296. for rank in range(1, self.world_size):
  297. self.command_queues[rank].put(("start_nccl_process_group", None))
  298. self._start_nccl_process_group()
  299. if self.rank == 0:
  300. logger.info("\n\n\n\t*** DONE loading model on all ranks ***\n\n")
  301. @torch.inference_mode()
  302. def handle_request(self, request):
  303. """Dispatch a request based on its type."""
  304. if self.has_shutdown:
  305. raise RuntimeError(
  306. "cannot handle request after the predictor has shutdown; please create a new predictor"
  307. )
  308. # when starting a session, we need to create a session id before dispatching
  309. # the request to the workers
  310. if request["type"] == "start_session" and request.get("session_id") is None:
  311. request["session_id"] = str(uuid.uuid4())
  312. # dispatch the request to all worker processes
  313. if self.world_size > 1 and self.rank == 0:
  314. for rank in range(1, self.world_size):
  315. self.command_queues[rank].put((request, False))
  316. response = super().handle_request(request)
  317. if self.world_size > 1:
  318. torch.distributed.barrier() # wait for all ranks to finish
  319. return response
  320. @torch.inference_mode()
  321. def handle_stream_request(self, request):
  322. """Dispatch a stream request based on its type."""
  323. if self.has_shutdown:
  324. raise RuntimeError(
  325. "cannot handle request after the predictor has shutdown; please create a new predictor"
  326. )
  327. # dispatch the request to all worker processes
  328. if self.world_size > 1 and self.rank == 0:
  329. for rank in range(1, self.world_size):
  330. self.command_queues[rank].put((request, True))
  331. yield from super().handle_stream_request(request)
  332. if self.world_size > 1:
  333. torch.distributed.barrier() # wait for all ranks to finish
  334. def _start_worker_processes(self, *model_args, **model_kwargs):
  335. """Start worker processes for handling model inference."""
  336. world_size = self.world_size
  337. logger.info(f"spawning {world_size - 1} worker processes")
  338. # Use "spawn" (instead of "fork") for different PyTorch or CUDA context
  339. mp_ctx = mp.get_context("spawn")
  340. self.command_queues = {rank: mp_ctx.Queue() for rank in range(1, world_size)}
  341. self.result_queues = {rank: mp_ctx.Queue() for rank in range(1, world_size)}
  342. parent_pid = os.getpid()
  343. for rank in range(1, world_size):
  344. # set the environment variables for each worker process
  345. os.environ["IS_MAIN_PROCESS"] = "0" # mark this as a worker process
  346. os.environ["RANK"] = f"{rank}"
  347. worker_process = mp_ctx.Process(
  348. target=Sam3VideoPredictorMultiGPU._worker_process_command_loop,
  349. args=(
  350. rank,
  351. world_size,
  352. self.command_queues[rank],
  353. self.result_queues[rank],
  354. model_args,
  355. model_kwargs,
  356. self.gpus_to_use,
  357. parent_pid,
  358. ),
  359. daemon=True,
  360. )
  361. worker_process.start()
  362. # revert the environment variables for the main process
  363. os.environ["IS_MAIN_PROCESS"] = "1"
  364. os.environ["RANK"] = "0"
  365. # wait for all the worker processes to load the model and collect their PIDs
  366. self.worker_pids = {}
  367. for rank in range(1, self.world_size):
  368. # a large timeout to cover potentially long model loading time due to compilation
  369. _, worker_pid = self.result_queues[rank].get(timeout=7200)
  370. self.worker_pids[rank] = worker_pid
  371. logger.info(f"spawned {world_size - 1} worker processes")
  372. def _start_nccl_process_group(self):
  373. rank = int(os.environ["RANK"])
  374. world_size = int(os.environ["WORLD_SIZE"])
  375. if world_size == 1:
  376. return
  377. logger.debug(f"starting NCCL process group on {rank=} with {world_size=}")
  378. assert not torch.distributed.is_initialized()
  379. # use the "env://" init method with environment variables set in start_worker_processes
  380. # a short 3-min timeout to quickly detect any synchronization failures
  381. timeout_sec = int(os.getenv("SAM3_COLLECTIVE_OP_TIMEOUT_SEC", "180"))
  382. timeout = datetime.timedelta(seconds=timeout_sec)
  383. torch.distributed.init_process_group(
  384. backend="nccl",
  385. init_method="env://",
  386. timeout=timeout,
  387. device_id=self.device,
  388. )
  389. # warm-up the NCCL process group by running a dummy all-reduce
  390. tensor = torch.ones(1024, 1024).cuda()
  391. torch.distributed.all_reduce(tensor)
  392. logger.debug(f"started NCCL process group on {rank=} with {world_size=}")
  393. def _find_free_port(self) -> int:
  394. """
  395. Find a free port (a random free port from 1024 to 65535 will be selected)
  396. https://stackoverflow.com/questions/1365265/on-localhost-how-do-i-pick-a-free-port-number)
  397. """
  398. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
  399. s.bind(("", 0))
  400. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  401. return s.getsockname()[1]
  402. @staticmethod
  403. def _worker_process_command_loop(
  404. rank,
  405. world_size,
  406. command_queue,
  407. result_queue,
  408. model_args,
  409. model_kwargs,
  410. gpus_to_use,
  411. parent_pid,
  412. ):
  413. """
  414. The command loop for each worker process. It listens to commands from the main process
  415. and executes them using the model.
  416. """
  417. logger.info(f"starting worker process {rank=} with {world_size=}")
  418. # verify that the environment variables are set correctly
  419. assert int(os.environ["IS_MAIN_PROCESS"]) == 0
  420. assert int(os.environ["RANK"]) == rank
  421. assert int(os.environ["WORLD_SIZE"]) == world_size
  422. # load the model in this worker process
  423. predictor = Sam3VideoPredictorMultiGPU(
  424. *model_args, gpus_to_use=gpus_to_use, **model_kwargs
  425. )
  426. logger.info(f"started worker {rank=} with {world_size=}")
  427. # return the worker process id to the main process for bookkeeping
  428. worker_pid = os.getpid()
  429. result_queue.put(("load_model", worker_pid))
  430. # wait for the command to start the NCCL process group
  431. request_type, _ = command_queue.get(timeout=7200)
  432. assert request_type == "start_nccl_process_group"
  433. predictor._start_nccl_process_group()
  434. # keep listening to commands from the main process
  435. while True:
  436. try:
  437. request, is_stream_request = command_queue.get(timeout=5.0)
  438. if request == "shutdown":
  439. logger.info(f"worker {rank=} shutting down")
  440. torch.distributed.destroy_process_group()
  441. result_queue.put(("shutdown", True)) # acknowledge the shutdown
  442. sys.exit(0)
  443. logger.debug(f"worker {rank=} received request {request['type']=}")
  444. if is_stream_request:
  445. for _ in predictor.handle_stream_request(request):
  446. pass # handle stream requests in a generator fashion
  447. else:
  448. predictor.handle_request(request)
  449. except queue.Empty:
  450. # Usually Python's multiprocessing module will shutdown all the daemon worker
  451. # processes when the main process exits gracefully. However, the user may kill
  452. # the main process using SIGKILL and thereby leaving no chance for the main process
  453. # to clean up its daemon child processes. So here we manually check whether the
  454. # parent process still exists (every 5 sec as in `command_queue.get` timeout).
  455. if not psutil.pid_exists(parent_pid):
  456. logger.info(
  457. f"stopping worker {rank=} as its parent process has exited"
  458. )
  459. sys.exit(1)
  460. except Exception as e:
  461. logger.error(f"worker {rank=} exception: {e}", exc_info=True)
  462. def shutdown(self):
  463. """Shutdown all worker processes."""
  464. if self.rank == 0 and self.world_size > 1:
  465. logger.info(f"shutting down {self.world_size - 1} worker processes")
  466. for rank in range(1, self.world_size):
  467. self.command_queues[rank].put(("shutdown", False))
  468. torch.distributed.destroy_process_group()
  469. for rank in range(1, self.world_size):
  470. self.result_queues[rank].get() # wait for the worker to acknowledge
  471. logger.info(f"shut down {self.world_size - 1} worker processes")
  472. self.has_shutdown = True
  473. super().shutdown()