linml 0.6.2__tar.gz

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-0.6.2/PKG-INFO ADDED
@@ -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
+ [![PyPI](https://img.shields.io/pypi/v/linml.svg)](https://pypi.org/project/linml/)
31
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](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.
linml-0.6.2/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # linml (Python Bindings)
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/linml.svg)](https://pypi.org/project/linml/)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
5
+
6
+ Python client library and CLI wrapper for **LinML** (Linux ML), the Linux counterpart to Windows ML for [ONNX Runtime](https://onnxruntime.ai).
7
+
8
+ ## Features
9
+
10
+ - **Direct In-Memory Inference Sessions**: `linml.InferenceSession("model.onnx")` executes ONNX models with hardware-abstracted execution providers (`cpu`, `cuda`, `tensorrt`, `trt-rtx`, `openvino`, `migraphx`).
11
+ - **HTTP REST Microservice Client**: `linml.InferenceClient("http://localhost:8080")` interacts with high-performance `linml serve` daemons at ~1 ms latency.
12
+ - **NumPy Integration**: Pass numpy arrays directly as dictionary kwargs or lists; outputs convert seamlessly back to NumPy `ndarray`.
13
+ - **Model Graph & EP Diagnostics**: `linml.inspect("model.onnx")` inspects model graph topology, dynamic shapes, and execution provider compatibility warnings.
14
+ - **Hardware Probing & Auto-Setup**: `linml.setup()` and `linml.doctor()` discover and verify host accelerators directly from Python.
15
+
16
+ ## Quick Start
17
+
18
+ ### 1. Installation
19
+
20
+ ```bash
21
+ pip install linml
22
+ ```
23
+
24
+ ### 2. High-Level Inference Session
25
+
26
+ ```python
27
+ import numpy as np
28
+ import linml
29
+
30
+ # Launch an in-process or daemon-managed session
31
+ with linml.InferenceSession("model.onnx", provider="cuda") as session:
32
+ x = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
33
+ result = session.predict(x=x)
34
+
35
+ print(f"Provider: {result.selected_provider}")
36
+ print(f"Latency: {result.latency_ms:.2f} ms")
37
+
38
+ # Access output tensor as NumPy array
39
+ y = result.outputs["y"].to_numpy()
40
+ print("Output shape:", y.shape)
41
+ ```
42
+
43
+ ### 3. HTTP Microservice Client (`linml serve`)
44
+
45
+ When running `linml serve --port 8080 --model model.onnx`:
46
+
47
+ ```python
48
+ import linml
49
+
50
+ client = linml.InferenceClient("http://localhost:8080")
51
+
52
+ # Check service health and provider readiness
53
+ health = client.health()
54
+ print(f"Status: {health.status}, Provider: {health.selected_provider}")
55
+
56
+ # Submit prediction
57
+ result = client.predict({"x": [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]})
58
+ print(result.outputs["y"].data)
59
+
60
+ client.close()
61
+ ```
62
+
63
+ ### 4. Model Inspection & Diagnostics
64
+
65
+ ```python
66
+ import linml
67
+
68
+ # Inspect model inputs, outputs, opset, and EP compatibility
69
+ report = linml.inspect("model.onnx")
70
+
71
+ print(f"Format: ONNX IR v{report.ir_version}, Opset: {report.opsets}")
72
+ for inp in report.inputs:
73
+ print(f"Input: {inp.name} ({inp.data_type}, shape={inp.shape})")
74
+
75
+ for warning in report.compatibility_warnings:
76
+ print(f"Warning [{warning.provider}]: {warning.message}")
77
+ ```
78
+
79
+ ## License
80
+
81
+ MIT License. See [LICENSE](https://github.com/mesalimllc/LinML/blob/main/LICENSE) for details.
@@ -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
+ ]
@@ -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
+ )
@@ -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)
@@ -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()