File size: 2,504 Bytes
1003449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""ONNX Runtime model loading for accelerated inference."""

from pathlib import Path

import state
from config.runtime import ENABLE_ONNX_INFERENCE, ONNX_MODEL_DIR

ONNX_DIR = Path(ONNX_MODEL_DIR)


def _ort_providers() -> list[str]:
    """Return available ONNX Runtime execution providers, preferring GPU."""
    providers = []
    if state.device.type == "cuda":
        providers.append("CUDAExecutionProvider")
    providers.append("CPUExecutionProvider")
    return providers


def load_seg_onnx_session():
    """Load the OneFormer ONNX session if available."""
    if not ENABLE_ONNX_INFERENCE:
        return None
    if state.seg_onnx_session is not None:
        return state.seg_onnx_session

    model_path = ONNX_DIR / "oneformer_seg.onnx"
    if not model_path.exists():
        print(f"ONNX segmentation model not found at {model_path}, falling back to PyTorch.", flush=True)
        return None

    try:
        import onnxruntime as ort
        sess_options = ort.SessionOptions()
        sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
        state.seg_onnx_session = ort.InferenceSession(
            str(model_path), sess_options, providers=_ort_providers(),
        )
        print(f"ONNX segmentation model loaded from {model_path}", flush=True)
        return state.seg_onnx_session
    except Exception as exc:
        print(f"Failed to load ONNX segmentation model ({exc}), falling back to PyTorch.", flush=True)
        return None


def load_depth_onnx_session():
    """Load the Depth-Anything ONNX session if available."""
    if not ENABLE_ONNX_INFERENCE:
        return None
    if state.depth_onnx_session is not None:
        return state.depth_onnx_session

    model_path = ONNX_DIR / "depth_anything.onnx"
    if not model_path.exists():
        print(f"ONNX depth model not found at {model_path}, falling back to PyTorch.", flush=True)
        return None

    try:
        import onnxruntime as ort
        sess_options = ort.SessionOptions()
        sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
        state.depth_onnx_session = ort.InferenceSession(
            str(model_path), sess_options, providers=_ort_providers(),
        )
        print(f"ONNX depth model loaded from {model_path}", flush=True)
        return state.depth_onnx_session
    except Exception as exc:
        print(f"Failed to load ONNX depth model ({exc}), falling back to PyTorch.", flush=True)
        return None