Spaces:
Paused
Paused
Download apps/renderer/models/loader.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 7.04 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/models/loader.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/models/loader.py
-
curl -L -o loader.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/models/loader.py
7.04 kB
| """Lazy model loading and warm-start logic.""" | |
| import time | |
| import torch | |
| import state | |
| from config.models import ( | |
| ONEFORMER_MODEL_NAME, | |
| DEPTH_MODEL_NAME, | |
| GEOMETRY_MODEL, | |
| MOGE_MODEL_NAME, | |
| SAM2_MODEL_CFG, | |
| SAM2_CHECKPOINT, | |
| SAM2_MODEL_NAME, | |
| INTRINSIC_MODEL_VERSION, | |
| ) | |
| from config.runtime import ( | |
| ENABLE_MOGE_GEOMETRY, | |
| ENABLE_SAM_REFINEMENT, | |
| ENABLE_DEPTH_ESTIMATION, | |
| ENABLE_INTRINSIC_SHADING, | |
| ENABLE_SHADING_TRANSFER, | |
| WARM_START_MODELS, | |
| ) | |
| from transformers import ( | |
| AutoImageProcessor, | |
| AutoModelForDepthEstimation, | |
| OneFormerForUniversalSegmentation, | |
| OneFormerProcessor, | |
| ) | |
| def _load_segmentation_model(): | |
| if state.seg_processor is not None and state.seg_model is not None: | |
| return | |
| print(f"Loading OneFormer: {ONEFORMER_MODEL_NAME} ...", flush=True) | |
| state.seg_processor = OneFormerProcessor.from_pretrained( | |
| ONEFORMER_MODEL_NAME, | |
| local_files_only=state.hf_offline(), | |
| ) | |
| state.seg_model = OneFormerForUniversalSegmentation.from_pretrained( | |
| ONEFORMER_MODEL_NAME, | |
| local_files_only=state.hf_offline(), | |
| ).to(state.device) | |
| state.seg_model.eval() | |
| print("OneFormer loaded.", flush=True) | |
| def _load_intrinsic_model(): | |
| if ENABLE_INTRINSIC_SHADING and state.intrinsic_models is None: | |
| try: | |
| print(f"Loading Intrinsic Image Decomposition model: {INTRINSIC_MODEL_VERSION} ...", flush=True) | |
| from intrinsic.pipeline import load_models | |
| state.intrinsic_models = load_models(INTRINSIC_MODEL_VERSION, device=str(state.device)) | |
| print("Intrinsic model loaded.", flush=True) | |
| except Exception as exc: | |
| print(f"Intrinsic model failed to load ({exc}). Falling back to luminance shading.", flush=True) | |
| def _load_depth_model() -> bool: | |
| if not ENABLE_DEPTH_ESTIMATION: | |
| return False | |
| if state.depth_processor is not None and state.depth_model is not None: | |
| return True | |
| print(f"Loading depth model: {DEPTH_MODEL_NAME} ...", flush=True) | |
| state.depth_processor = AutoImageProcessor.from_pretrained( | |
| DEPTH_MODEL_NAME, | |
| local_files_only=state.hf_offline(), | |
| ) | |
| state.depth_model = AutoModelForDepthEstimation.from_pretrained( | |
| DEPTH_MODEL_NAME, | |
| local_files_only=state.hf_offline(), | |
| ).to(state.device) | |
| state.depth_model.eval() | |
| print("Depth model loaded.", flush=True) | |
| return True | |
| def _load_moge_model() -> bool: | |
| if not ENABLE_MOGE_GEOMETRY or GEOMETRY_MODEL != "moge" or state.device.type != "cuda": | |
| return False | |
| if state.moge_model is not None: | |
| return True | |
| print(f"Loading MoGe geometry model: {MOGE_MODEL_NAME} ...", flush=True) | |
| from moge.model.v2 import MoGeModel | |
| state.moge_model = MoGeModel.from_pretrained(MOGE_MODEL_NAME).to(state.device) | |
| state.moge_model.eval() | |
| print("MoGe geometry model loaded.", flush=True) | |
| return True | |
| def _load_sam2_predictor(): | |
| if not ENABLE_SAM_REFINEMENT: | |
| return None | |
| if state.sam2_predictor is not None: | |
| return state.sam2_predictor | |
| try: | |
| from sam2.sam2_image_predictor import SAM2ImagePredictor | |
| if SAM2_MODEL_CFG and SAM2_CHECKPOINT: | |
| from sam2.build_sam import build_sam2 | |
| model = build_sam2(SAM2_MODEL_CFG, SAM2_CHECKPOINT, device=str(state.device)) | |
| model.eval() | |
| state.sam2_predictor = SAM2ImagePredictor(model) | |
| else: | |
| state.sam2_predictor = SAM2ImagePredictor.from_pretrained(SAM2_MODEL_NAME) | |
| if hasattr(state.sam2_predictor, "model"): | |
| state.sam2_predictor.model.to(state.device) | |
| state.sam2_predictor.model.eval() | |
| print("SAM2 refinement model loaded.", flush=True) | |
| return state.sam2_predictor | |
| except Exception as exc: | |
| print(f"SAM2 refinement unavailable ({exc}).", flush=True) | |
| if state.device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| return None | |
| def warm_start_models(): | |
| if not WARM_START_MODELS: | |
| print("Model warm start disabled; models will load on first use.", flush=True) | |
| return | |
| t_start = time.perf_counter() | |
| print(f"Warm-starting visualizer models on {state.device} ...", flush=True) | |
| # Try ONNX sessions first | |
| from config.runtime import ENABLE_ONNX_INFERENCE | |
| if ENABLE_ONNX_INFERENCE: | |
| from models.onnx_loader import load_seg_onnx_session, load_depth_onnx_session | |
| load_seg_onnx_session() | |
| load_depth_onnx_session() | |
| _load_segmentation_model() | |
| moge_loaded = False | |
| if ENABLE_MOGE_GEOMETRY and GEOMETRY_MODEL == "moge": | |
| try: | |
| moge_loaded = _load_moge_model() | |
| except Exception as exc: | |
| print(f"MoGe warm start skipped ({exc}); depth fallback may be used.", flush=True) | |
| if state.device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| if ENABLE_DEPTH_ESTIMATION and not moge_loaded: | |
| try: | |
| _load_depth_model() | |
| except Exception as exc: | |
| print(f"Depth model warm start skipped ({exc}); depth will be retried on first use.", flush=True) | |
| if state.device.type == "cuda": | |
| torch.cuda.empty_cache() | |
| if ENABLE_SAM_REFINEMENT: | |
| _load_sam2_predictor() | |
| if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING: | |
| _load_intrinsic_model() | |
| _warm_up_inference() | |
| print(f"[TIMING] Model warm start took {time.perf_counter() - t_start:.3f} seconds", flush=True) | |
| def _warm_up_inference(): | |
| """Run throwaway inference so the first real job doesn't pay CUDA kernel init. | |
| Loading weights alone leaves kernel compilation and autocast setup for the | |
| first request, which made post-restart jobs take 16-48s instead of ~5s. | |
| Both orientations are warmed because inference inputs are capped at | |
| INFERENCE_MAX_DIMENSION on the long side (portrait and landscape shapes). | |
| """ | |
| # Deferred: models.depth / models.segmentation import from this module. | |
| import numpy as np | |
| from PIL import Image | |
| from config.runtime import INFERENCE_MAX_DIMENSION | |
| from models.depth import estimate_scene_geometry | |
| from models.segmentation import run_segmentation | |
| long_side = INFERENCE_MAX_DIMENSION | |
| short_side = round(long_side * 0.75) | |
| rng = np.random.default_rng(0) | |
| for w, h in ((short_side, long_side), (long_side, short_side)): | |
| t0 = time.perf_counter() | |
| try: | |
| img_np = rng.integers(0, 256, size=(h, w, 3), dtype=np.uint8) | |
| img = Image.fromarray(img_np) | |
| run_segmentation(img, img_np) | |
| estimate_scene_geometry(img, img_np, w, h) | |
| if state.device.type == "cuda": | |
| torch.cuda.synchronize() | |
| print(f"[TIMING] Warm-up inference {w}x{h} took {time.perf_counter() - t0:.3f} seconds", flush=True) | |
| except Exception as exc: | |
| print(f"Warm-up inference {w}x{h} skipped ({exc}); first job may be slower.", flush=True) | |