linml 0.6.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- linml/__init__.py +44 -0
- linml/binary.py +140 -0
- linml/cli.py +176 -0
- linml/client.py +118 -0
- linml/models.py +328 -0
- linml/session.py +247 -0
- linml-0.6.2.dist-info/METADATA +108 -0
- linml-0.6.2.dist-info/RECORD +11 -0
- linml-0.6.2.dist-info/WHEEL +5 -0
- linml-0.6.2.dist-info/entry_points.txt +2 -0
- linml-0.6.2.dist-info/top_level.txt +1 -0
linml/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""LinML: Linux ONNX Runtime inference integration layer and client library."""
|
|
2
|
+
|
|
3
|
+
from .binary import find_linml_binary, get_linml_binary
|
|
4
|
+
from .client import InferenceClient
|
|
5
|
+
from .cli import bench, doctor, inspect, providers_list, run, setup
|
|
6
|
+
from .models import (
|
|
7
|
+
CompatibilityFinding,
|
|
8
|
+
HealthResponse,
|
|
9
|
+
InferenceResult,
|
|
10
|
+
ModelGraphMetadata,
|
|
11
|
+
ModelIdentity,
|
|
12
|
+
ModelInspectionReport,
|
|
13
|
+
ModelTensorMetadata,
|
|
14
|
+
OpsetImport,
|
|
15
|
+
TensorOutput,
|
|
16
|
+
TensorSpec,
|
|
17
|
+
)
|
|
18
|
+
from .session import InferenceSession
|
|
19
|
+
|
|
20
|
+
__version__ = "0.6.2"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"InferenceClient",
|
|
24
|
+
"InferenceSession",
|
|
25
|
+
"InferenceResult",
|
|
26
|
+
"TensorSpec",
|
|
27
|
+
"TensorOutput",
|
|
28
|
+
"HealthResponse",
|
|
29
|
+
"ModelInspectionReport",
|
|
30
|
+
"ModelIdentity",
|
|
31
|
+
"ModelTensorMetadata",
|
|
32
|
+
"ModelGraphMetadata",
|
|
33
|
+
"OpsetImport",
|
|
34
|
+
"CompatibilityFinding",
|
|
35
|
+
"find_linml_binary",
|
|
36
|
+
"get_linml_binary",
|
|
37
|
+
"inspect",
|
|
38
|
+
"run",
|
|
39
|
+
"doctor",
|
|
40
|
+
"providers_list",
|
|
41
|
+
"setup",
|
|
42
|
+
"bench",
|
|
43
|
+
"__version__",
|
|
44
|
+
]
|
linml/binary.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Dict, List, Optional
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_dotnet_env() -> Dict[str, str]:
|
|
12
|
+
"""Return an environment dictionary with DOTNET_ROOT and PATH configured if ~/.dotnet exists."""
|
|
13
|
+
env = os.environ.copy()
|
|
14
|
+
user_dotnet = Path.home() / ".dotnet"
|
|
15
|
+
if user_dotnet.is_dir():
|
|
16
|
+
if "DOTNET_ROOT" not in env:
|
|
17
|
+
env["DOTNET_ROOT"] = str(user_dotnet)
|
|
18
|
+
current_path = env.get("PATH", "")
|
|
19
|
+
if str(user_dotnet) not in current_path.split(os.pathsep):
|
|
20
|
+
env["PATH"] = f"{user_dotnet}{os.pathsep}{current_path}"
|
|
21
|
+
return env
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def find_linml_binary() -> Optional[List[str]]:
|
|
25
|
+
"""Locate the linml executable or dotnet command to run the CLI.
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
List of command arguments (e.g. ['/path/to/linml'] or ['dotnet', '/path/to/linml.dll'])
|
|
29
|
+
or None if not found.
|
|
30
|
+
"""
|
|
31
|
+
# 1. Explicit environment override
|
|
32
|
+
env_bin = os.environ.get("LINML_BIN")
|
|
33
|
+
if env_bin:
|
|
34
|
+
bin_path = Path(env_bin).resolve()
|
|
35
|
+
if not bin_path.is_file():
|
|
36
|
+
raise ValueError(f"LINML_BIN points to non-existent file: {env_bin}")
|
|
37
|
+
if env_bin.endswith(".dll"):
|
|
38
|
+
dotnet = shutil.which("dotnet") or str(Path.home() / ".dotnet" / "dotnet")
|
|
39
|
+
return [dotnet, str(bin_path)]
|
|
40
|
+
return [str(bin_path)]
|
|
41
|
+
|
|
42
|
+
# 2. Packaged binary within python wheel directory
|
|
43
|
+
pkg_dir = Path(__file__).resolve().parent
|
|
44
|
+
bundled_bin = pkg_dir / "bin" / "linml"
|
|
45
|
+
if bundled_bin.is_file() and os.access(bundled_bin, os.X_OK):
|
|
46
|
+
return [str(bundled_bin)]
|
|
47
|
+
|
|
48
|
+
# 3. System PATH lookup. Exclude the Python entry point wrapper script to prevent self-invocation loops.
|
|
49
|
+
path_bin = shutil.which("linml")
|
|
50
|
+
if path_bin:
|
|
51
|
+
path_path = Path(path_bin).resolve()
|
|
52
|
+
wrapper_paths = set()
|
|
53
|
+
if sys.argv and sys.argv[0]:
|
|
54
|
+
try:
|
|
55
|
+
wrapper_paths.add(Path(sys.argv[0]).resolve())
|
|
56
|
+
except Exception:
|
|
57
|
+
pass
|
|
58
|
+
wrapper_paths.add((Path(sys.executable).parent / "linml").resolve())
|
|
59
|
+
|
|
60
|
+
is_python_wrapper = path_path in wrapper_paths
|
|
61
|
+
if not is_python_wrapper:
|
|
62
|
+
try:
|
|
63
|
+
with open(path_path, "rb") as stream:
|
|
64
|
+
shebang = stream.readline(256).lower()
|
|
65
|
+
is_python_wrapper = shebang.startswith(b"#!") and b"python" in shebang
|
|
66
|
+
except (OSError, UnicodeError):
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
if not is_python_wrapper:
|
|
70
|
+
return [str(path_path)]
|
|
71
|
+
|
|
72
|
+
# 4. Standard Linux user install directories
|
|
73
|
+
user_candidates = [
|
|
74
|
+
Path.home() / ".local" / "bin" / "linml",
|
|
75
|
+
Path.home() / ".local" / "share" / "linml" / "linml",
|
|
76
|
+
]
|
|
77
|
+
for cand in user_candidates:
|
|
78
|
+
if cand.is_file() and os.access(cand, os.X_OK):
|
|
79
|
+
return [str(cand)]
|
|
80
|
+
|
|
81
|
+
# 5. Repository local build outputs
|
|
82
|
+
repo_root = pkg_dir.parent.parent.parent
|
|
83
|
+
|
|
84
|
+
# Self-contained published native binary (no external runtime required)
|
|
85
|
+
published_bin = repo_root / "artifacts" / "publish" / "linux-x64" / "linml"
|
|
86
|
+
if published_bin.is_file() and os.access(published_bin, os.X_OK):
|
|
87
|
+
return [str(published_bin)]
|
|
88
|
+
|
|
89
|
+
# 6. Repository compiled .dll via dotnet host
|
|
90
|
+
dotnet = shutil.which("dotnet")
|
|
91
|
+
if not dotnet:
|
|
92
|
+
user_dotnet_bin = Path.home() / ".dotnet" / "dotnet"
|
|
93
|
+
if user_dotnet_bin.is_file() and os.access(user_dotnet_bin, os.X_OK):
|
|
94
|
+
dotnet = str(user_dotnet_bin)
|
|
95
|
+
|
|
96
|
+
if dotnet:
|
|
97
|
+
dll_candidates = [
|
|
98
|
+
repo_root / "src" / "LinML.Cli" / "bin" / "Release" / "net10.0" / "linml.dll",
|
|
99
|
+
repo_root / "src" / "LinML.Cli" / "bin" / "Debug" / "net10.0" / "linml.dll",
|
|
100
|
+
repo_root / "artifacts" / "publish" / "linux-x64" / "linml.dll",
|
|
101
|
+
]
|
|
102
|
+
for dll in dll_candidates:
|
|
103
|
+
if dll.is_file():
|
|
104
|
+
return [dotnet, str(dll)]
|
|
105
|
+
|
|
106
|
+
# 7. Framework-dependent apphost binary fallback
|
|
107
|
+
apphost_candidates = [
|
|
108
|
+
repo_root / "src" / "LinML.Cli" / "bin" / "Release" / "net10.0" / "linml",
|
|
109
|
+
repo_root / "src" / "LinML.Cli" / "bin" / "Debug" / "net10.0" / "linml",
|
|
110
|
+
]
|
|
111
|
+
for cand in apphost_candidates:
|
|
112
|
+
if cand.is_file() and os.access(cand, os.X_OK):
|
|
113
|
+
return [str(cand)]
|
|
114
|
+
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def get_linml_binary() -> List[str]:
|
|
119
|
+
"""Return the linml command or raise RuntimeError if not found."""
|
|
120
|
+
cmd = find_linml_binary()
|
|
121
|
+
if not cmd:
|
|
122
|
+
raise RuntimeError(
|
|
123
|
+
"Could not find the 'linml' executable. "
|
|
124
|
+
"Please ensure 'linml' is in your PATH, set the LINML_BIN environment variable, "
|
|
125
|
+
"or run 'bash scripts/install.sh'."
|
|
126
|
+
)
|
|
127
|
+
return cmd
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def run_linml_cli(args: List[str], check: bool = True) -> subprocess.CompletedProcess:
|
|
131
|
+
"""Execute linml CLI command with arguments."""
|
|
132
|
+
base_cmd = get_linml_binary()
|
|
133
|
+
full_cmd = base_cmd + args
|
|
134
|
+
return subprocess.run(
|
|
135
|
+
full_cmd,
|
|
136
|
+
capture_output=True,
|
|
137
|
+
text=True,
|
|
138
|
+
check=check,
|
|
139
|
+
env=get_dotnet_env(),
|
|
140
|
+
)
|
linml/cli.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, List, Optional, Union
|
|
9
|
+
|
|
10
|
+
from .binary import get_dotnet_env, get_linml_binary, run_linml_cli
|
|
11
|
+
from .models import InferenceResult, ModelInspectionReport, TensorSpec
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def inspect(model_path: Union[str, Path]) -> ModelInspectionReport:
|
|
15
|
+
"""Inspect ONNX model graph structure, inputs/outputs, and EP compatibility."""
|
|
16
|
+
model_str = str(Path(model_path).resolve())
|
|
17
|
+
proc = run_linml_cli(["inspect", "--model", model_str, "--json"])
|
|
18
|
+
data = json.loads(proc.stdout)
|
|
19
|
+
return ModelInspectionReport.from_dict(data)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def run(
|
|
23
|
+
model_path: Union[str, Path],
|
|
24
|
+
inputs: Union[str, Path, Dict[str, Any], List[Union[TensorSpec, Dict[str, Any]]]],
|
|
25
|
+
provider: Optional[str] = None,
|
|
26
|
+
require_provider: bool = False,
|
|
27
|
+
profile: bool = False,
|
|
28
|
+
ep_options: Optional[Dict[str, str]] = None,
|
|
29
|
+
) -> InferenceResult:
|
|
30
|
+
"""Execute one-shot inference using the linml CLI."""
|
|
31
|
+
model_str = str(Path(model_path).resolve())
|
|
32
|
+
temp_inputs_file = None
|
|
33
|
+
|
|
34
|
+
if isinstance(inputs, (str, Path)):
|
|
35
|
+
inputs_path = str(Path(inputs).resolve())
|
|
36
|
+
else:
|
|
37
|
+
# Convert in-memory inputs to temporary JSON file
|
|
38
|
+
tensor_specs: List[Dict[str, Any]] = []
|
|
39
|
+
if isinstance(inputs, dict):
|
|
40
|
+
for name, val in inputs.items():
|
|
41
|
+
if isinstance(val, TensorSpec):
|
|
42
|
+
tensor_specs.append(val.to_dict())
|
|
43
|
+
else:
|
|
44
|
+
spec = TensorSpec.from_any(name=name, value=val)
|
|
45
|
+
tensor_specs.append(spec.to_dict())
|
|
46
|
+
elif isinstance(inputs, list):
|
|
47
|
+
for item in inputs:
|
|
48
|
+
if isinstance(item, TensorSpec):
|
|
49
|
+
tensor_specs.append(item.to_dict())
|
|
50
|
+
elif isinstance(item, dict):
|
|
51
|
+
tensor_specs.append(item)
|
|
52
|
+
else:
|
|
53
|
+
raise ValueError(f"Unsupported input item: {type(item)}")
|
|
54
|
+
else:
|
|
55
|
+
raise ValueError("Invalid inputs parameter.")
|
|
56
|
+
|
|
57
|
+
temp_inputs_file = tempfile.NamedTemporaryFile(
|
|
58
|
+
mode="w", suffix=".json", delete=False, encoding="utf-8"
|
|
59
|
+
)
|
|
60
|
+
json.dump({"tensors": tensor_specs}, temp_inputs_file)
|
|
61
|
+
temp_inputs_file.close()
|
|
62
|
+
inputs_path = temp_inputs_file.name
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
args = ["run", "--model", model_str, "--inputs", inputs_path, "--json"]
|
|
66
|
+
if provider:
|
|
67
|
+
args.extend(["--provider", provider])
|
|
68
|
+
if require_provider:
|
|
69
|
+
args.append("--require-provider")
|
|
70
|
+
if profile:
|
|
71
|
+
args.append("--profile")
|
|
72
|
+
if ep_options:
|
|
73
|
+
for k, v in ep_options.items():
|
|
74
|
+
args.extend(["--ep-option", f"{k}={v}"])
|
|
75
|
+
|
|
76
|
+
proc = run_linml_cli(args)
|
|
77
|
+
data = json.loads(proc.stdout)
|
|
78
|
+
return InferenceResult.from_dict(data)
|
|
79
|
+
finally:
|
|
80
|
+
if temp_inputs_file and os.path.exists(temp_inputs_file.name):
|
|
81
|
+
try:
|
|
82
|
+
os.remove(temp_inputs_file.name)
|
|
83
|
+
except OSError:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def doctor(
|
|
88
|
+
model: Optional[Union[str, Path]] = None,
|
|
89
|
+
inputs: Optional[Union[str, Path]] = None,
|
|
90
|
+
) -> Dict[str, Any]:
|
|
91
|
+
"""Run linml doctor diagnostic probe."""
|
|
92
|
+
if model is not None and inputs is None:
|
|
93
|
+
raise ValueError("inputs must be provided when model is specified for linml.doctor()")
|
|
94
|
+
|
|
95
|
+
args = ["doctor", "--json"]
|
|
96
|
+
if model:
|
|
97
|
+
args.extend(["--model", str(Path(model).resolve())])
|
|
98
|
+
if inputs:
|
|
99
|
+
args.extend(["--inputs", str(Path(inputs).resolve())])
|
|
100
|
+
proc = run_linml_cli(args)
|
|
101
|
+
return json.loads(proc.stdout)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def providers_list() -> Dict[str, Any]:
|
|
105
|
+
"""Query available execution providers and detected hardware."""
|
|
106
|
+
proc = run_linml_cli(["providers", "list", "--json"])
|
|
107
|
+
return json.loads(proc.stdout)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def setup(
|
|
111
|
+
dry_run: bool = False,
|
|
112
|
+
all_plugins: bool = False,
|
|
113
|
+
force: bool = False,
|
|
114
|
+
root: Optional[Union[str, Path]] = None,
|
|
115
|
+
) -> Dict[str, Any]:
|
|
116
|
+
"""Run hardware-aware auto-setup."""
|
|
117
|
+
args = ["setup", "--json"]
|
|
118
|
+
if dry_run:
|
|
119
|
+
args.append("--dry-run")
|
|
120
|
+
if all_plugins:
|
|
121
|
+
args.append("--all")
|
|
122
|
+
if force:
|
|
123
|
+
args.append("--force")
|
|
124
|
+
if root:
|
|
125
|
+
args.extend(["--root", str(Path(root).resolve())])
|
|
126
|
+
proc = run_linml_cli(args)
|
|
127
|
+
return json.loads(proc.stdout)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def bench(
|
|
131
|
+
model_path: Union[str, Path],
|
|
132
|
+
inputs_path: Union[str, Path],
|
|
133
|
+
provider: Optional[str] = None,
|
|
134
|
+
all_ready: bool = False,
|
|
135
|
+
warmup: int = 5,
|
|
136
|
+
iterations: int = 50,
|
|
137
|
+
) -> Dict[str, Any]:
|
|
138
|
+
"""Run inference benchmarks across execution providers."""
|
|
139
|
+
args = [
|
|
140
|
+
"bench",
|
|
141
|
+
"--model", str(Path(model_path).resolve()),
|
|
142
|
+
"--inputs", str(Path(inputs_path).resolve()),
|
|
143
|
+
"--warmup", str(warmup),
|
|
144
|
+
"--iterations", str(iterations),
|
|
145
|
+
"--json",
|
|
146
|
+
]
|
|
147
|
+
if provider:
|
|
148
|
+
args.extend(["--provider", provider])
|
|
149
|
+
if all_ready:
|
|
150
|
+
args.append("--all-ready")
|
|
151
|
+
proc = run_linml_cli(args)
|
|
152
|
+
return json.loads(proc.stdout)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def main():
|
|
156
|
+
"""Forward CLI invocations to the underlying linml binary."""
|
|
157
|
+
import subprocess
|
|
158
|
+
|
|
159
|
+
if os.environ.get("LINML_PY_WRAPPER") == "1":
|
|
160
|
+
sys.stderr.write("Error: linml Python wrapper cannot launch itself recursively.\n")
|
|
161
|
+
sys.exit(1)
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
base_cmd = get_linml_binary()
|
|
165
|
+
except Exception as e:
|
|
166
|
+
sys.stderr.write(f"Error: {e}\n")
|
|
167
|
+
sys.exit(1)
|
|
168
|
+
|
|
169
|
+
full_cmd = base_cmd + sys.argv[1:]
|
|
170
|
+
env = get_dotnet_env()
|
|
171
|
+
env["LINML_PY_WRAPPER"] = "1"
|
|
172
|
+
try:
|
|
173
|
+
res = subprocess.run(full_cmd, env=env)
|
|
174
|
+
sys.exit(res.returncode)
|
|
175
|
+
except KeyboardInterrupt:
|
|
176
|
+
sys.exit(130)
|
linml/client.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import urllib.error
|
|
5
|
+
import urllib.parse
|
|
6
|
+
import urllib.request
|
|
7
|
+
from typing import Any, Dict, List, Optional, Union
|
|
8
|
+
|
|
9
|
+
from .models import HealthResponse, InferenceResult, TensorSpec
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class InferenceClient:
|
|
13
|
+
"""Client for communicating with a running LinML serve HTTP daemon."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, endpoint: str = "http://127.0.0.1:8080", timeout: float = 30.0):
|
|
16
|
+
self.endpoint = endpoint.rstrip("/")
|
|
17
|
+
self.timeout = timeout
|
|
18
|
+
|
|
19
|
+
def health(self) -> HealthResponse:
|
|
20
|
+
"""Query the /health endpoint of the LinML server."""
|
|
21
|
+
url = f"{self.endpoint}/health"
|
|
22
|
+
req = urllib.request.Request(url, method="GET")
|
|
23
|
+
req.add_header("Accept", "application/json")
|
|
24
|
+
try:
|
|
25
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
26
|
+
body = resp.read().decode("utf-8")
|
|
27
|
+
data = json.loads(body)
|
|
28
|
+
return HealthResponse.from_dict(data)
|
|
29
|
+
except urllib.error.HTTPError as e:
|
|
30
|
+
try:
|
|
31
|
+
err_body = e.read().decode("utf-8")
|
|
32
|
+
except Exception:
|
|
33
|
+
err_body = "(unable to read error response)"
|
|
34
|
+
raise RuntimeError(f"HTTP {e.code} checking server health: {err_body}") from e
|
|
35
|
+
|
|
36
|
+
def predict(
|
|
37
|
+
self,
|
|
38
|
+
inputs: Optional[Union[Dict[str, Any], List[Union[TensorSpec, Dict[str, Any]]]]] = None,
|
|
39
|
+
**kwargs: Any,
|
|
40
|
+
) -> InferenceResult:
|
|
41
|
+
"""Submit tensor inputs to the LinML server for inference.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
inputs: Dictionary of input names to arrays/lists, or list of TensorSpec objects.
|
|
45
|
+
**kwargs: Alternate syntax passing input names as kwargs: client.predict(x=arr, mask=arr2).
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
InferenceResult with output tensors, provider info, and latency metrics.
|
|
49
|
+
"""
|
|
50
|
+
tensor_specs: List[Dict[str, Any]] = []
|
|
51
|
+
|
|
52
|
+
# Combine inputs and kwargs
|
|
53
|
+
combined: Dict[str, Any] = {}
|
|
54
|
+
if isinstance(inputs, dict):
|
|
55
|
+
combined.update(inputs)
|
|
56
|
+
combined.update(kwargs)
|
|
57
|
+
|
|
58
|
+
if combined:
|
|
59
|
+
for name, val in combined.items():
|
|
60
|
+
if isinstance(val, TensorSpec):
|
|
61
|
+
tensor_specs.append(val.to_dict())
|
|
62
|
+
else:
|
|
63
|
+
spec = TensorSpec.from_any(name=name, value=val)
|
|
64
|
+
tensor_specs.append(spec.to_dict())
|
|
65
|
+
elif isinstance(inputs, list):
|
|
66
|
+
for item in inputs:
|
|
67
|
+
if isinstance(item, TensorSpec):
|
|
68
|
+
tensor_specs.append(item.to_dict())
|
|
69
|
+
elif isinstance(item, dict):
|
|
70
|
+
tensor_specs.append(item)
|
|
71
|
+
else:
|
|
72
|
+
raise ValueError(f"Unsupported input item in list: {type(item)}")
|
|
73
|
+
else:
|
|
74
|
+
raise ValueError("No tensor inputs provided to predict().")
|
|
75
|
+
|
|
76
|
+
payload = json.dumps({"tensors": tensor_specs}).encode("utf-8")
|
|
77
|
+
|
|
78
|
+
url = f"{self.endpoint}/v1/models/predict"
|
|
79
|
+
req = urllib.request.Request(url, data=payload, method="POST")
|
|
80
|
+
req.add_header("Content-Type", "application/json")
|
|
81
|
+
req.add_header("Accept", "application/json")
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
85
|
+
body = resp.read().decode("utf-8")
|
|
86
|
+
data = json.loads(body)
|
|
87
|
+
return InferenceResult.from_dict(data)
|
|
88
|
+
except urllib.error.HTTPError as e:
|
|
89
|
+
try:
|
|
90
|
+
err_body = e.read().decode("utf-8")
|
|
91
|
+
except Exception:
|
|
92
|
+
err_body = "(unable to read error response)"
|
|
93
|
+
raise RuntimeError(f"HTTP {e.code} during inference: {err_body}") from e
|
|
94
|
+
|
|
95
|
+
def shutdown(self) -> bool:
|
|
96
|
+
"""Send graceful shutdown signal to the LinML HTTP daemon."""
|
|
97
|
+
url = f"{self.endpoint}/shutdown"
|
|
98
|
+
req = urllib.request.Request(url, data=b"{}", method="POST")
|
|
99
|
+
req.add_header("Content-Type", "application/json")
|
|
100
|
+
try:
|
|
101
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
102
|
+
return resp.status == 200
|
|
103
|
+
except urllib.error.HTTPError as e:
|
|
104
|
+
if e.code == 403:
|
|
105
|
+
raise PermissionError("Shutdown route rejected: remote clients cannot trigger shutdown.") from e
|
|
106
|
+
return False
|
|
107
|
+
except Exception:
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
def close(self):
|
|
111
|
+
"""Close client resources."""
|
|
112
|
+
pass
|
|
113
|
+
|
|
114
|
+
def __enter__(self) -> "InferenceClient":
|
|
115
|
+
return self
|
|
116
|
+
|
|
117
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
118
|
+
self.close()
|
linml/models.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any, Dict, List, Optional, Union
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
HAS_NUMPY = True
|
|
10
|
+
except ImportError:
|
|
11
|
+
HAS_NUMPY = False
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class TensorSpec:
|
|
16
|
+
name: str
|
|
17
|
+
data_type: str = "float32"
|
|
18
|
+
shape: List[int] = field(default_factory=list)
|
|
19
|
+
data: List[Union[float, int, bool]] = field(default_factory=list)
|
|
20
|
+
|
|
21
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
22
|
+
return {
|
|
23
|
+
"name": self.name,
|
|
24
|
+
"type": self.data_type,
|
|
25
|
+
"shape": self.shape,
|
|
26
|
+
"data": self.data,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def from_any(cls, name: str, value: Any, data_type: Optional[str] = None) -> "TensorSpec":
|
|
31
|
+
"""Convert a list, scalar, or numpy array to TensorSpec."""
|
|
32
|
+
if HAS_NUMPY and isinstance(value, np.ndarray):
|
|
33
|
+
if np.issubdtype(value.dtype, np.bool_):
|
|
34
|
+
raise ValueError(
|
|
35
|
+
"Boolean tensors are not currently supported by LinML. "
|
|
36
|
+
"Convert to numeric (e.g. int32 or float32) before inference."
|
|
37
|
+
)
|
|
38
|
+
shape = list(value.shape)
|
|
39
|
+
flat = value.flatten().tolist()
|
|
40
|
+
if data_type is None:
|
|
41
|
+
if np.issubdtype(value.dtype, np.floating):
|
|
42
|
+
data_type = "float16" if value.dtype == np.float16 else "float32"
|
|
43
|
+
elif np.issubdtype(value.dtype, np.integer):
|
|
44
|
+
data_type = "int64" if value.dtype == np.int64 else "int32"
|
|
45
|
+
else:
|
|
46
|
+
data_type = "float32"
|
|
47
|
+
return cls(name=name, data_type=data_type, shape=shape, data=flat)
|
|
48
|
+
|
|
49
|
+
if isinstance(value, (list, tuple)):
|
|
50
|
+
shape, flat = _infer_shape_and_flatten(value)
|
|
51
|
+
if any(isinstance(x, bool) for x in flat):
|
|
52
|
+
raise ValueError(
|
|
53
|
+
"Boolean tensors are not currently supported by LinML. "
|
|
54
|
+
"Convert to numeric (e.g. int32 or float32) before inference."
|
|
55
|
+
)
|
|
56
|
+
dtype = data_type or ("int64" if all(isinstance(x, int) for x in flat) else "float32")
|
|
57
|
+
return cls(name=name, data_type=dtype, shape=shape, data=flat)
|
|
58
|
+
|
|
59
|
+
if isinstance(value, bool):
|
|
60
|
+
raise ValueError(
|
|
61
|
+
"Boolean tensors are not currently supported by LinML. "
|
|
62
|
+
"Convert to numeric (e.g. int32 or float32) before inference."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Scalar
|
|
66
|
+
dtype = data_type or ("int64" if isinstance(value, int) else "float32")
|
|
67
|
+
return cls(name=name, data_type=dtype, shape=[], data=[value])
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _infer_shape_and_flatten(nested: Any) -> tuple[List[int], List[Any]]:
|
|
71
|
+
if not isinstance(nested, (list, tuple)):
|
|
72
|
+
return [], [nested]
|
|
73
|
+
shape = [len(nested)]
|
|
74
|
+
if len(nested) == 0:
|
|
75
|
+
return shape, []
|
|
76
|
+
|
|
77
|
+
first = nested[0]
|
|
78
|
+
if isinstance(first, (list, tuple)):
|
|
79
|
+
sub_shape, _ = _infer_shape_and_flatten(first)
|
|
80
|
+
shape.extend(sub_shape)
|
|
81
|
+
|
|
82
|
+
flat: List[Any] = []
|
|
83
|
+
|
|
84
|
+
def _flatten(item: Any):
|
|
85
|
+
if isinstance(item, (list, tuple)):
|
|
86
|
+
for sub in item:
|
|
87
|
+
_flatten(sub)
|
|
88
|
+
else:
|
|
89
|
+
flat.append(item)
|
|
90
|
+
|
|
91
|
+
_flatten(nested)
|
|
92
|
+
return shape, flat
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _parse_duration(val: Any) -> float:
|
|
96
|
+
if isinstance(val, (int, float)):
|
|
97
|
+
return float(val)
|
|
98
|
+
if isinstance(val, str):
|
|
99
|
+
# Format: [-][d.]hh:mm:ss[.fffffff]
|
|
100
|
+
import re
|
|
101
|
+
m = re.match(r"^(?:(\d+)\.)?(\d+):(\d+):(\d+(?:\.\d+)?)$", val.strip())
|
|
102
|
+
if m:
|
|
103
|
+
days = int(m.group(1) or 0)
|
|
104
|
+
hours = int(m.group(2))
|
|
105
|
+
minutes = int(m.group(3))
|
|
106
|
+
seconds = float(m.group(4))
|
|
107
|
+
return (days * 86400 + hours * 3600 + minutes * 60 + seconds) * 1000.0
|
|
108
|
+
return 0.0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass
|
|
112
|
+
class TensorOutput:
|
|
113
|
+
name: str
|
|
114
|
+
data_type: str
|
|
115
|
+
shape: List[int]
|
|
116
|
+
data: List[Union[float, int, bool]]
|
|
117
|
+
|
|
118
|
+
def to_numpy(self) -> Any:
|
|
119
|
+
if not HAS_NUMPY:
|
|
120
|
+
raise RuntimeError("NumPy is required to use to_numpy(). Install with 'pip install numpy'.")
|
|
121
|
+
dtype_map = {
|
|
122
|
+
"float32": np.float32,
|
|
123
|
+
"float": np.float32,
|
|
124
|
+
"float16": np.float16,
|
|
125
|
+
"float64": np.float64,
|
|
126
|
+
"double": np.float64,
|
|
127
|
+
"int64": np.int64,
|
|
128
|
+
"long": np.int64,
|
|
129
|
+
"int32": np.int32,
|
|
130
|
+
"int": np.int32,
|
|
131
|
+
"int16": np.int16,
|
|
132
|
+
"int8": np.int8,
|
|
133
|
+
"uint8": np.uint8,
|
|
134
|
+
"bool": bool,
|
|
135
|
+
}
|
|
136
|
+
np_dtype = dtype_map.get(self.data_type.lower(), np.float32)
|
|
137
|
+
arr = np.array(self.data, dtype=np_dtype)
|
|
138
|
+
if self.shape is not None:
|
|
139
|
+
return arr.reshape(self.shape)
|
|
140
|
+
return arr
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass
|
|
144
|
+
class InferenceResult:
|
|
145
|
+
selected_provider: str
|
|
146
|
+
latency_ms: float
|
|
147
|
+
fallback_chain: List[Dict[str, Any]]
|
|
148
|
+
outputs: Dict[str, TensorOutput]
|
|
149
|
+
node_placements: List[Dict[str, Any]] = field(default_factory=list)
|
|
150
|
+
raw_response: Dict[str, Any] = field(default_factory=dict)
|
|
151
|
+
|
|
152
|
+
@classmethod
|
|
153
|
+
def from_dict(cls, data: Dict[str, Any]) -> "InferenceResult":
|
|
154
|
+
outputs_map: Dict[str, TensorOutput] = {}
|
|
155
|
+
for out in data.get("outputs", []):
|
|
156
|
+
name = out.get("name", "")
|
|
157
|
+
dtype = out.get("dataType", out.get("type", "float32"))
|
|
158
|
+
shape = out.get("shape", [])
|
|
159
|
+
tensor_data = out.get("data", [])
|
|
160
|
+
outputs_map[name] = TensorOutput(
|
|
161
|
+
name=name, data_type=dtype, shape=shape, data=tensor_data
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
# Parse latency: prefer latencyMs, fallback to duration TimeSpan string
|
|
165
|
+
latency_ms = data.get("latencyMs")
|
|
166
|
+
if latency_ms is None and "duration" in data:
|
|
167
|
+
latency_ms = _parse_duration(data["duration"])
|
|
168
|
+
else:
|
|
169
|
+
latency_ms = float(latency_ms or 0.0)
|
|
170
|
+
|
|
171
|
+
# Parse node placements: prefer nodePlacements, fallback to diagnostics parsing
|
|
172
|
+
node_placements = data.get("nodePlacements", [])
|
|
173
|
+
if not node_placements and "diagnostics" in data:
|
|
174
|
+
import re
|
|
175
|
+
for diag in data.get("diagnostics", []):
|
|
176
|
+
msg = diag.get("message", "")
|
|
177
|
+
m = re.match(r"Node '([^']+)' ran on (\w+)", msg)
|
|
178
|
+
if m:
|
|
179
|
+
node_placements.append({"nodeName": m.group(1), "provider": m.group(2)})
|
|
180
|
+
|
|
181
|
+
return cls(
|
|
182
|
+
selected_provider=data.get("selectedProvider", ""),
|
|
183
|
+
latency_ms=latency_ms,
|
|
184
|
+
fallback_chain=data.get("fallbackChain", []),
|
|
185
|
+
outputs=outputs_map,
|
|
186
|
+
node_placements=node_placements,
|
|
187
|
+
raw_response=data,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass
|
|
192
|
+
class HealthResponse:
|
|
193
|
+
status: str
|
|
194
|
+
service: str
|
|
195
|
+
selected_provider: str
|
|
196
|
+
fallback_chain: List[Dict[str, Any]]
|
|
197
|
+
model: Dict[str, Any]
|
|
198
|
+
process_id: Optional[int] = None
|
|
199
|
+
active_requests: int = 0
|
|
200
|
+
raw: Dict[str, Any] = field(default_factory=dict)
|
|
201
|
+
|
|
202
|
+
@classmethod
|
|
203
|
+
def from_dict(cls, data: Dict[str, Any]) -> "HealthResponse":
|
|
204
|
+
return cls(
|
|
205
|
+
status=data.get("status", "unknown"),
|
|
206
|
+
service=data.get("service", "LinML"),
|
|
207
|
+
selected_provider=data.get("selectedProvider", ""),
|
|
208
|
+
fallback_chain=data.get("fallbackChain", []),
|
|
209
|
+
model=data.get("model", {}),
|
|
210
|
+
process_id=data.get("processId"),
|
|
211
|
+
active_requests=data.get("activeRequests", 0),
|
|
212
|
+
raw=data,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@dataclass
|
|
217
|
+
class OpsetImport:
|
|
218
|
+
domain: str
|
|
219
|
+
version: int
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@dataclass
|
|
223
|
+
class ModelTensorMetadata:
|
|
224
|
+
name: str
|
|
225
|
+
data_type: str
|
|
226
|
+
shape: List[int]
|
|
227
|
+
is_dynamic: bool
|
|
228
|
+
symbolic_dimensions: List[str] = field(default_factory=list)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass
|
|
232
|
+
class ModelGraphMetadata:
|
|
233
|
+
node_count: int
|
|
234
|
+
operators: List[str] = field(default_factory=list)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@dataclass
|
|
238
|
+
class CompatibilityFinding:
|
|
239
|
+
provider: str
|
|
240
|
+
severity: str
|
|
241
|
+
message: str
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass
|
|
245
|
+
class ModelIdentity:
|
|
246
|
+
path: str
|
|
247
|
+
sha256: str
|
|
248
|
+
size_bytes: int
|
|
249
|
+
name: Optional[str] = None
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
@dataclass
|
|
253
|
+
class ModelInspectionReport:
|
|
254
|
+
model: ModelIdentity
|
|
255
|
+
ir_version: int
|
|
256
|
+
opsets: List[OpsetImport]
|
|
257
|
+
inputs: List[ModelTensorMetadata]
|
|
258
|
+
outputs: List[ModelTensorMetadata]
|
|
259
|
+
graph: ModelGraphMetadata
|
|
260
|
+
compatibility_warnings: List[CompatibilityFinding]
|
|
261
|
+
metadata: Dict[str, str] = field(default_factory=dict)
|
|
262
|
+
producer_name: Optional[str] = None
|
|
263
|
+
producer_version: Optional[str] = None
|
|
264
|
+
domain: Optional[str] = None
|
|
265
|
+
model_version: int = 0
|
|
266
|
+
description: Optional[str] = None
|
|
267
|
+
|
|
268
|
+
@classmethod
|
|
269
|
+
def from_dict(cls, data: Dict[str, Any]) -> "ModelInspectionReport":
|
|
270
|
+
model_data = data.get("model", {})
|
|
271
|
+
model_id = ModelIdentity(
|
|
272
|
+
path=model_data.get("path", ""),
|
|
273
|
+
sha256=model_data.get("sha256", ""),
|
|
274
|
+
size_bytes=model_data.get("sizeBytes", 0),
|
|
275
|
+
name=model_data.get("name"),
|
|
276
|
+
)
|
|
277
|
+
opsets = [
|
|
278
|
+
OpsetImport(domain=o.get("domain", ""), version=o.get("version", 0))
|
|
279
|
+
for o in data.get("opsetImports", data.get("opsets", []))
|
|
280
|
+
]
|
|
281
|
+
inputs = [
|
|
282
|
+
ModelTensorMetadata(
|
|
283
|
+
name=i.get("name", ""),
|
|
284
|
+
data_type=i.get("dataType", ""),
|
|
285
|
+
shape=i.get("shape", []),
|
|
286
|
+
is_dynamic=i.get("isDynamic", False),
|
|
287
|
+
symbolic_dimensions=i.get("symbolicDimensions", []),
|
|
288
|
+
)
|
|
289
|
+
for i in data.get("inputs", [])
|
|
290
|
+
]
|
|
291
|
+
outputs = [
|
|
292
|
+
ModelTensorMetadata(
|
|
293
|
+
name=o.get("name", ""),
|
|
294
|
+
data_type=o.get("dataType", ""),
|
|
295
|
+
shape=o.get("shape", []),
|
|
296
|
+
is_dynamic=o.get("isDynamic", False),
|
|
297
|
+
symbolic_dimensions=o.get("symbolicDimensions", []),
|
|
298
|
+
)
|
|
299
|
+
for o in data.get("outputs", [])
|
|
300
|
+
]
|
|
301
|
+
graph_data = data.get("graph", {})
|
|
302
|
+
graph = ModelGraphMetadata(
|
|
303
|
+
node_count=graph_data.get("nodeCount", 0),
|
|
304
|
+
operators=graph_data.get("operators", []),
|
|
305
|
+
)
|
|
306
|
+
warnings = [
|
|
307
|
+
CompatibilityFinding(
|
|
308
|
+
provider=w.get("provider", ""),
|
|
309
|
+
severity=w.get("severity", "Warning"),
|
|
310
|
+
message=w.get("message", ""),
|
|
311
|
+
)
|
|
312
|
+
for w in data.get("compatibilityWarnings", [])
|
|
313
|
+
]
|
|
314
|
+
return cls(
|
|
315
|
+
model=model_id,
|
|
316
|
+
ir_version=data.get("irVersion", 0),
|
|
317
|
+
opsets=opsets,
|
|
318
|
+
inputs=inputs,
|
|
319
|
+
outputs=outputs,
|
|
320
|
+
graph=graph,
|
|
321
|
+
compatibility_warnings=warnings,
|
|
322
|
+
metadata=data.get("metadataProps", data.get("metadata", {})),
|
|
323
|
+
producer_name=data.get("producerName"),
|
|
324
|
+
producer_version=data.get("producerVersion"),
|
|
325
|
+
domain=data.get("domain"),
|
|
326
|
+
model_version=data.get("modelVersion", 0),
|
|
327
|
+
description=data.get("description"),
|
|
328
|
+
)
|
linml/session.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import socket
|
|
5
|
+
import subprocess
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Dict, List, Optional, Union
|
|
9
|
+
|
|
10
|
+
from .binary import get_dotnet_env, get_linml_binary
|
|
11
|
+
from .client import InferenceClient
|
|
12
|
+
from .models import InferenceResult, TensorOutput, TensorSpec
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _get_free_port() -> int:
|
|
16
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
17
|
+
s.bind(("127.0.0.1", 0))
|
|
18
|
+
return s.getsockname()[1]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class InferenceSession:
|
|
22
|
+
"""Manages an active ONNX Runtime session via an embedded linml serve daemon."""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
model_path: Union[str, Path],
|
|
27
|
+
provider: Optional[str] = None,
|
|
28
|
+
require_provider: bool = False,
|
|
29
|
+
ep_options: Optional[Dict[str, str]] = None,
|
|
30
|
+
host: str = "127.0.0.1",
|
|
31
|
+
port: Optional[int] = None,
|
|
32
|
+
startup_timeout: float = 120.0,
|
|
33
|
+
request_timeout: float = 30.0,
|
|
34
|
+
):
|
|
35
|
+
self.model_path = str(Path(model_path).resolve())
|
|
36
|
+
if not os.path.isfile(self.model_path):
|
|
37
|
+
raise FileNotFoundError(f"Model file not found: {self.model_path}")
|
|
38
|
+
|
|
39
|
+
self.provider = provider
|
|
40
|
+
self.require_provider = require_provider
|
|
41
|
+
self.ep_options = ep_options or {}
|
|
42
|
+
self.host = host
|
|
43
|
+
self._user_port = port
|
|
44
|
+
self.port = port
|
|
45
|
+
self.startup_timeout = startup_timeout
|
|
46
|
+
self.request_timeout = request_timeout
|
|
47
|
+
|
|
48
|
+
self.endpoint = ""
|
|
49
|
+
self._process: Optional[subprocess.Popen] = None
|
|
50
|
+
self._client: Optional[InferenceClient] = None
|
|
51
|
+
self._server_verified = False
|
|
52
|
+
self._closed = False
|
|
53
|
+
|
|
54
|
+
self._start_server()
|
|
55
|
+
|
|
56
|
+
def _start_server(self):
|
|
57
|
+
max_attempts = 3 if self._user_port is None else 1
|
|
58
|
+
last_err: Optional[Exception] = None
|
|
59
|
+
|
|
60
|
+
for attempt in range(max_attempts):
|
|
61
|
+
self.port = self._user_port or _get_free_port()
|
|
62
|
+
formatted_host = f"[{self.host}]" if ":" in self.host and not self.host.startswith("[") else self.host
|
|
63
|
+
self.endpoint = f"http://{formatted_host}:{self.port}"
|
|
64
|
+
|
|
65
|
+
base_cmd = get_linml_binary()
|
|
66
|
+
cmd = base_cmd + [
|
|
67
|
+
"serve",
|
|
68
|
+
"--model", self.model_path,
|
|
69
|
+
"--host", self.host,
|
|
70
|
+
"--port", str(self.port),
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
if self.provider:
|
|
74
|
+
cmd.extend(["--provider", self.provider])
|
|
75
|
+
if self.require_provider:
|
|
76
|
+
cmd.append("--require-provider")
|
|
77
|
+
for k, v in self.ep_options.items():
|
|
78
|
+
cmd.extend(["--ep-option", f"{k}={v}"])
|
|
79
|
+
|
|
80
|
+
self._process = subprocess.Popen(
|
|
81
|
+
cmd,
|
|
82
|
+
stdout=subprocess.DEVNULL,
|
|
83
|
+
stderr=subprocess.PIPE,
|
|
84
|
+
text=True,
|
|
85
|
+
env=get_dotnet_env(),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
self._client = InferenceClient(endpoint=self.endpoint, timeout=self.request_timeout)
|
|
89
|
+
health_client = InferenceClient(endpoint=self.endpoint, timeout=1.0)
|
|
90
|
+
|
|
91
|
+
# Wait for daemon readiness
|
|
92
|
+
deadline = time.time() + self.startup_timeout
|
|
93
|
+
started = False
|
|
94
|
+
|
|
95
|
+
while time.time() < deadline:
|
|
96
|
+
# Check if process crashed early
|
|
97
|
+
if self._process.poll() is not None:
|
|
98
|
+
stderr_output = ""
|
|
99
|
+
if self._process.stderr:
|
|
100
|
+
try:
|
|
101
|
+
stderr_output = self._process.stderr.read()
|
|
102
|
+
except Exception:
|
|
103
|
+
stderr_output = "(stderr unavailable)"
|
|
104
|
+
last_err = RuntimeError(
|
|
105
|
+
f"LinML serve process exited prematurely with code {self._process.returncode}: {stderr_output}"
|
|
106
|
+
)
|
|
107
|
+
break
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
health = health_client.health()
|
|
111
|
+
if health.status.lower() in ("healthy", "ready"):
|
|
112
|
+
# Verify process identity
|
|
113
|
+
if health.process_id is not None and health.process_id != self._process.pid:
|
|
114
|
+
# Port claimed by unrelated server
|
|
115
|
+
time.sleep(0.05)
|
|
116
|
+
continue
|
|
117
|
+
|
|
118
|
+
# Verify model identity
|
|
119
|
+
model_info = health.model
|
|
120
|
+
if model_info and isinstance(model_info, dict):
|
|
121
|
+
reported_path = model_info.get("path")
|
|
122
|
+
if reported_path:
|
|
123
|
+
try:
|
|
124
|
+
if Path(reported_path).resolve() != Path(self.model_path).resolve():
|
|
125
|
+
time.sleep(0.05)
|
|
126
|
+
continue
|
|
127
|
+
except Exception:
|
|
128
|
+
pass
|
|
129
|
+
|
|
130
|
+
self._server_verified = True
|
|
131
|
+
started = True
|
|
132
|
+
break
|
|
133
|
+
except Exception as e:
|
|
134
|
+
last_err = e
|
|
135
|
+
time.sleep(0.05)
|
|
136
|
+
|
|
137
|
+
if started:
|
|
138
|
+
return
|
|
139
|
+
|
|
140
|
+
# Cleanup this attempt before next attempt
|
|
141
|
+
if self._process:
|
|
142
|
+
try:
|
|
143
|
+
self._process.terminate()
|
|
144
|
+
self._process.wait(timeout=1.0)
|
|
145
|
+
except Exception:
|
|
146
|
+
try:
|
|
147
|
+
self._process.kill()
|
|
148
|
+
except Exception:
|
|
149
|
+
pass
|
|
150
|
+
self._process = None
|
|
151
|
+
|
|
152
|
+
self.close()
|
|
153
|
+
raise TimeoutError(
|
|
154
|
+
f"Timed out waiting for LinML server to start on {self.endpoint}: {last_err}"
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
def predict(
|
|
158
|
+
self,
|
|
159
|
+
inputs: Optional[Union[Dict[str, Any], List[Union[TensorSpec, Dict[str, Any]]]]] = None,
|
|
160
|
+
**kwargs: Any,
|
|
161
|
+
) -> InferenceResult:
|
|
162
|
+
"""Run model inference on the active session."""
|
|
163
|
+
if self._closed or not self._client:
|
|
164
|
+
raise RuntimeError("InferenceSession is closed.")
|
|
165
|
+
return self._client.predict(inputs=inputs, **kwargs)
|
|
166
|
+
|
|
167
|
+
def run(
|
|
168
|
+
self,
|
|
169
|
+
output_names: Optional[List[str]] = None,
|
|
170
|
+
input_feed: Optional[Dict[str, Any]] = None,
|
|
171
|
+
) -> List[Any]:
|
|
172
|
+
"""ONNX Runtime-compatible API: session.run([output_names], input_feed).
|
|
173
|
+
|
|
174
|
+
Returns list of NumPy arrays (or list data if NumPy is not installed) in order of output_names.
|
|
175
|
+
"""
|
|
176
|
+
if input_feed is None:
|
|
177
|
+
raise ValueError("input_feed dictionary must be provided.")
|
|
178
|
+
|
|
179
|
+
result = self.predict(input_feed)
|
|
180
|
+
|
|
181
|
+
if output_names:
|
|
182
|
+
ordered_outputs: List[Any] = []
|
|
183
|
+
for name in output_names:
|
|
184
|
+
if name not in result.outputs:
|
|
185
|
+
raise KeyError(f"Requested output '{name}' not found in model outputs: {list(result.outputs.keys())}")
|
|
186
|
+
tensor_out = result.outputs[name]
|
|
187
|
+
try:
|
|
188
|
+
ordered_outputs.append(tensor_out.to_numpy())
|
|
189
|
+
except RuntimeError:
|
|
190
|
+
ordered_outputs.append(tensor_out.data)
|
|
191
|
+
return ordered_outputs
|
|
192
|
+
|
|
193
|
+
# Default: return all outputs in dict order
|
|
194
|
+
out_list: List[Any] = []
|
|
195
|
+
for tensor_out in result.outputs.values():
|
|
196
|
+
try:
|
|
197
|
+
out_list.append(tensor_out.to_numpy())
|
|
198
|
+
except RuntimeError:
|
|
199
|
+
out_list.append(tensor_out.data)
|
|
200
|
+
return out_list
|
|
201
|
+
|
|
202
|
+
def health(self):
|
|
203
|
+
"""Query server health and selected provider status."""
|
|
204
|
+
if self._closed or not self._client:
|
|
205
|
+
raise RuntimeError("InferenceSession is closed.")
|
|
206
|
+
return self._client.health()
|
|
207
|
+
|
|
208
|
+
def close(self):
|
|
209
|
+
"""Shut down the background server and cleanup resources."""
|
|
210
|
+
if self._closed:
|
|
211
|
+
return
|
|
212
|
+
self._closed = True
|
|
213
|
+
|
|
214
|
+
if self._client:
|
|
215
|
+
if self._server_verified and self._process and self._process.poll() is None:
|
|
216
|
+
try:
|
|
217
|
+
self._client.shutdown()
|
|
218
|
+
except Exception:
|
|
219
|
+
pass
|
|
220
|
+
self._client = None
|
|
221
|
+
|
|
222
|
+
if self._process:
|
|
223
|
+
if self._process.stdout:
|
|
224
|
+
try:
|
|
225
|
+
self._process.stdout.close()
|
|
226
|
+
except Exception:
|
|
227
|
+
pass
|
|
228
|
+
if self._process.stderr:
|
|
229
|
+
try:
|
|
230
|
+
self._process.stderr.close()
|
|
231
|
+
except Exception:
|
|
232
|
+
pass
|
|
233
|
+
try:
|
|
234
|
+
self._process.wait(timeout=2.0)
|
|
235
|
+
except subprocess.TimeoutExpired:
|
|
236
|
+
self._process.terminate()
|
|
237
|
+
try:
|
|
238
|
+
self._process.wait(timeout=1.0)
|
|
239
|
+
except subprocess.TimeoutExpired:
|
|
240
|
+
self._process.kill()
|
|
241
|
+
self._process = None
|
|
242
|
+
|
|
243
|
+
def __enter__(self) -> "InferenceSession":
|
|
244
|
+
return self
|
|
245
|
+
|
|
246
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
247
|
+
self.close()
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: linml
|
|
3
|
+
Version: 0.6.2
|
|
4
|
+
Summary: Linux ONNX Runtime inference integration layer and client library
|
|
5
|
+
Author-email: Mesilim LLC <cloud@trackdub.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: onnx,onnxruntime,inference,machine-learning,cuda,tensorrt,openvino,linux
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
Provides-Extra: numpy
|
|
23
|
+
Requires-Dist: numpy>=1.20; extra == "numpy"
|
|
24
|
+
Provides-Extra: test
|
|
25
|
+
Requires-Dist: pytest>=7.0; extra == "test"
|
|
26
|
+
Requires-Dist: numpy>=1.20; extra == "test"
|
|
27
|
+
|
|
28
|
+
# linml (Python Bindings)
|
|
29
|
+
|
|
30
|
+
[](https://pypi.org/project/linml/)
|
|
31
|
+
[](LICENSE)
|
|
32
|
+
|
|
33
|
+
Python client library and CLI wrapper for **LinML** (Linux ML), the Linux counterpart to Windows ML for [ONNX Runtime](https://onnxruntime.ai).
|
|
34
|
+
|
|
35
|
+
## Features
|
|
36
|
+
|
|
37
|
+
- **Direct In-Memory Inference Sessions**: `linml.InferenceSession("model.onnx")` executes ONNX models with hardware-abstracted execution providers (`cpu`, `cuda`, `tensorrt`, `trt-rtx`, `openvino`, `migraphx`).
|
|
38
|
+
- **HTTP REST Microservice Client**: `linml.InferenceClient("http://localhost:8080")` interacts with high-performance `linml serve` daemons at ~1 ms latency.
|
|
39
|
+
- **NumPy Integration**: Pass numpy arrays directly as dictionary kwargs or lists; outputs convert seamlessly back to NumPy `ndarray`.
|
|
40
|
+
- **Model Graph & EP Diagnostics**: `linml.inspect("model.onnx")` inspects model graph topology, dynamic shapes, and execution provider compatibility warnings.
|
|
41
|
+
- **Hardware Probing & Auto-Setup**: `linml.setup()` and `linml.doctor()` discover and verify host accelerators directly from Python.
|
|
42
|
+
|
|
43
|
+
## Quick Start
|
|
44
|
+
|
|
45
|
+
### 1. Installation
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pip install linml
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### 2. High-Level Inference Session
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import numpy as np
|
|
55
|
+
import linml
|
|
56
|
+
|
|
57
|
+
# Launch an in-process or daemon-managed session
|
|
58
|
+
with linml.InferenceSession("model.onnx", provider="cuda") as session:
|
|
59
|
+
x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
|
|
60
|
+
result = session.predict(x=x)
|
|
61
|
+
|
|
62
|
+
print(f"Provider: {result.selected_provider}")
|
|
63
|
+
print(f"Latency: {result.latency_ms:.2f} ms")
|
|
64
|
+
|
|
65
|
+
# Access output tensor as NumPy array
|
|
66
|
+
y = result.outputs["y"].to_numpy()
|
|
67
|
+
print("Output shape:", y.shape)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### 3. HTTP Microservice Client (`linml serve`)
|
|
71
|
+
|
|
72
|
+
When running `linml serve --port 8080 --model model.onnx`:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import linml
|
|
76
|
+
|
|
77
|
+
client = linml.InferenceClient("http://localhost:8080")
|
|
78
|
+
|
|
79
|
+
# Check service health and provider readiness
|
|
80
|
+
health = client.health()
|
|
81
|
+
print(f"Status: {health.status}, Provider: {health.selected_provider}")
|
|
82
|
+
|
|
83
|
+
# Submit prediction
|
|
84
|
+
result = client.predict({"x": [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]})
|
|
85
|
+
print(result.outputs["y"].data)
|
|
86
|
+
|
|
87
|
+
client.close()
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 4. Model Inspection & Diagnostics
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import linml
|
|
94
|
+
|
|
95
|
+
# Inspect model inputs, outputs, opset, and EP compatibility
|
|
96
|
+
report = linml.inspect("model.onnx")
|
|
97
|
+
|
|
98
|
+
print(f"Format: ONNX IR v{report.ir_version}, Opset: {report.opsets}")
|
|
99
|
+
for inp in report.inputs:
|
|
100
|
+
print(f"Input: {inp.name} ({inp.data_type}, shape={inp.shape})")
|
|
101
|
+
|
|
102
|
+
for warning in report.compatibility_warnings:
|
|
103
|
+
print(f"Warning [{warning.provider}]: {warning.message}")
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT License. See [LICENSE](https://github.com/mesalimllc/LinML/blob/main/LICENSE) for details.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
linml/__init__.py,sha256=xBlHYTgBVNLMgCLQdhPitpXuRl9b_jePbWXhM68KeYk,990
|
|
2
|
+
linml/binary.py,sha256=yU4EJvYqKIcpFZieyn1ZoH4KKw3Jsb2jGCNO2rii6wE,5089
|
|
3
|
+
linml/cli.py,sha256=bPG-QMnfcJvZkkN_rJ-L9j8NMH5D_Yte3ixiMJYqz6Y,5709
|
|
4
|
+
linml/client.py,sha256=4gsK_tarD8pjmjUbs9C1ps--JJabZ63iCkIgLrqoF6M,4567
|
|
5
|
+
linml/models.py,sha256=E6cIDtr5ScyQtwmDiII4NSv4JNlwiQVMzY-Zw4-KcwI,10883
|
|
6
|
+
linml/session.py,sha256=6WzrhXDn7kp0aWXEgBDdBPL0U8U-Ga3wSVn9YwwU9js,8983
|
|
7
|
+
linml-0.6.2.dist-info/METADATA,sha256=aB-hgY83rEmuBaixGK7gFOvYQxBor9k2EDNlH7Bm78Q,3900
|
|
8
|
+
linml-0.6.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
linml-0.6.2.dist-info/entry_points.txt,sha256=LZNcWaD0knpGqWxyWcG1KzD-zGxeIKi3_YP7X0dCPmo,41
|
|
10
|
+
linml-0.6.2.dist-info/top_level.txt,sha256=32FnfPmaBa5a7g0q3S5Y_d6avxy9FjtJRjohV2VLARg,6
|
|
11
|
+
linml-0.6.2.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
linml
|