Spaces:
Paused
Paused
Zhen Ye commited on
Commit ·
301e154
1
Parent(s): a4e3c2b
feat(ttfs): instrument segmentation time-to-first-stream
Browse filesFiles changed (5)
27 unmodified lines282930313233375 unmodified lines40941041141241341419 unmodified lines43443543643743843936 unmodified lines4764774784794804818 unmodified lines4904914924934944952 unmodified lines49849950050150250320 unmodified lines524525526527528529241 unmodified lines7717727737747757765 unmodified lines78278378478578678778878979079119 unmodified lines81181281381481581627 unmodified linesimport asyncioimport shutilimport tempfileimport uuidfrom contextlib import asynccontextmanagerfrom datetime import timedelta375 unmodified linesenable_depth: bool = Form(False),enable_gpt: bool = Form(True),):if mode not in VALID_MODES:raise HTTPException(status_code=400,19 unmodified linesfinally:await video.close()# --- Mission-Driven Query Parsing ---mission_spec = Nonemission_mode = "LEGACY"36 unmodified lines"LEGACY mode: no mission text, defaults=%s, GPT disabled", query_list)available_depth_estimators = set(list_depth_estimators())if depth_estimator not in available_depth_estimators:raise HTTPException(8 unmodified linesactive_depth = depth_estimator if enable_depth else Nonetry:processed_frame, detections = process_first_frame(str(input_path),query_list,2 unmodified linessegmenter_name=segmenter,)cv2.imwrite(str(first_frame_path), processed_frame)# GPT and depth are now handled in the async pipeline (enrichment thread)first_frame_gpt_results = Noneexcept Exception:20 unmodified linesmission_spec=mission_spec,mission_mode=mission_mode,first_frame_gpt_results=first_frame_gpt_results,)get_job_storage().create(job)asyncio.create_task(process_video_async(job_id))241 unmodified linesloop = asyncio.get_running_loop()buffered = False# Get or create the asyncio.Event for this stream (must be in async context)event = get_stream_event(job_id)5 unmodified linestry:# Initial Buffer: Wait until we have enough frames or job is doneif not buffered:if q.qsize() < 5:await asyncio.sleep(0.1)continuebuffered = True# Event-driven wait — replaces busy-wait pollingif event is not None:19 unmodified linessuccess, buffer = await loop.run_in_executor(None, cv2.imencode, '.jpg', frame, encode_param)if success:yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')27 unmodified lines28293031323334375 unmodified lines41041141241341441541641719 unmodified lines43743843944044144244344436 unmodified lines4814824834844854864874888 unmodified lines4974984995005015025032 unmodified lines50650750850951051151220 unmodified lines533534535536537538539241 unmodified lines7817827837847857867877887897907917927937947955 unmodified lines80180280380480580680780880981081181281381481519 unmodified lines83583683783883984084184284384427 unmodified linesimport asyncioimport shutilimport tempfileimport timeimport uuidfrom contextlib import asynccontextmanagerfrom datetime import timedelta375 unmodified linesenable_depth: bool = Form(False),enable_gpt: bool = Form(True),):_ttfs_t0 = time.perf_counter()if mode not in VALID_MODES:raise HTTPException(status_code=400,19 unmodified linesfinally:await video.close()logging.info("[TTFS:%s] +%.1fs upload_saved", job_id, time.perf_counter() - _ttfs_t0)# --- Mission-Driven Query Parsing ---mission_spec = Nonemission_mode = "LEGACY"36 unmodified lines"LEGACY mode: no mission text, defaults=%s, GPT disabled", query_list)logging.info("[TTFS:%s] +%.1fs mission_parsed", job_id, time.perf_counter() - _ttfs_t0)available_depth_estimators = set(list_depth_estimators())if depth_estimator not in available_depth_estimators:raise HTTPException(8 unmodified linesactive_depth = depth_estimator if enable_depth else Nonetry:logging.info("[TTFS:%s] +%.1fs process_first_frame start", job_id, time.perf_counter() - _ttfs_t0)processed_frame, detections = process_first_frame(str(input_path),query_list,2 unmodified linessegmenter_name=segmenter,)cv2.imwrite(str(first_frame_path), processed_frame)logging.info("[TTFS:%s] +%.1fs process_first_frame done", job_id, time.perf_counter() - _ttfs_t0)# GPT and depth are now handled in the async pipeline (enrichment thread)first_frame_gpt_results = Noneexcept Exception:20 unmodified linesmission_spec=mission_spec,mission_mode=mission_mode,first_frame_gpt_results=first_frame_gpt_results,ttfs_t0=_ttfs_t0,)get_job_storage().create(job)asyncio.create_task(process_video_async(job_id))241 unmodified linesloop = asyncio.get_running_loop()buffered = False# TTFS instrumentation_first_yielded = False_buffer_wait_logged = False_job = get_job_storage().get(job_id)_stream_t0 = _job.ttfs_t0 if _job else Noneif _stream_t0:logging.info("[TTFS:%s] +%.1fs stream_subscribed", job_id, time.perf_counter() - _stream_t0)# Get or create the asyncio.Event for this stream (must be in async context)event = get_stream_event(job_id)5 unmodified linestry:# Initial Buffer: Wait until we have enough frames or job is doneif not buffered:if not _buffer_wait_logged and _stream_t0:logging.info("[TTFS:%s] +%.1fs stream_buffer_wait (qsize=%d)", job_id, time.perf_counter() - _stream_t0, q.qsize())_buffer_wait_logged = Trueif q.qsize() < 5:await asyncio.sleep(0.1)continuebuffered = Trueif _stream_t0:logging.info("[TTFS:%s] +%.1fs stream_buffer_ready", job_id, time.perf_counter() - _stream_t0)# Event-driven wait — replaces busy-wait pollingif event is not None:19 unmodified linessuccess, buffer = await loop.run_in_executor(None, cv2.imencode, '.jpg', frame, encode_param)if success:if not _first_yielded:_first_yielded = Trueif _stream_t0:logging.info("[TTFS:%s] +%.1fs first_yield_to_client", job_id, time.perf_counter() - _stream_t0)yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
1276 unmodified lines1277127812791280128112829 unmodified lines12921293129412951296129717 unmodified lines131513161317131813191320153 unmodified lines147414751476147714781479135 unmodified lines16151616161716181619162058 unmodified lines16791680168116821683168417 unmodified lines17021703170417051706170749 unmodified lines17571758175917601761176217 unmodified lines17801781178217831784178511 unmodified lines179717981799180018011802180318041805180639 unmodified lines18461847184818491850185114 unmodified lines186618671868186918701871156 unmodified lines20282029203020312032203321 unmodified lines20552056205720582059206030 unmodified lines2091209220932094209520961276 unmodified lines_perf_lock=None,num_maskmem: Optional[int] = None,detector_name: Optional[str] = None,) -> str:"""Run Grounded-SAM-2 video tracking pipeline.9 unmodified linesfrom models.segmenters.grounded_sam2 import MaskDictionary, ObjectInfo, LazyFrameObjectsactive_segmenter = segmenter_name or "GSAM2-L"logging.info("Grounded-SAM-2 tracking: segmenter=%s, queries=%s, step=%d",active_segmenter, queries, step,17 unmodified linesif _perf_metrics is not None:_perf_metrics["frame_extraction_ms"] = (time.perf_counter() - _t_ext) * 1000.0total_frames = len(frame_names)logging.info("Extracted %d frames to %s", total_frames, frame_dir)num_gpus = torch.cuda.device_count()153 unmodified linesdef _writer_loop():nonlocal render_donenext_idx = 0buf: Dict[int, Tuple] = {}135 unmodified linesif stream_queue or job_id:with _stream_lock:_stream_deque.append(frm)next_idx += 1if next_idx % 30 == 0:58 unmodified lines"accumulated=%d frames in %.1fs",r_prod, r_stream, accumulated, elapsed,)# --- Phase 2: adaptive streaming ---last_adjust = time.perf_counter()17 unmodified linesstream_queue.put(frame, timeout=0.01)except Exception:passpublished += 1last_publish_time = time.perf_counter()time.sleep(frame_interval)49 unmodified lines_publisher_thread = Thread(target=_stream_publisher_thread, daemon=True)_publisher_thread.start()# ==================================================================# Phase 1-4: Tracking (single-GPU fallback vs multi-GPU pipeline)# Segments are fed incrementally to render_in as they complete.17 unmodified linessegmenter._perf_metrics = _perf_metricssegmenter._perf_lock = Noneif _perf_metrics is not None:_t_track = time.perf_counter()11 unmodified linesseen.add(fi)render_in.put((fi, LazyFrameObjects(segment_output, fi)))tracking_results = segmenter.process_video(frame_dir, frame_names, queries,on_segment=_feed_segment,on_segment_output=_feed_segment_gpu,)if _perf_metrics is not None:39 unmodified linesseg._perf_metrics = _perf_metricsseg._perf_lock = _actual_lock# Phase 2: Init SAM2 models/state per GPU (parallel)if _perf_metrics is not None:_t_init = time.perf_counter()14 unmodified lines_perf_metrics["init_state_ms"] = (time.perf_counter() - _t_init) * 1000.0_t_track = time.perf_counter()# Phase 3: Parallel segment processing (queue-based workers)segments = list(range(0, total_frames, step))num_total_segments = len(segments)156 unmodified lineselse {})render_in.put((fi, tracking_results.get(fi, {})))next_seg_idx += 1continue21 unmodified lines):tracking_results[fi] = {}render_in.put((fi, {}))next_seg_idx += 1continue30 unmodified linesLazyFrameObjects(segment_output, fi, remapping),))next_seg_idx += 1for t in seg_workers:1276 unmodified lines12771278127912801281128212839 unmodified lines129312941295129612971298129913001301130213031304130517 unmodified lines1323132413251326132713281329153 unmodified lines1483148414851486148714881489135 unmodified lines16251626162716281629163016311632163358 unmodified lines169216931694169516961697169817 unmodified lines1716171717181719172017211722172349 unmodified lines1773177417751776177717781779178017 unmodified lines1798179918001801180218031804180511 unmodified lines181718181819182018211822182318241825182618271828182939 unmodified lines1869187018711872187318741875187614 unmodified lines18911892189318941895189618971898156 unmodified lines2055205620572058205920602061206221 unmodified lines2084208520862087208820892090209130 unmodified lines212221232124212521262127212821291276 unmodified lines_perf_lock=None,num_maskmem: Optional[int] = None,detector_name: Optional[str] = None,_ttfs_t0: Optional[float] = None,) -> str:"""Run Grounded-SAM-2 video tracking pipeline.9 unmodified linesfrom models.segmenters.grounded_sam2 import MaskDictionary, ObjectInfo, LazyFrameObjectsactive_segmenter = segmenter_name or "GSAM2-L"def _ttfs(msg):if _ttfs_t0 is not None:logging.info("[TTFS:%s] +%.1fs %s", job_id, time.perf_counter() - _ttfs_t0, msg)_ttfs("enter run_grounded_sam2_tracking")logging.info("Grounded-SAM-2 tracking: segmenter=%s, queries=%s, step=%d",active_segmenter, queries, step,17 unmodified linesif _perf_metrics is not None:_perf_metrics["frame_extraction_ms"] = (time.perf_counter() - _t_ext) * 1000.0total_frames = len(frame_names)_ttfs(f"frame_extraction done ({total_frames} frames)")logging.info("Extracted %d frames to %s", total_frames, frame_dir)num_gpus = torch.cuda.device_count()153 unmodified linesdef _writer_loop():nonlocal render_done_first_deposit = Falsenext_idx = 0buf: Dict[int, Tuple] = {}135 unmodified linesif stream_queue or job_id:with _stream_lock:_stream_deque.append(frm)if not _first_deposit:_first_deposit = True_ttfs("first_frame_deposited_to_deque")next_idx += 1if next_idx % 30 == 0:58 unmodified lines"accumulated=%d frames in %.1fs",r_prod, r_stream, accumulated, elapsed,)_ttfs(f"publisher: startup_wait done ({accumulated} frames in {elapsed:.1f}s)")# --- Phase 2: adaptive streaming ---last_adjust = time.perf_counter()17 unmodified linesstream_queue.put(frame, timeout=0.01)except Exception:passif published == 0:_ttfs("first_publish_frame")published += 1last_publish_time = time.perf_counter()time.sleep(frame_interval)49 unmodified lines_publisher_thread = Thread(target=_stream_publisher_thread, daemon=True)_publisher_thread.start()_ttfs("writer+publisher threads started")# ==================================================================# Phase 1-4: Tracking (single-GPU fallback vs multi-GPU pipeline)# Segments are fed incrementally to render_in as they complete.17 unmodified linessegmenter._perf_metrics = _perf_metricssegmenter._perf_lock = None_ttfs(f"model loaded ({active_segmenter})")if _perf_metrics is not None:_t_track = time.perf_counter()11 unmodified linesseen.add(fi)render_in.put((fi, LazyFrameObjects(segment_output, fi)))_ttfs("process_video started")tracking_results = segmenter.process_video(frame_dir, frame_names, queries,on_segment=_feed_segment,on_segment_output=_feed_segment_gpu,_ttfs_t0=_ttfs_t0,_ttfs_job_id=job_id,)if _perf_metrics is not None:39 unmodified linesseg._perf_metrics = _perf_metricsseg._perf_lock = _actual_lock_ttfs(f"model loaded ({active_segmenter}, {num_gpus} GPUs)")# Phase 2: Init SAM2 models/state per GPU (parallel)if _perf_metrics is not None:_t_init = time.perf_counter()14 unmodified lines_perf_metrics["init_state_ms"] = (time.perf_counter() - _t_init) * 1000.0_t_track = time.perf_counter()_ttfs("multi-GPU tracking started")# Phase 3: Parallel segment processing (queue-based workers)segments = list(range(0, total_frames, step))num_total_segments = len(segments)156 unmodified lineselse {})render_in.put((fi, tracking_results.get(fi, {})))if next_seg_idx == 0:_ttfs("first_segment_reconciled (multi-GPU, no detections)")next_seg_idx += 1continue21 unmodified lines):tracking_results[fi] = {}render_in.put((fi, {}))if next_seg_idx == 0:_ttfs("first_segment_reconciled (multi-GPU, empty masks)")next_seg_idx += 1continue30 unmodified linesLazyFrameObjects(segment_output, fi, remapping),))if next_seg_idx == 0:_ttfs("first_segment_reconciled (multi-GPU)")next_seg_idx += 1for t in seg_workers:
39 unmodified lines40414243444539 unmodified linesfirst_frame_gpt_results=job.first_frame_gpt_results,num_maskmem=7,detector_name=job.detector_name,)else:detections_list = None39 unmodified lines4041424344454639 unmodified linesfirst_frame_gpt_results=job.first_frame_gpt_results,num_maskmem=7,detector_name=job.detector_name,_ttfs_t0=job.ttfs_t0,)else:detections_list = None
37 unmodified lines38394037 unmodified linesmission_spec: Optional[Any] = None # utils.schemas.MissionSpecificationmission_mode: str = "LEGACY" # "MISSION" or "LEGACY"first_frame_gpt_results: Optional[Dict[str, Any]] = None # Cached GPT results from process_first_frame37 unmodified lines3839404137 unmodified linesmission_spec: Optional[Any] = None # utils.schemas.MissionSpecificationmission_mode: str = "LEGACY" # "MISSION" or "LEGACY"first_frame_gpt_results: Optional[Dict[str, Any]] = None # Cached GPT results from process_first_framettfs_t0: Optional[float] = None # TTFS anchor: time.perf_counter() at endpoint entry
714 unmodified lines71571671771871972098 unmodified lines81982082182282382442 unmodified lines86786886987087187219 unmodified lines892893894895896897714 unmodified linestext_prompts: List[str],on_segment: Optional[Callable[[Dict[int, Dict[int, "ObjectInfo"]]], None]] = None,on_segment_output: Optional[Callable[["SegmentOutput"], None]] = None,) -> Dict[int, Dict[int, ObjectInfo]]:"""Run full Grounded-SAM-2 tracking pipeline on extracted JPEG frames.98 unmodified linesseg_results[fi] = all_results[fi]if on_segment and seg_results:on_segment(seg_results)continue# -- SAM2 image predictor on keyframe --42 unmodified linesseg_results_empty[fi] = {}if on_segment:on_segment(seg_results_empty)continue# -- SAM2 video predictor: propagate masks --19 unmodified linessam2_masks.mask_width = first_info.mask.shape[-1] if first_info.mask.ndim >= 2 else 0if on_segment_output is not None:on_segment_output(segment_output)logging.info("Grounded-SAM-2 tracking complete: %d frames, %d tracked objects",714 unmodified lines71571671771871972072172298 unmodified lines82182282382482582682782882942 unmodified lines87287387487587687787887988019 unmodified lines900901902903904905906907908714 unmodified linestext_prompts: List[str],on_segment: Optional[Callable[[Dict[int, Dict[int, "ObjectInfo"]]], None]] = None,on_segment_output: Optional[Callable[["SegmentOutput"], None]] = None,_ttfs_t0: Optional[float] = None,_ttfs_job_id: Optional[str] = None,) -> Dict[int, Dict[int, ObjectInfo]]:"""Run full Grounded-SAM-2 tracking pipeline on extracted JPEG frames.98 unmodified linesseg_results[fi] = all_results[fi]if on_segment and seg_results:on_segment(seg_results)if start_idx == 0 and _ttfs_t0 is not None:logging.info("[TTFS:%s] +%.1fs first_segment_complete (no detections, step=%d)",_ttfs_job_id, time.perf_counter() - _ttfs_t0, step)continue# -- SAM2 image predictor on keyframe --42 unmodified linesseg_results_empty[fi] = {}if on_segment:on_segment(seg_results_empty)if start_idx == 0 and _ttfs_t0 is not None:logging.info("[TTFS:%s] +%.1fs first_segment_complete (empty masks, step=%d)",_ttfs_job_id, time.perf_counter() - _ttfs_t0, step)continue# -- SAM2 video predictor: propagate masks --19 unmodified linessam2_masks.mask_width = first_info.mask.shape[-1] if first_info.mask.ndim >= 2 else 0if on_segment_output is not None:on_segment_output(segment_output)if start_idx == 0 and _ttfs_t0 is not None:logging.info("[TTFS:%s] +%.1fs first_segment_complete (step=%d)",_ttfs_job_id, time.perf_counter() - _ttfs_t0, step)logging.info("Grounded-SAM-2 tracking complete: %d frames, %d tracked objects",
app.py+28
inference.py+33
jobs/background.py+1
jobs/models.py+1
models/segmenters/grounded_sam2.py+11