tempest_fastapi_sdk.modelops¶
Modelops: exportar, quantizar e medir os modelos que o serviço serve.
modelops
¶
Model ops — export, quantize and benchmark the models a service serves.
Three jobs that always travel together, because you cannot honestly do one without the others: you quantize to make a model cheaper, you benchmark to find out whether it actually got cheaper, and you export to the format the target device runs.
from tempest_fastapi_sdk.modelops import (
benchmark_onnx,
export_onnx_to_ort,
quantize_onnx_dynamic,
)
quantized = quantize_onnx_dynamic("m.onnx", "m.int8.onnx")
profile = benchmark_onnx("m.int8.onnx", n_repetitions=50)
mobile = export_onnx_to_ort("m.int8.onnx", "dist/", target_platform="arm")
Two extras, so you install only the weight you need:
[modelops]— psutil + nvidia-ml-py. Enough for :func:benchmarkover any callable, with CPU/RAM/GPU/energy measurement.[modelops-onnx]— adds onnx + onnxruntime: static analysis, ONNX benchmarking,.onnxto.ortconversion, graph optimization, and quantization of both raw graphs and transformers exports.
This module itself imports with neither. Every heavy dependency is resolved
inside the function that needs it, and its absence raises an ImportError
naming the extra to install.
There is no HuggingFace ONNX export here, on purpose. The only maintained
per-architecture export registry lives in optimum, which caps
transformers to an upper bound that would propagate to every consumer of
this SDK. Run it as a build step in a throwaway environment instead::
uvx --from "optimum[onnxruntime]" optimum-cli export onnx \
--model distilbert-base-uncased --task text-classification \
exports/distilbert
then point :func:optimize_hf_onnx and :func:quantize_hf_onnx at that
directory. Both run on onnxruntime's own transformers tooling, so nothing
here constrains your transformers version.
DEFAULT_REPETITIONS
module-attribute
¶
Timed calls. Enough for a stable median without making a CI job crawl.
DEFAULT_WARMUP
module-attribute
¶
Warm-up calls discarded before timing starts.
COMPACT_SCHEMA_VERSION
module-attribute
¶
Version of the compact layout.
Read by tempest-react-sdk/tabular in another language, so a change here
breaks a consumer that this repository does not build. Bump only for a
breaking layout change.
BASELINE_FILENAME
module-attribute
¶
Fixed name, referenced from the manifest.
MANIFEST_FILENAME
module-attribute
¶
Fixed name, so a consumer needs only the directory URL.
MANIFEST_SCHEMA_VERSION
module-attribute
¶
Version of the manifest contract.
Read by tempest-react-sdk/tabular as well as by this SDK, so a change
here breaks a consumer in another language. Bump it only for a breaking
shape change, and keep readers tolerant of unknown fields.
DEFAULT_SAMPLE_INTERVAL_S
module-attribute
¶
Default polling interval: fast enough for ~10 ms kernels, cheap enough that the sampler thread does not distort the measurement.
RAPL_ROOT
module-attribute
¶
Linux powercap sysfs root holding the RAPL energy counters.
ORT_CONFIG_SUFFIXES
module-attribute
¶
ORT_CONFIG_SUFFIXES: tuple[str, ...] = (
".required_operators.config",
".required_operators.with_runtime_opt.config",
)
Side files the ORT conversion writes for minimal-build kernel selection.
DEFAULT_BINS
module-attribute
¶
Quantile bins per feature in a baseline.
Ten is the convention PSI is normally computed with: enough resolution to see a shifted mode, few enough that each bin holds a usable count on the sample sizes a device accumulates in an hour.
DEFAULT_WINDOW_ROWS
module-attribute
¶
Rows per drift window before the counters reset.
Drift is a property of a population, so it is measured over a window rather than per request. When a window fills, its report is kept as the last complete measurement and the counters start again — so the numbers describe recent traffic instead of everything since boot, which would take days to respond to a real shift.
MAX_TRACKED_LABELS
module-attribute
¶
Distinct predicted labels counted individually per monitor.
The class-share section exists for classifiers, whose label set is small and
fixed; 64 is far past any class count the serving path here targets. A
regressor produces a new label per row, and without a cap each one became a
dictionary key — 50 000 distinct outputs made a 50 000-key map and a
report of 889 270 bytes of JSON (measured; 65 keys and 1 350 bytes
with the cap). Past the cap, new labels count into
:data:OTHER_LABEL. Classes named in the baseline always keep their own
bucket, whatever order traffic arrives in, so the output PSI never loses a
known class to the overflow.
MIN_ROWS_FOR_DRIFT
module-attribute
¶
Rows below which a drift number is noise rather than signal.
PSI compares proportions. With 30 rows across 10 bins, an empty bin is the
expected outcome of sampling, not evidence of drift, and the smoothing
constant then dominates the score. Reports below this threshold carry
sufficient_sample=False — they are not suppressed, because "we do not
have enough traffic yet" is itself worth seeing on a dashboard.
OTHER_LABEL
module-attribute
¶
Share key that absorbs labels beyond :data:MAX_TRACKED_LABELS.
PSI_MODERATE
module-attribute
¶
PSI above which a feature is considered to have moved.
From credit-scorecard practice (Siddiqi, Credit Risk Scorecards), where PSI has been the standard population-shift measure for decades: below 0.1 the population is treated as stable, 0.1-0.25 as a shift worth investigating, above 0.25 as a shift that invalidates the model's calibration.
These are conventions, not a statistical test. PSI has no p-value and no null distribution; it does not tell you a shift is significant, only that it is large by a rule of thumb the industry agreed on. Treat a crossing as a reason to look, not a reason to act automatically.
PSI_SIGNIFICANT
module-attribute
¶
PSI above which a feature has moved enough to distrust the model.
See :data:PSI_MODERATE for the provenance and the caveat.
DEFAULT_COST_WEIGHTS
module-attribute
¶
DEFAULT_COST_WEIGHTS: dict[str, float] = {
"latency_ms_median": 0.4,
"energy_per_inference_j": 0.25,
"rss_peak_mb": 0.2,
"disk_size_mb": 0.15,
}
Default composite-score weights, tuned for an edge/mobile deployment.
Latency dominates because it is what a user feels; energy and memory follow because they are what a battery and a small device run out of; artifact size matters because it gates the app download. A server deployment with a throughput SLO should re-weight — that is the point of the parameter.
DEFAULT_MAX_PREDICT_ROWS
module-attribute
¶
Rows one POST /predict may carry before it is refused with 422.
Without a limit, one request decides how much memory and how many seconds of
inference the device spends on it: every row is parsed, coerced and scored
before that request is answered. Ten thousand rows is well past the batch
sizes the serving guidance here measures, and still bounds the worst
request. Raise it per router with max_rows=; None removes the limit
for a device that trusts its callers.
DEFAULT_INTRA_OP_THREADS
module-attribute
¶
Intra-op threads. One, because one request should not take the machine.
ONNX Runtime's own default is one thread per core. In a service that is usually the wrong default for a different reason than it first appears: with per-request threads, N concurrent requests oversubscribe the CPU and every one of them gets slower. One thread per request keeps the arithmetic predictable, and the parallelism you want lives in the concurrent requests themselves.
Raise it when a single call has real work to do. Measured on a 12-core machine, a 300-tree forest over 20 features:
=================== ============== ================== Threads One row (ms) 1000 rows (ms) =================== ============== ================== 1 0.019 16.6 2 0.013 8.2 4 0.012 4.2 8 0.010 2.3 =================== ============== ==================
A batch scales almost linearly with threads. A small graph does not: the same measurement on a logistic regression showed 0.213 ms for 1000 rows at one thread and 0.214 ms at eight — the work is too small to split.
So the rule is the shape of the workload, not the size of the device:
batched or large-ensemble inference wants threads, one-row-at-a-time on a
small graph does not care, and a service serving many callers at once
wants this default. Measure with
:func:~tempest_fastapi_sdk.modelops.benchmark_onnx on the target device
— not on your laptop, whose core count and memory bandwidth are not the
device's.
BINARY_TREE_FIXED_IN_ONNXRUNTIME
module-attribute
¶
First onnxruntime release that evaluates a binary tree ensemble right.
Measured against the released wheels with every other package held fixed
(skl2onnx 1.20.0, scikit-learn 1.9.0, onnx 1.22.0): on
onnxruntime 1.27.0 the probability output of a binary
RandomForestClassifier comes back as [-1, 1] / [-0, 0] — a
decision score — for a maximum absolute error of 1.0 against
predict_proba; on 1.28.0 the same graph yields the correct
probabilities, error 9.5e-08.
That comparison also relocates the defect. It was previously recorded
here as a skl2onnx conversion bug; since the converter, scikit-learn
and onnx were byte-identical across the two runs, the graph was
always right and the fault was in onnxruntime's ai.onnx.ml
TreeEnsemble evaluation. The SDK's declared floor is
onnxruntime>=1.29.0, above this one, so a normal install cannot hit
it; the runtime is still checked at call time, because a floor only binds
the resolver and an environment assembled around it would otherwise fail
silently.
DEFAULT_OPSET
module-attribute
¶
Target ONNX opset.
Chosen low enough that older embedded ONNX Runtime builds can load the graph, and high enough for the operators scikit-learn converters emit. Raise it only when a converter needs something newer — a device running last year's runtime cannot load a graph built for this year's opset, and that failure appears at deployment, not at export.
REMOTE_PROVIDERS
module-attribute
¶
Execution providers that call out to a remote endpoint.
ONNX Runtime registers AzureExecutionProvider by default and returns it
first from get_available_providers(). Leaving it in the default priority
list would make a local benchmark report a remote provider, so it is
filtered out unless the caller asks for it explicitly.
TabularInput
¶
TabularInput = ArrayLike | HasValues
2-D feature matrix or 1-D label sequence (array, nested sequence, DataFrame).
TorchExampleInput
¶
Single tensor or tuple of tensors forwarded to a torch.nn.Module.
CompactExport
¶
Bases: BaseSchema
What :func:export_sklearn_to_compact produced.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The written file. |
size_bytes |
int
|
Its size. |
kind |
CompactKindEnum
|
Which reader it needs. |
task |
CompactTaskEnum
|
Classification or regression. |
n_features |
int
|
Values expected per row. |
n_trees |
int
|
Trees in the ensemble; |
classes |
list[str]
|
Class labels in score-column order. |
estimator |
str
|
Class name of the exported estimator. |
verified |
bool | None
|
Whether the written file reproduces the
estimator. |
max_abs_diff |
float | None
|
Largest probability difference found during that check. |
CompactKindEnum
¶
Bases: BaseStrEnum
Which reader a compact file needs.
Attributes:
| Name | Type | Description |
|---|---|---|
LINEAR |
Coefficients and intercepts; the reader does a dot product. |
|
TREE_ENSEMBLE |
One or more trees averaged; the reader walks them. |
CompactTaskEnum
¶
Bases: BaseStrEnum
What the model answers.
Attributes:
| Name | Type | Description |
|---|---|---|
CLASSIFICATION |
Class label plus per-class scores. |
|
REGRESSION |
A single value per row. |
UnsupportedEstimatorError
¶
Bases: TypeError
The estimator has no compact representation.
Raised instead of writing something approximate: a format that silently dropped a step would produce a model that runs and answers wrongly, which is worse than an error naming the ONNX route.
ArtifactSource
¶
Bases: BaseSchema
Where the packaged model came from, when it came from somewhere.
Present when the package was built from an existing artifact — today a
.pkl handed over by a training pipeline. It is what lets someone
holding a model that is running on a device answer "which file made
this", months later.
Attributes:
| Name | Type | Description |
|---|---|---|
file |
str
|
Name of the source artifact. |
kind |
str
|
What it was, e.g. |
sha256 |
str
|
Digest of that file. |
bytes |
int
|
Its size. |
sklearn_version |
str
|
The scikit-learn version that read it and performed the conversion. A pickle records no version of its own (measured on scikit-learn 1.9), so this is the only version fact the chain can offer. |
warnings |
list[str]
|
Warnings raised while reading the source. |
EdgeManifest
¶
Bases: BaseSchema
Everything a runtime needs to serve the package correctly.
Written as manifest.json and read by both this SDK's
:func:load_edge_package and tempest-react-sdk/tabular in the
browser.
Attributes:
| Name | Type | Description |
|---|---|---|
schema_version |
int
|
Contract version. |
name |
str
|
Logical model name. |
version |
str
|
This build. Defaults to the model's content hash, so identical bytes never look like a new version. |
created_at |
str
|
ISO-8601 UTC timestamp. |
sdk_version |
str
|
SDK that produced the package. |
estimator |
str
|
Class name of the exported estimator. |
model |
ModelFile
|
The graph and its digest. |
input |
ModelInput
|
What it expects. |
output |
ModelOutput
|
What it answers. |
verified |
bool | None
|
Whether the export was checked against the
estimator's own predictions. |
verification |
ExportVerification | None
|
The numbers behind it. |
runtimes |
list[RuntimeArtifact]
|
Every file a runtime can load, so a consumer picks the one it can run rather than the one the publisher happened to write. |
source |
ArtifactSource | None
|
Where the packaged model came from, when it was built from an existing artifact. |
baseline_file |
str | None
|
Drift baseline filename. |
baseline_samples |
int
|
Rows the baseline summarises. |
EdgePackage
¶
Bases: BaseSchema
What :func:edge_pipeline wrote.
Attributes:
| Name | Type | Description |
|---|---|---|
directory |
str
|
The package directory — this is what you ship, whole. |
manifest |
EdgeManifest
|
Its manifest, already parsed. |
model_path |
str
|
The graph. |
gzip_path |
str | None
|
The pre-compressed copy. |
baseline_path |
str | None
|
The drift baseline. |
manifest_path |
str
|
The manifest file. |
LoadedEdgePackage
¶
Bases: BaseSchema
A package loaded and wired up, ready to answer.
Attributes:
| Name | Type | Description |
|---|---|---|
manifest |
EdgeManifest
|
What was loaded. |
predictor |
OnnxPredictor
|
The running model. |
monitor |
PredictionMonitor | None
|
Wired to the package's baseline, when it has one. |
baseline |
FeatureBaseline | None
|
The baseline itself. |
ModelFile
¶
Bases: BaseSchema
The graph and how to verify you got the right bytes.
Attributes:
| Name | Type | Description |
|---|---|---|
file |
str
|
Filename inside the package directory. |
sha256 |
str
|
Digest of the file, so a device can detect a truncated download instead of loading half a model. |
bytes |
int
|
Size on disk. |
gzip_file |
str | None
|
Pre-compressed copy, when one was written. |
gzip_bytes |
int | None
|
Its size — what actually crosses the
network when the server sends it with
|
opset |
int
|
ONNX opset the graph targets. |
dtype |
str
|
Input element type. |
ModelInput
¶
Bases: BaseSchema
What the graph expects per row.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Graph input name. |
features |
int
|
Values per row. |
feature_names |
list[str]
|
Column order used at training time. The most valuable field in the manifest: a model fed the right columns in the wrong order answers confidently and wrongly, and nothing else in the package catches it. |
ModelOutput
¶
Bases: BaseSchema
What the graph answers.
Attributes:
| Name | Type | Description |
|---|---|---|
is_classifier |
bool
|
Whether class scores are produced. |
label_output |
str
|
Output holding classes or values. |
probability_output |
str | None
|
Output holding class scores. |
classes |
list[str]
|
Class labels in score-column order, so a
consumer can map |
RuntimeArtifact
¶
Bases: BaseSchema
One file in the package a runtime can load.
A package may carry the same model twice: as ONNX, which any runtime reads but costs a 25.6 MB WebAssembly download in a browser, and as the compact format, which needs no runtime but covers only linear models and tree ensembles. Listing both lets the consumer pick by what it already ships instead of the publisher deciding for it.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
|
file |
str
|
Filename inside the package directory. |
bytes |
int
|
Size on disk. |
gzip_file |
str | None
|
Pre-compressed copy, when one was written. |
gzip_bytes |
int | None
|
Its size. |
sha256 |
str
|
Digest of the file. |
NullPowerSampler
¶
Sampler for hosts with nothing to measure.
Every method is a no-op and :meth:reading reports
:attr:~tempest_fastapi_sdk.modelops.EnergySourceEnum.UNAVAILABLE with all
energy fields set to None.
reading
¶
reading() -> EnergyReading
Return an empty reading.
Returns:
| Name | Type | Description |
|---|---|---|
EnergyReading |
EnergyReading
|
Source |
latest_power_w
¶
Return None.
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Always |
peak_memory_mb
¶
Return None.
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Always |
NvidiaSmiPowerSampler
¶
Bases: _ThreadedPowerSampler
GPU energy by polling the nvidia-smi binary.
The fallback for hosts that have the NVIDIA driver but not pynvml.
Each poll spawns a process, so the interval defaults to a slower 50 ms —
below that the sampler starts competing with the model for CPU.
Initialize the sampler and look for nvidia-smi on PATH.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device_index
|
int
|
Zero-based GPU index to query. |
0
|
interval_s
|
float
|
Polling interval in seconds. |
0.05
|
available
property
¶
Whether nvidia-smi is on PATH.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
NvmlPowerSampler
¶
NvmlPowerSampler(
*, device_index: int = 0, interval_s: float = DEFAULT_SAMPLE_INTERVAL_S
)
Bases: _ThreadedPowerSampler
GPU energy through NVML (pynvml).
Two measurement paths, picked automatically:
- Total-energy counter —
nvmlDeviceGetTotalEnergyConsumptionreturns millijoules accumulated since the driver loaded. Taking the delta across the window gives energy the driver itself integrated, so short kernels that a sampler would miss are still counted. Volta and newer. - Sampled power — on older cards the counter is unsupported, so the
background thread integrates
nvmlDeviceGetPowerUsageinstead.
The polling thread runs either way: it is what supplies per-repetition instantaneous power and GPU-memory peaks.
Example:
>>> sampler = NvmlPowerSampler(device_index=0)
>>> sampler.start()
>>> run_inference()
>>> sampler.stop()
>>> sampler.reading().energy_j
Initialize the sampler and probe NVML.
Probing happens once, here, so :attr:available is a cheap property
the benchmark can consult before committing to a code path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device_index
|
int
|
Zero-based GPU index to measure. |
0
|
interval_s
|
float
|
Polling interval in seconds. |
DEFAULT_SAMPLE_INTERVAL_S
|
available
property
¶
Whether NVML resolved a handle for the requested device.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
reading
¶
reading() -> EnergyReading
Prefer the driver's energy counter, fall back to integration.
Returns:
| Name | Type | Description |
|---|---|---|
EnergyReading |
EnergyReading
|
Source |
EnergyReading
|
usable, |
|
EnergyReading
|
|
PowerSampler
¶
Bases: Protocol
Something that can measure energy over a window.
The benchmark calls :meth:start before the timed repetitions,
:meth:stop after them, and :meth:reading once to collect the result.
:meth:latest_power_w is polled per repetition to annotate raw samples.
RaplEnergySampler
¶
RaplEnergySampler(*, root: str = RAPL_ROOT)
CPU package energy from the Linux powercap (RAPL) counters.
Reads energy_uj for every intel-rapl:<n> package domain (the AMD
driver exposes the same interface), sums the deltas across the window and
handles counter wraparound with max_energy_range_uj.
Two things commonly make this unavailable, both silently:
- Permissions. Since CVE-2020-8694 most distributions ship
energy_ujas0400 root, because a high-resolution energy trace leaks information about what the CPU is doing. Reading it as a normal user then fails. - Virtualization. WSL2, most containers and most cloud VMs do not expose powercap at all.
Example:
>>> sampler = RaplEnergySampler()
>>> sampler.start()
>>> run_inference()
>>> sampler.stop()
>>> sampler.reading().source
Discover readable package domains under root.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
str
|
Powercap sysfs root. Overridable for testing. |
RAPL_ROOT
|
available
property
¶
Whether at least one readable package domain was found.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
reading
¶
reading() -> EnergyReading
Return the accumulated CPU package energy.
Returns:
| Name | Type | Description |
|---|---|---|
EnergyReading |
EnergyReading
|
Source |
EnergyReading
|
|
latest_power_w
¶
Return None: RAPL exposes energy, not instantaneous power.
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Always |
peak_memory_mb
¶
Return None: RAPL says nothing about memory.
Returns:
| Type | Description |
|---|---|
float | None
|
float | None: Always |
DriftReport
¶
Bases: BaseSchema
Input drift over the current window.
Attributes:
| Name | Type | Description |
|---|---|---|
features |
list[FeatureDrift]
|
Per-feature drift, worst first. |
worst_psi |
float
|
The highest PSI across features. |
verdict |
DriftVerdictEnum
|
The worst feature's verdict, or
|
n_rows |
int
|
Rows in this window. |
sufficient_sample |
bool
|
Whether the window holds at least
:data: |
DriftVerdictEnum
¶
Bases: BaseStrEnum
How much the live population has moved from the baseline.
Attributes:
| Name | Type | Description |
|---|---|---|
STABLE |
No feature crossed :data: |
|
MODERATE |
At least one feature moved; worth investigating. |
|
SIGNIFICANT |
At least one feature crossed :data: |
|
INSUFFICIENT_DATA |
Fewer than :data: |
FeatureBaseline
¶
Bases: BaseSchema
What the training data looked like, small enough to ship with a model.
Built by :func:baseline_from_samples at training time and saved next to
the model file. It holds bin edges and proportions — never the training
rows themselves — so it is a few kilobytes and carries no records.
Example:
>>> baseline = baseline_from_samples(X_train, labels=y_train)
>>> Path("dist/baseline.json").write_text(baseline.model_dump_json())
Attributes:
| Name | Type | Description |
|---|---|---|
features |
list[FeatureBins]
|
Per-feature baseline distribution. |
n_samples |
int
|
Rows the baseline was built from. |
label_proportions |
dict[str, float]
|
Share per predicted class in the baseline, when labels were supplied. Empty for a regressor or when they were not. |
FeatureBins
¶
Bases: BaseSchema
The baseline distribution of one feature.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Feature name, or its positional index as a string. |
edges |
list[float]
|
Interior bin boundaries, ascending. A value
falls in bin |
proportions |
list[float]
|
Share of baseline rows per bin. |
constant |
bool
|
Whether the training data held a single value. Such a feature gets a narrow middle bin, so any live value that differs registers instead of vanishing into one catch-all bin. |
FeatureDrift
¶
Bases: BaseSchema
How far one feature has moved.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Feature name. |
psi |
float
|
Population Stability Index against the baseline. |
verdict |
DriftVerdictEnum
|
The PSI read against the conventional thresholds. |
proportions |
list[float]
|
Observed share per bin, so a dashboard can show where it moved rather than only how much. |
LatencyReport
¶
Bases: BaseSchema
How fast and how much the device has been answering.
Attributes:
| Name | Type | Description |
|---|---|---|
n_calls |
int
|
Prediction calls observed. |
n_rows |
int
|
Rows across those calls — a batch of 64 is one call and 64 rows, and throughput questions need the second number. |
seconds_total |
float
|
Total inference time. |
median_ms |
float
|
Median call latency, over the recent window. |
p95_ms |
float
|
95th percentile call latency, over the recent window. |
max_ms |
float
|
Slowest call in the recent window. |
MonitoringReport
¶
Bases: BaseSchema
Everything the monitor knows, in one object.
Attributes:
| Name | Type | Description |
|---|---|---|
latency |
LatencyReport
|
Speed and volume. |
drift |
DriftReport
|
Input drift over the current window. |
predictions |
PredictionDistribution
|
What the model is answering. |
model_version |
str | None
|
Which version produced these numbers, when the predictor is registry-backed. Without it, a drift report cannot be attributed to a model. |
PredictionDistribution
¶
Bases: BaseSchema
What the model has been answering.
For a classifier this is the share per class, compared against the baseline share when one was supplied. For a regressor the class fields stay empty and the summary statistics carry the signal.
Attributes:
| Name | Type | Description |
|---|---|---|
shares |
dict[str, float]
|
Observed share per predicted class. |
baseline_shares |
dict[str, float]
|
Share per class in the baseline, when known. |
psi |
float
|
PSI of the predicted-class distribution against the baseline. Zero when there is no baseline to compare against. |
verdict |
DriftVerdictEnum
|
That PSI read against the thresholds. |
n_rows |
int
|
Predictions in this window. |
mean |
float | None
|
Mean predicted value, for a regressor. |
minimum |
float | None
|
Smallest predicted value seen. |
maximum |
float | None
|
Largest predicted value seen. |
PredictionMetrics
¶
Publishes a monitor's numbers as Prometheus metrics.
Example:
>>> metrics = PredictionMetrics()
>>> metrics.observe(prediction) # per call
>>> metrics.observe_report(monitor.report()) # periodically
Split in two on purpose: counters and the latency histogram are cheap enough to update per request, while drift gauges describe a window and only change when one closes.
Attributes:
| Name | Type | Description |
|---|---|---|
namespace |
str
|
Metric name prefix. |
Build the metric objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
Prefix for every metric name. |
'edge_model'
|
registry
|
Any
|
A |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
observe
¶
observe(prediction: Prediction) -> None
Record one prediction call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prediction
|
Prediction
|
What the predictor returned. |
required |
observe_report
¶
observe_report(report: MonitoringReport) -> None
Publish a monitoring report as gauge values.
Drift gauges are left untouched while the sample is insufficient: publishing a noisy PSI from 12 rows would put a spike on the dashboard that means nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
report
|
MonitoringReport
|
From
:meth: |
required |
PredictionMonitor
¶
PredictionMonitor(
*,
baseline: FeatureBaseline | None = None,
window_rows: int = DEFAULT_WINDOW_ROWS,
model_version: str | None = None,
max_labels: int = MAX_TRACKED_LABELS,
)
Tracks latency, input drift and output distribution for one predictor.
Example:
>>> monitor = PredictionMonitor(baseline=baseline)
>>> result = predictor.predict(rows)
>>> monitor.observe(rows, result)
>>> monitor.report().drift.verdict
'stable'
Rows are counted into the baseline's bins and discarded, so memory is
n_features x n_bins counters, at most max_labels label buckets
plus the baseline's classes and :data:OTHER_LABEL, and a fixed latency
ring — regardless of traffic. No copy of the requests is retained, which
also means no feature values are held in memory to leak into a log or a
crash dump.
Drift is measured per window (:data:DEFAULT_WINDOW_ROWS). When a
window fills, its report becomes the last complete measurement and the
counters reset, so the numbers track recent traffic rather than
everything since boot.
Without a baseline it still records latency and the prediction
distribution: those need no training-time artifact, and a device with
no baseline should not be left with no monitoring at all.
Thread-safe; :meth:observe is called from request handlers.
Attributes:
| Name | Type | Description |
|---|---|---|
baseline |
FeatureBaseline | None
|
The training-time reference. |
window_rows |
int
|
Rows per drift window. |
model_version |
str | None
|
Stamped onto every report. |
max_labels |
int
|
Distinct labels counted individually beyond the baseline's classes. |
Configure the monitor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
baseline
|
FeatureBaseline | None
|
From
:func: |
None
|
window_rows
|
int
|
Rows before the drift counters reset. |
DEFAULT_WINDOW_ROWS
|
model_version
|
str | None
|
Version stamped onto reports. |
None
|
max_labels
|
int
|
Distinct labels counted individually beyond
the baseline's own classes; the rest count into
:data: |
MAX_TRACKED_LABELS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ImportError
|
When a baseline with features is given and numpy
(the |
observe
¶
observe(features: TabularInput, prediction: Prediction) -> None
Record one prediction call.
Cheap enough for the request path: binning is a searchsorted
over the baseline edges, and nothing is allocated per row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
TabularInput
|
The rows that were predicted — the same
value passed to :meth: |
required |
prediction
|
Prediction
|
What came back. |
required |
report
¶
report() -> MonitoringReport
Return everything measured so far.
The drift section describes the current window when it holds enough rows, and otherwise the last completed one — so a freshly reset window does not blank the dashboard.
Returns:
| Name | Type | Description |
|---|---|---|
MonitoringReport |
MonitoringReport
|
Latency, drift and prediction distribution. |
reset
¶
Drop every accumulated number.
Call this after :meth:~OnnxPredictor.reload swaps the model: the
counters describe the previous version, and mixing two versions'
latencies into one percentile hides exactly the regression a fleet
update needs to catch.
ArtifactDigestMismatchError
¶
Bases: ValueError
The pickle on disk is not the one the caller pinned.
Raised by :func:load_sklearn_artifact before the file is
unpickled, so a substituted artifact never executes. Subclasses
ValueError to match the digest check of load_edge_package.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The file that was checked. |
expected |
str
|
The normalised digest the caller pinned. |
actual |
str
|
The digest of the file on disk. |
Build the error with both digests in the message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The file that was checked. |
required |
expected
|
str
|
The normalised digest the caller pinned. |
required |
actual
|
str
|
The digest of the file on disk. |
required |
LoadedArtifact
¶
Bases: BaseSchema
A fitted estimator read from a pickle, plus where it came from.
Attributes:
| Name | Type | Description |
|---|---|---|
estimator |
Any
|
The unpickled object, ready to convert. |
source_path |
str
|
The file it was read from. |
sha256 |
str
|
Digest of that file, so the produced package can be traced back to the exact artifact. |
bytes |
int
|
Its size on disk. |
sklearn_version |
str
|
The scikit-learn version that read it — which is the one that will convert it. The version that wrote it is not recorded in the pickle (see the module docstring). |
estimator_type |
str
|
Class name of the loaded estimator. |
feature_names |
list[str]
|
Column order recovered from
|
load_warnings |
list[str]
|
Warnings raised while unpickling. Empty is the normal case; anything here is worth reading before shipping the conversion. |
HasValues
¶
Bases: Protocol
DataFrame- or Series-like container exposing its raw array via values.
SklearnEstimator
¶
Bases: Protocol
Minimal fitted-estimator contract accepted by scikit-learn export helpers.
Satisfied by every fitted scikit-learn estimator and Pipeline, as well
as compatible third-party estimators exposing predict.
predict
¶
predict(x: TabularInput) -> Iterable[object]
Predict labels or target values for a batch of rows.
SupportsAvailableProviders
¶
Bases: Protocol
Minimal onnxruntime module surface read by :func:default_providers.
get_available_providers
¶
Return the execution providers registered by the runtime.
PredictRequestSchema
¶
Bases: BaseSchema
Request body for POST /predict.
Attributes:
| Name | Type | Description |
|---|---|---|
rows |
list[list[float]]
|
One list of features per row. Always a list of lists, even for a single prediction — accepting both shapes would make a client's off-by-one silently produce a different answer instead of an error. |
PredictResponseSchema
¶
Bases: BaseSchema
Response body for POST /predict.
Attributes:
| Name | Type | Description |
|---|---|---|
labels |
list[Any]
|
Predicted class or value per row. |
probabilities |
list[list[float]]
|
Class scores, when available. |
n_rows |
int
|
Rows predicted. |
seconds |
float
|
Inference duration on the device. |
model_version |
str | None
|
Which version answered, when the predictor is registry-backed. Without it a client cannot tell whether a changed answer came from a changed model. |
RegistryModelSource
¶
RegistryModelSource(
registry: ArtifactRegistry[Any],
name: str,
cache_dir: str | Path,
*,
checksum_field: str | None = "sha256",
)
Resolves the current model version from an artifact registry.
Example:
>>> source = RegistryModelSource(registry, "fraud-classifier", "models/")
>>> await source.sync(predictor) # from a periodic task
The device holds one file per version under cache_dir, so a
rollback is a reload rather than a re-download. Nothing is deleted
automatically: on a device with a small disk you want to decide when
old versions go, not discover they went.
A download lands in a .part file and is renamed into place only
once it is complete (and, when the row carries a digest, verified), so
a connection dropped mid-file is retried on the next sync instead of
being mistaken for a cached version. :meth:sync holds a lock across
fetch and reload, so a periodic task and POST /model/sync racing
each other download and reload a version once.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The logical artifact key in the registry. |
cache_dir |
Path
|
Where downloaded versions live. |
checksum_field |
str | None
|
Row attribute holding the expected hex SHA-256 of the file. |
current_version |
str | None
|
The version currently loaded. |
Configure the source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
ArtifactRegistry[Any]
|
The registry to ask. |
required |
name
|
str
|
The logical artifact key. |
required |
cache_dir
|
str | Path
|
Where to keep downloaded versions. |
required |
checksum_field
|
str | None
|
Row attribute holding the expected
hex SHA-256 of the file. The SDK's
:class: |
'sha256'
|
fetch
async
¶
Download the current version if it is not already cached.
Returns:
| Type | Description |
|---|---|
tuple[str, Path] | None
|
tuple[str, Path] | None: The version and its local path, or |
tuple[str, Path] | None
|
|
tuple[str, Path] | None
|
a normal state before the first activation, not an error. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
When the registry row names an object the storage client cannot produce, or when the downloaded file does not match the SHA-256 the row advertises. A mismatched file is deleted, never cached. |
sync
async
¶
sync(predictor: OnnxPredictor) -> str | None
Reload predictor when the registry has a different version.
Safe to call on a schedule, and concurrently: calls are serialised, and a no-op when the current version is already loaded. The reload itself (session build plus warm-up) runs in a worker thread, so the event loop keeps answering requests while a large model loads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictor
|
OnnxPredictor
|
The predictor to update. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The version now loaded, or |
str | None
|
registry had nothing to offer. |
BenchmarkProfile
¶
Bases: BaseSchema
Everything measured for one model: static, runtime and ranking.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Display name of the model. |
runtime |
RuntimeAggregate
|
Aggregate over the timed repetitions. |
static |
StaticModelMetrics | None
|
Static metrics, when collected. |
samples |
list[RuntimeSample]
|
Raw per-repetition samples. Empty unless the benchmark was asked to keep them. |
quality |
float | None
|
Task quality (accuracy, F1, mAP…) supplied by the caller. Never measured here — the SDK has no idea what "good" means for your task. |
composite_score |
float | None
|
Weighted cost score, lower is
better. Filled by :func: |
is_pareto |
bool
|
Whether the model is non-dominated on cost vs quality. |
BenchmarkReport
¶
Bases: BaseSchema
Comparison of several models measured under the same conditions.
Attributes:
| Name | Type | Description |
|---|---|---|
profiles |
list[BenchmarkProfile]
|
One entry per model, sorted by
|
pareto |
list[ParetoPoint]
|
Pareto annotation, one entry per model. |
weights |
dict[str, float]
|
Weights the composite score used, after renormalization over the dimensions that had data. |
hardware |
HardwareInfo | None
|
Host the measurements ran on. Quote it with the numbers — latency on a workstation says nothing about latency on a phone. |
CalibrationMethodEnum
¶
Bases: BaseStrEnum
Algorithm used to pick activation ranges during static quantization.
MINMAX is the safe default. ENTROPY / PERCENTILE trade a
little accuracy on outliers for a tighter range, which usually recovers
accuracy on models that MINMAX degrades.
EnergyReading
¶
Bases: BaseSchema
Energy drawn over one measured window.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
EnergySourceEnum
|
How the figure was obtained. Always check it
before quoting a number — a |
duration_s |
float
|
Length of the measured window in seconds. |
energy_j |
float | None
|
Energy over the window in Joules. |
mean_power_w |
float | None
|
Mean power draw in Watts. |
peak_power_w |
float | None
|
Highest sampled power draw in Watts. |
samples |
int
|
Number of power samples collected. |
device_index |
int | None
|
GPU index, for the NVML/SMI sources. |
EnergySourceEnum
¶
Bases: BaseStrEnum
Where an energy figure came from — it changes how it must be read.
NVML_COUNTER— NVML's monotonic total-energy counter (nvmlDeviceGetTotalEnergyConsumption). The most accurate option: the driver integrates for us. Volta and newer.NVML_SAMPLING— periodic NVML power reads integrated over the measured window. Accurate to the sampling interval.NVIDIA_SMI— same integration, but polling thenvidia-smibinary. Used whenpynvmlis missing.RAPL— Intel/AMD running-average-power-limit counters under/sys/class/powercap. CPU package energy, Linux bare metal only.UNAVAILABLE— nothing to measure with; every energy field isNone.
ExportResult
¶
Bases: BaseSchema
Outcome of one export or graph-optimization step.
Attributes:
| Name | Type | Description |
|---|---|---|
source_path |
str
|
Input artifact. |
output_path |
str
|
Artifact that was written. |
format |
ModelFormatEnum
|
Format of the output. |
source_size_mb |
float
|
Input size in MB. |
output_size_mb |
float
|
Output size in MB. |
size_ratio |
float
|
|
opset |
int | None
|
ONNX opset of the output, when known. |
optimization_style |
OrtOptimizationStyleEnum | None
|
Style used for an
|
extra_files |
list[str]
|
Side artifacts written next to the output,
such as the |
GraphOptimizationLevelEnum
¶
Bases: BaseStrEnum
ONNX Runtime graph-optimization level.
Mirrors onnxruntime.GraphOptimizationLevel. ALL is the usual
choice when writing an optimized .onnx back to disk; the lower levels
exist to isolate a regression introduced by a fusion.
HFOptimizationLevelEnum
¶
Bases: BaseStrEnum
Graph-optimization preset for a transformers ONNX export.
O1— basic general optimizations.O2—O1plus transformers-specific fusions (attention, layer norm). The usual pick, and the last one that is precision-preserving.O3—O2plus GELU approximation (small numeric drift).O4—O3plus float16 conversion. GPU only.
HFQuantizationTargetEnum
¶
Bases: BaseStrEnum
CPU instruction set a transformers export is quantized for.
Picking the wrong one still produces a valid model, just a slower one — the fused integer kernels are only selected when the CPU supports them.
ARM64— phones, Raspberry Pi, Apple silicon, Graviton.AVX2— any x86-64 since ~2013.AVX512— Skylake-SP and newer server CPUs.AVX512_VNNI— Cascade Lake and newer; the fastest int8 path.
There is no TensorRT member: that target is static-quantization only, and
:func:~tempest_fastapi_sdk.modelops.quantize_hf_onnx is a dynamic path.
Use :func:~tempest_fastapi_sdk.modelops.quantize_onnx_static with your
own calibration data for a TensorRT-bound artifact.
ModelFormatEnum
¶
Bases: BaseStrEnum
On-disk format of a model artifact.
TORCH— a PyTorch checkpoint (.pt/.pth) or a livetorch.nn.Module.ONNX— an ONNX graph (.onnx), the interchange format.ORT— an ONNX Runtime format file (.ort): the graph already optimized and serialized for the minimal mobile/edge runtime build.
OrtOptimizationStyleEnum
¶
Bases: BaseStrEnum
Optimization style applied when converting .onnx to .ort.
FIXED— bake the optimizations in at conversion time. Smallest and fastest at load, but the file is tied to the operator set that the conversion machine resolved. This is the edge/mobile default.RUNTIME— keep the graph closer to the original so the runtime can re-optimize for the device it actually lands on. Slightly slower to load, more portable across execution providers.
ParetoPoint
¶
Bases: BaseSchema
One model reduced to the axes the Pareto comparison uses.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Model name. |
latency_ms |
float
|
Median latency; lower is better. |
energy_j |
float | None
|
Energy per inference; lower is better. |
gflops |
float | None
|
Static forward GFLOPs; lower is better. |
memory_mb |
float | None
|
Peak memory (GPU when present, else RSS); lower is better. |
disk_size_mb |
float | None
|
Artifact size; lower is better. |
quality |
float | None
|
Caller-supplied quality; higher is better. |
is_pareto |
bool
|
True when no other point dominates this one. |
QuantizationBackendEnum
¶
Bases: BaseStrEnum
Which engine produced a quantized artifact.
ONNXRUNTIME_DYNAMIC— weights quantized ahead of time, activations quantized on the fly. No calibration data needed.ONNXRUNTIME_STATIC— weights and activations quantized using calibration samples. Faster, needs representative inputs.ONNXRUNTIME_TRANSFORMERS— the same dynamic quantizer, applied to a transformers export directory with the weight type and saturation settings that suit transformer graphs.BITSANDBYTES— transformers + bitsandbytes int8/int4 weights, kept in the PyTorch format.
QuantizationFormatEnum
¶
Bases: BaseStrEnum
How quantized operators are represented in the graph.
QDQ— insert explicitQuantizeLinear/DequantizeLinearpairs. Portable, and what most execution providers expect.QOPERATOR— use the fused quantized operators directly (QLinearConv,MatMulInteger, …). Smaller graph, narrower provider support.
QuantizationResult
¶
Bases: BaseSchema
Outcome of one quantization step.
Attributes:
| Name | Type | Description |
|---|---|---|
source_path |
str
|
Model that was quantized. |
output_path |
str
|
Quantized artifact. |
backend |
QuantizationBackendEnum
|
Engine that did the work. |
weight_type |
QuantWeightTypeEnum | None
|
Type the weights landed in. |
source_size_mb |
float
|
Input size in MB. |
output_size_mb |
float
|
Output size in MB. |
compression_ratio |
float
|
|
per_channel |
bool
|
Whether weights were quantized per channel. |
notes |
list[str]
|
Anything the caller should know — skipped operators, calibration sample count, provider caveats. |
QuantWeightTypeEnum
¶
Bases: BaseStrEnum
Integer/float type the weights are quantized to.
Names map 1:1 onto onnxruntime.quantization.QuantType members. The
exotic ones (INT4 / UINT4 / FLOAT8E4M3FN) only exist on newer
ONNX Runtime builds — asking for one the installed runtime does not have
raises a clear error instead of silently falling back.
RuntimeAggregate
¶
Bases: BaseSchema
Latency, memory and energy summary over the timed repetitions.
Latency is reported as median plus IQR first because inference latency is heavy-tailed: a single cold-start or scheduler hiccup moves the mean far more than the median. The mean is kept because throughput and energy-per-inference derive from it.
Attributes:
| Name | Type | Description |
|---|---|---|
device |
str
|
Device the model ran on ( |
provider |
str | None
|
Execution provider, for ONNX Runtime. |
n_warmup |
int
|
Warm-up calls discarded before timing. |
n_repetitions |
int
|
Timed calls. |
batch_size |
int
|
Batch size of a single call. |
latency_ms_median |
float
|
Median latency. |
latency_ms_iqr |
float
|
Inter-quartile range of latency. |
latency_ms_p95 |
float
|
95th-percentile latency. |
latency_ms_p99 |
float
|
99th-percentile latency. |
latency_ms_mean |
float
|
Mean latency. |
latency_ms_std |
float
|
Sample standard deviation (Bessel). |
latency_ms_min |
float
|
Fastest call. |
latency_ms_max |
float
|
Slowest call. |
throughput_per_s |
float
|
|
rss_peak_mb |
float | None
|
Highest RSS sampled. |
rss_delta_mb |
float | None
|
RSS growth from before warm-up to the last repetition — a rough leak signal. |
cpu_percent_mean |
float | None
|
Mean process CPU usage per core. |
gpu_memory_peak_mb |
float | None
|
Highest GPU memory sampled. Per process when a probe was supplied (the torch path), otherwise device-wide, counting every process on the card. |
gpu_power_mean_w |
float | None
|
Mean GPU power draw. |
gpu_energy_j |
float | None
|
GPU energy over the timed window. |
cpu_energy_j |
float | None
|
CPU package energy over the window. |
energy_per_inference_j |
float | None
|
Total measured energy divided
by |
energy_source |
EnergySourceEnum
|
Provenance of the energy figures. |
RuntimeSample
¶
Bases: BaseSchema
One timed repetition of a benchmark.
Attributes:
| Name | Type | Description |
|---|---|---|
index |
int
|
Zero-based repetition number. |
latency_ms |
float
|
Wall-clock time for the call, in milliseconds. |
rss_mb |
float | None
|
Process resident set size right after the
call, in MB. |
cpu_percent |
float | None
|
Process CPU usage since the previous sample, normalized per core. |
gpu_memory_mb |
float | None
|
GPU memory in use, in MB. |
gpu_power_w |
float | None
|
Most recent GPU power sample, in Watts. |
StaticModelMetrics
¶
Bases: BaseSchema
Model properties that do not depend on running inference.
Everything here is cheap to collect and stable across machines, which makes it the right thing to quote in a paper or a README: parameter count, on-disk size and (when a shape is known) forward GFLOPs.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Display name; defaults to the file stem. |
path |
str
|
Path that was inspected. Empty for an in-memory module. |
format |
ModelFormatEnum
|
Artifact format. |
n_parameters |
int
|
Total parameter count. |
n_trainable_parameters |
int | None
|
Parameters with gradients, when
the format tracks that (PyTorch). |
disk_size_mb |
float
|
Artifact size in MB. |
gflops |
float | None
|
Forward-pass GFLOPs at the profiled shape, or
|
opset |
int | None
|
ONNX opset version, when applicable. |
producer |
str | None
|
Tool that produced the artifact. |
inputs |
list[TensorSpec]
|
Declared inputs. |
outputs |
list[TensorSpec]
|
Declared outputs. |
TensorSpec
¶
Bases: BaseSchema
Name, element type and shape of one model input or output.
Dimensions come through as declared: an int for a fixed dimension and
a str for a symbolic one ("batch", "sequence"). A symbolic
dimension must be resolved to a concrete value before a benchmark can
feed the model.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Tensor name as declared in the graph. |
dtype |
str
|
Element type ( |
shape |
list[int | str]
|
One entry per dimension. |
OnnxPredictor
¶
OnnxPredictor(
model_path: str | Path,
*,
providers: Sequence[str] | None = None,
intra_op_threads: int = DEFAULT_INTRA_OP_THREADS,
inter_op_threads: int = 1,
warmup: bool = True,
dtype: str = "float32",
)
A loaded ONNX model, ready to answer.
Example:
>>> predictor = OnnxPredictor("dist/classifier.onnx")
>>> result = predictor.predict([[5.1, 3.5, 1.4, 0.2]])
>>> result.labels, result.probabilities[0]
([0], [0.98, 0.02, 0.0])
Thread-safe for concurrent :meth:predict: ONNX Runtime sessions are,
and :meth:reload swaps the session and its description together under
a lock, so an in-flight call finishes against the session it started
with and validates its rows against that same session.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
Path
|
The model file currently loaded. |
Load a model and prepare it to serve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
The |
required |
providers
|
Sequence[str] | None
|
Execution providers in
priority order, e.g.
|
None
|
intra_op_threads
|
int
|
Threads inside an operator. See
:data: |
DEFAULT_INTRA_OP_THREADS
|
inter_op_threads
|
int
|
Threads across operators. |
1
|
warmup
|
bool
|
Run one throwaway inference at construction so the first real request does not pay for allocation and kernel selection. |
True
|
dtype
|
str
|
Element type to coerce inputs to. Must match what the graph was exported with. |
'float32'
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When onnxruntime is unavailable. |
FileNotFoundError
|
When the model file does not exist. |
info
property
¶
info: PredictorInfo
Return what is loaded and how it is configured.
Returns:
| Name | Type | Description |
|---|---|---|
PredictorInfo |
PredictorInfo
|
The current model's description. |
warm_up
¶
Run one throwaway inference to pay the first-call cost now.
Skipped when the graph does not declare a fixed feature count, since
there is no shape to synthesise. A failure is logged, not raised: the
model is already in service, and a warm-up that fails here says the
same thing the first real request will — :meth:reload, which still
has a previous model to keep, refuses the swap instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
int
|
Rows in the warm-up batch. |
1
|
predict
¶
predict(features: TabularInput) -> Prediction
Predict for a batch of rows.
Example:
>>> predictor.predict([[5.1, 3.5, 1.4, 0.2], [6.2, 2.9, 4.3, 1.3]])
The session and its description are read together, so a
:meth:reload landing mid-call cannot validate the width against one
model and run the rows through another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
TabularInput
|
A 2-D array, nested sequence, or
DataFrame. A single row must still be wrapped: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Prediction |
Prediction
|
Labels, probabilities when the graph has them, |
Prediction
|
and the call's duration. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the input is not 2-D, or its width does not match what the graph expects. Checking the width here turns a confusing runtime error into a clear one. |
reload
¶
reload(model_path: str | Path, *, warmup: bool = True) -> PredictorInfo
Swap in a different model file without recreating the object.
The new session is built — and, with warmup, run once — before
the old one is dropped, so a broken file leaves the predictor serving
the previous model instead of taking it out of service. That is the
behaviour a fleet update needs: a bad rollout should degrade to
"still on the old version", never to "answering nothing".
Blocking: loading and warming run on the calling thread. From an
async handler, call it through asyncio.to_thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
The new model file. |
required |
warmup
|
bool
|
Run one inference on the new session before it serves, and refuse the swap when that inference fails. A model that loads but cannot answer its own declared input is a bad rollout, not a slow first request. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
PredictorInfo |
PredictorInfo
|
The newly loaded model's description. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When the new file does not exist. |
RuntimeError
|
When the new session fails its warm-up — the previous model stays in service. |
Exception
|
Whatever the runtime raises for an unloadable model — the previous model stays in service. |
Prediction
¶
Bases: BaseSchema
One batch of predictions.
Attributes:
| Name | Type | Description |
|---|---|---|
labels |
list[Any]
|
Predicted class or regressed value per row. |
probabilities |
list[list[float]]
|
Class scores per row, empty for a regressor or a graph without a score output. |
n_rows |
int
|
Rows predicted. |
seconds |
float
|
Wall-clock duration of the call. |
PredictorInfo
¶
Bases: BaseSchema
What a loaded predictor is and how it is configured.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
The model file in use. |
input_name |
str
|
Graph input name. |
n_features |
int | None
|
Features per row, when the graph declares a fixed second dimension. |
output_names |
list[str]
|
Every graph output, in order. |
label_output |
str | None
|
The output holding predicted classes. |
proba_output |
str | None
|
The output holding class scores. |
providers |
list[str]
|
Execution providers actually in use — not the ones requested. ONNX Runtime silently falls back, so a device you believe is on CUDA may be on CPU. |
intra_op_threads |
int
|
Threads used inside an operator. |
is_classifier |
bool
|
Whether a class output was found. |
EdgeBundle
¶
Bases: BaseSchema
Everything :func:edge_bundle produced.
Attributes:
| Name | Type | Description |
|---|---|---|
export |
SklearnExport
|
The initial conversion. |
verification |
ExportVerification | None
|
The numeric check, when samples were given to run it with. |
stages |
list[EdgeStage]
|
Each step, in order. |
deployable |
str
|
The artifact to ship — the last one produced. |
size_reduction |
float
|
Deployable size as a fraction of the
first export. |
EdgeStage
¶
Bases: BaseSchema
One step of :func:edge_bundle, and what it cost.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The stage — |
path |
str
|
The artifact it produced. |
size_bytes |
int
|
That artifact's size. |
skipped |
bool
|
Whether the stage was skipped. |
note |
str
|
Why it was skipped, or what it did. |
ExportVerification
¶
Bases: BaseSchema
How closely the exported graph reproduces the estimator.
Attributes:
| Name | Type | Description |
|---|---|---|
passed |
bool
|
Whether the export is within tolerance. |
n_samples |
int
|
Samples compared. |
max_abs_diff |
float | None
|
Largest absolute difference across compared outputs, when the outputs are numeric. |
label_agreement |
float | None
|
Fraction of samples where the
predicted class matched, for classifiers. |
mismatched |
int
|
Samples where the label differed. |
detail |
str
|
What was compared and what happened. |
SklearnExport
¶
Bases: BaseSchema
The result of converting an estimator.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
str
|
Where the |
size_bytes |
int
|
Its size on disk. |
opset |
int
|
The opset it targets. |
dtype |
TensorDtypeEnum
|
Input element type. |
input_name |
str
|
Name of the graph input. |
n_features |
int
|
Features the graph expects per row. |
zipmap |
bool
|
Whether the ZipMap wrapper was kept. |
estimator |
str
|
Class name of the exported estimator. |
needs_verification
property
¶
Return whether this export must be verified before shipping.
Always True in spirit — every export should be checked — but
it is True emphatically when :attr:warnings is non-empty,
because then a specific, documented converter defect is known to
affect this combination.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether a known issue applies to this export. |
TensorDtypeEnum
¶
Bases: BaseStrEnum
Element type of the exported graph's input.
FLOAT32— the edge default. Half the memory of double, and the precision device accelerators actually implement.FLOAT64— matches scikit-learn exactly. Use it when a numerical difference matters more than size, and accept that many runtimes will fall back to a slow path or refuse.
benchmark
¶
benchmark(
call: Callable[[], Any],
*,
name: str = "callable",
n_warmup: int = DEFAULT_WARMUP,
n_repetitions: int = DEFAULT_REPETITIONS,
batch_size: int = 1,
device: str = "cpu",
provider: str | None = None,
static: StaticModelMetrics | None = None,
power_sampler: PowerSampler | None = None,
cpu_energy_sampler: PowerSampler | None = None,
sync: Callable[[], None] | None = None,
memory_probe: Callable[[], float | None] | None = None,
keep_samples: bool = False,
) -> BenchmarkProfile
Time a callable and report latency, memory and energy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
call
|
Callable[[], Any]
|
Zero-argument callable performing exactly one unit of work. Build the inputs outside it — anything done inside is measured as part of the model. |
required |
name
|
str
|
Display name for the profile. |
'callable'
|
n_warmup
|
int
|
Calls to run and discard before timing. |
DEFAULT_WARMUP
|
n_repetitions
|
int
|
Timed calls. Must be at least 1. |
DEFAULT_REPETITIONS
|
batch_size
|
int
|
Items processed per call; only used to turn latency into throughput. |
1
|
device
|
str
|
Device label recorded in the report. |
'cpu'
|
provider
|
str | None
|
Execution provider label, for ONNX Runtime. |
None
|
static
|
StaticModelMetrics | None
|
Static metrics to attach. |
None
|
power_sampler
|
PowerSampler | None
|
GPU sampler. By default one
is resolved only when |
None
|
cpu_energy_sampler
|
PowerSampler | None
|
CPU energy sampler.
Defaults to
:func: |
None
|
sync
|
Callable[[], None] | None
|
Called before starting and after
stopping each timer. Required for asynchronous backends —
without |
None
|
memory_probe
|
Callable[[], float | None] | None
|
Returns device memory in MB for the current call. |
None
|
keep_samples
|
bool
|
Keep the per-repetition samples on the profile. Off by default: 50 rows per model is noise in a summary and weight in a JSON response. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkProfile |
BenchmarkProfile
|
Aggregate over the timed calls, plus the raw |
BenchmarkProfile
|
samples when |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Example:
>>> from tempest_fastapi_sdk.modelops import benchmark
>>> profile = benchmark(
... lambda: sum(range(10_000)),
... name="sum",
... n_warmup=2,
... n_repetitions=5,
... )
>>> profile.runtime.n_repetitions
5
benchmark_models
¶
benchmark_models(
model_paths: Sequence[str | Path],
*,
quality: Mapping[str, float] | None = None,
weights: Mapping[str, float] | None = None,
share_samplers: bool = True,
**kwargs: Any,
) -> BenchmarkReport
Benchmark several ONNX/ORT models and rank them against each other.
Every model is measured with the same settings and the same samplers, which is the only way the comparison means anything.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_paths
|
Sequence[str | Path]
|
Models to compare. |
required |
quality
|
Mapping[str, float] | None
|
Model name to task quality (accuracy, F1, mAP…). Needed for the Pareto frontier — cost alone cannot say which model is better. |
None
|
weights
|
Mapping[str, float] | None
|
Composite-score weights. See
:data: |
None
|
share_samplers
|
bool
|
Reuse one CPU energy sampler across all models instead of re-scanning the powercap tree for each. The GPU sampler is still chosen per model from the device it ran on. |
True
|
**kwargs
|
Any
|
Forwarded to :func: |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkReport |
BenchmarkReport
|
Ranked profiles, Pareto annotation, the effective |
BenchmarkReport
|
weights and the host description. |
Example:
>>> from tempest_fastapi_sdk.modelops import benchmark_models
>>> report = benchmark_models(
... ["models/n.onnx", "models/s.onnx"],
... quality={"n": 0.80, "s": 0.84},
... n_repetitions=20,
... )
>>> [p.name for p in report.profiles]
benchmark_onnx
¶
benchmark_onnx(
model_path: str | Path,
*,
name: str | None = None,
providers: list[str] | None = None,
feeds: Mapping[str, Any] | None = None,
input_shapes: Mapping[str, Sequence[int]] | None = None,
dynamic_dims: Mapping[str, int] | None = None,
batch_size: int = 1,
n_warmup: int = DEFAULT_WARMUP,
n_repetitions: int = DEFAULT_REPETITIONS,
keep_samples: bool = False,
seed: int = 0,
power_sampler: PowerSampler | None = None,
cpu_energy_sampler: PowerSampler | None = None,
) -> BenchmarkProfile
Benchmark an .onnx or .ort model through ONNX Runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
Model to load. |
required |
name
|
str | None
|
Display name. Defaults to the file stem. |
None
|
providers
|
list[str] | None
|
Execution providers, in preference order. Defaults to whatever the runtime offers. |
None
|
feeds
|
Mapping[str, Any] | None
|
Real inputs to run. Strongly preferred over synthetic data when latency depends on content (sequence length, number of detections). Synthesized when omitted. |
None
|
input_shapes
|
Mapping[str, Sequence[int]] | None
|
Explicit shape per input, for synthesized feeds. |
None
|
dynamic_dims
|
Mapping[str, int] | None
|
Value for each symbolic
dimension, e.g. |
None
|
batch_size
|
int
|
Value used for an unnamed leading dimension, and the divisor for throughput. |
1
|
n_warmup
|
int
|
Warm-up calls discarded. |
DEFAULT_WARMUP
|
n_repetitions
|
int
|
Timed calls. |
DEFAULT_REPETITIONS
|
keep_samples
|
bool
|
Keep per-repetition samples. |
False
|
seed
|
int
|
Seed for synthesized inputs. |
0
|
power_sampler
|
PowerSampler | None
|
GPU sampler override. |
None
|
cpu_energy_sampler
|
PowerSampler | None
|
CPU sampler override. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkProfile |
BenchmarkProfile
|
Runtime aggregate plus static metrics when the |
BenchmarkProfile
|
artifact could be analyzed. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
FileNotFoundError
|
When the model does not exist. |
ValueError
|
When a symbolic dimension cannot be resolved. |
Example:
>>> from tempest_fastapi_sdk.modelops import benchmark_onnx
>>> profile = benchmark_onnx(
... "models/classify.onnx",
... dynamic_dims={"height": 224, "width": 224},
... n_repetitions=20,
... )
>>> profile.runtime.latency_ms_median
benchmark_torch
¶
benchmark_torch(
module: Module,
example_input: TorchExampleInput,
*,
name: str | None = None,
device: str | None = None,
batch_size: int = 1,
n_warmup: int = DEFAULT_WARMUP,
n_repetitions: int = DEFAULT_REPETITIONS,
keep_samples: bool = False,
collect_static: bool = True,
power_sampler: PowerSampler | None = None,
cpu_energy_sampler: PowerSampler | None = None,
) -> BenchmarkProfile
Benchmark a torch.nn.Module forward pass.
The module is switched to eval() and run under torch.no_grad(),
and on CUDA every timer is bracketed by torch.cuda.synchronize().
Both inputs and module are moved to the target device before warm-up, so
the timed window contains no host-to-device copy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
The module to benchmark. |
required |
example_input
|
TorchExampleInput
|
A tensor, or a tuple of tensors, to feed it. |
required |
name
|
str | None
|
Display name. Defaults to the class name. |
None
|
device
|
str | None
|
|
None
|
batch_size
|
int
|
Items per call, for the throughput figure. |
1
|
n_warmup
|
int
|
Warm-up calls discarded. |
DEFAULT_WARMUP
|
n_repetitions
|
int
|
Timed calls. |
DEFAULT_REPETITIONS
|
keep_samples
|
bool
|
Keep per-repetition samples. |
False
|
collect_static
|
bool
|
Also count parameters and FLOPs. The FLOP count runs one extra forward pass. |
True
|
power_sampler
|
PowerSampler | None
|
GPU sampler override. |
None
|
cpu_energy_sampler
|
PowerSampler | None
|
CPU sampler override. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkProfile |
BenchmarkProfile
|
Runtime aggregate, plus static metrics when |
BenchmarkProfile
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When torch is not installed. |
Example:
>>> import torch
>>> from tempest_fastapi_sdk.modelops import benchmark_torch
>>> profile = benchmark_torch(
... torch.nn.Linear(128, 10),
... torch.randn(1, 128),
... n_warmup=2,
... n_repetitions=5,
... )
>>> profile.runtime.n_repetitions
5
export_sklearn_to_compact
¶
export_sklearn_to_compact(
estimator: SklearnEstimator,
verify_samples: TabularInput | Literal[False] | None = None,
output_path: str | Path = "model.tmc",
*,
feature_names: Sequence[str] | None = None,
tolerance: float = DEFAULT_TOLERANCE,
) -> CompactExport
Write a fitted estimator as a runtime-free compact model.
Example:
>>> export = export_sklearn_to_compact(model, X_test, "dist/risk.tmc")
>>> export.kind, export.verified
(<CompactKindEnum.TREE_ENSEMBLE: 'tree_ensemble'>, True)
The result is read by tempest-react-sdk/tabular's CompactPredictor,
which needs no WebAssembly and no ONNX Runtime — the whole reader is
about two kilobytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
SklearnEstimator
|
A fitted linear model, tree, forest, or a
Pipeline of |
required |
verify_samples
|
TabularInput | Literal[False] | None
|
Rows to check
the written file against the estimator's own predictions. Strongly
recommended: this format is verified by that comparison and nothing
else. Pass |
None
|
output_path
|
str | Path
|
Where to write. |
'model.tmc'
|
feature_names
|
Sequence[str] | None
|
Column order to record.
Taken from |
None
|
tolerance
|
float
|
Largest probability difference accepted. |
DEFAULT_TOLERANCE
|
Returns:
| Name | Type | Description |
|---|---|---|
CompactExport |
CompactExport
|
Where it was written, what it holds, and whether it |
CompactExport
|
reproduces the estimator. |
Raises:
| Type | Description |
|---|---|
UnsupportedEstimatorError
|
When the estimator (or a pipeline step) has no compact representation. The message names the ONNX route, which covers everything this does not. |
ValueError
|
When the written file disagrees with the estimator. |
predict_compact
¶
predict_compact(
path: str | Path, rows: TabularInput
) -> tuple[list[Any], list[list[float]]]
Predict with the reference decoder.
Mirrors what the browser reader does, step for step, so a disagreement between them is a format bug rather than a language difference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The compact file. |
required |
rows
|
TabularInput
|
A 2-D array of feature values. |
required |
Returns:
| Type | Description |
|---|---|
list[Any]
|
tuple[list[Any], list[list[float]]]: Labels and per-class scores; |
list[list[float]]
|
the scores are empty for a regression model. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When numpy (the |
read_compact
¶
Read a compact file back into its header and arrays.
The reference decoder: the browser has its own, and these two agreeing is what makes the format a contract rather than a convention.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
The file to read. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
tuple[dict[str, Any], dict[str, Any]]: The header, and the sections |
dict[str, Any]
|
as numpy arrays keyed by name. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When numpy (the |
ValueError
|
When the magic bytes or schema version do not match. |
edge_pipeline
¶
edge_pipeline(
estimator: SklearnEstimator,
samples: TabularInput,
output_dir: str | Path,
*,
name: str = "model",
version: str | None = None,
labels: TabularInput | None = None,
feature_names: Sequence[str] | None = None,
verify_samples: TabularInput | Literal[False] | None = None,
tolerance: float = 0.0001,
baseline: bool = True,
bins: int = DEFAULT_BINS,
compress: bool = True,
compact: bool = False,
dtype: TensorDtypeEnum = FLOAT32,
opset: int = DEFAULT_OPSET,
) -> EdgePackage
Turn a fitted estimator into a directory you ship as-is.
Runs export → verify → drift baseline → manifest, writing a
self-describing package that this SDK's :func:load_edge_package and
tempest-react-sdk/tabular both consume.
Example:
>>> package = edge_pipeline(model, X_train, "dist/risk", labels=y_train)
>>> package.manifest.version, package.manifest.verified
('a1b2c3d4e5f6', True)
What this deliberately does not run, and why. Measured on random forests of 10 to 300 trees exported from scikit-learn:
- Graph optimisation changed the file by 0.1 KB on every size. The
ai.onnx.mloperators are single nodes; there is nothing to fuse. .ortconversion more than doubled the file every time (381 KB to 878 KB; 12.1 MB to 27.0 MB). It is a runtime-loading format, not a compression one.- int8 quantisation does not apply at all — tree and linear parameters are node attributes, not tensors.
- gzip took the same files to 10-13% of their size. That is the lever, and it costs nothing but a Content-Encoding header.
Use :func:~tempest_fastapi_sdk.modelops.edge_bundle when you want to
see those stages measured on your own model rather than trusting the
summary.
What actually controls size is the estimator, before any of this:
at 50 trees on 20 features, max_depth=6 produced 257 KB at 0.881
test accuracy while unlimited depth produced 1444 KB at 0.922 —
5.6x the bytes for 4 points. Single-row latency was identical
(0.0075 ms vs 0.0079 ms), because on these graphs latency is not what
you are trading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
SklearnEstimator
|
The fitted estimator or Pipeline. |
required |
samples
|
TabularInput
|
Training rows — used both to trace the export and to build the drift baseline. Pass the training set: a baseline built from production traffic describes the drifted population as normal. |
required |
output_dir
|
str | Path
|
Directory to create and fill. |
required |
name
|
str
|
Logical model name; also the model filename stem. |
'model'
|
version
|
str | None
|
Build version. Defaults to the model's content hash, so republishing identical bytes does not look like a new version to a device. |
None
|
labels
|
TabularInput | None
|
Training labels, recorded as the baseline output distribution. Without them, output drift cannot be measured. |
None
|
feature_names
|
Sequence[str] | None
|
Column order. Taken from a DataFrame when not given, positional indices otherwise. |
None
|
verify_samples
|
TabularInput | Literal[False] | None
|
Rows to check
the export against the estimator's own predictions. Defaults to
|
None
|
tolerance
|
float
|
Numeric tolerance for that check. |
0.0001
|
baseline
|
bool
|
Write the drift baseline. |
True
|
bins
|
int
|
Quantile bins per feature in the baseline. |
DEFAULT_BINS
|
compress
|
bool
|
Also write a gzipped copy of the graph. |
True
|
compact
|
bool
|
Also write the runtime-free |
False
|
dtype
|
TensorDtypeEnum
|
Input element type. |
FLOAT32
|
opset
|
int
|
Target ONNX opset. |
DEFAULT_OPSET
|
Returns:
| Name | Type | Description |
|---|---|---|
EdgePackage |
EdgePackage
|
Paths and the manifest. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the export fails verification. Shipping a graph
that does not reproduce the estimator is the one outcome this
pipeline refuses to let pass quietly — pass
|
load_edge_package
¶
load_edge_package(
directory: str | Path,
*,
providers: Sequence[str] | None = None,
intra_op_threads: int = DEFAULT_INTRA_OP_THREADS,
monitor: bool = True,
window_rows: int | None = None,
verify_digest: bool = True,
) -> LoadedEdgePackage
Load a package into a running predictor, monitor included.
Example:
>>> loaded = load_edge_package("dist/risk")
>>> result = loaded.predictor.predict(rows)
>>> loaded.monitor.observe(rows, result)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
The package directory. |
required |
providers
|
Sequence[str] | None
|
Execution providers. Include a CPU fallback on a GPU device. |
None
|
intra_op_threads
|
int
|
Threads inside an operator. Worth raising for a large ensemble or a batched workload — measured on a 300-tree forest, 1000 rows went from 16.6 ms at one thread to 2.3 ms at eight. A small graph shows no difference at all. |
DEFAULT_INTRA_OP_THREADS
|
monitor
|
bool
|
Wire a :class: |
True
|
window_rows
|
int | None
|
Drift window size; the monitor's default when omitted. |
None
|
verify_digest
|
bool
|
Check the model file against the manifest's SHA-256 before loading it. A truncated download otherwise fails as a confusing parse error, or worse, does not fail. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
LoadedEdgePackage |
LoadedEdgePackage
|
Manifest, predictor, monitor and baseline. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When the manifest or model file is missing. |
ValueError
|
When the model file does not match its digest. |
read_manifest
¶
read_manifest(directory: str | Path) -> EdgeManifest
Read a package's manifest without loading the model.
Cheap enough for a device to run on a schedule: it answers "is the published version the one I have" without touching the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
The package directory. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
EdgeManifest |
EdgeManifest
|
The parsed manifest. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When the directory has no manifest. |
resolve_cpu_energy_sampler
¶
resolve_cpu_energy_sampler() -> PowerSampler
Return a CPU energy sampler, or a no-op when RAPL is unreachable.
Returns:
| Name | Type | Description |
|---|---|---|
PowerSampler |
PowerSampler
|
:class: |
PowerSampler
|
class: |
Example:
>>> resolve_cpu_energy_sampler().available
False
resolve_power_sampler
¶
resolve_power_sampler(
*, device_index: int = 0, interval_s: float = DEFAULT_SAMPLE_INTERVAL_S
) -> PowerSampler
Return the best available GPU power sampler for this host.
Order of preference: NVML (accurate, cheap), nvidia-smi (works
without pynvml), then :class:NullPowerSampler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device_index
|
int
|
Zero-based GPU index to measure. |
0
|
interval_s
|
float
|
Polling interval in seconds. |
DEFAULT_SAMPLE_INTERVAL_S
|
Returns:
| Name | Type | Description |
|---|---|---|
PowerSampler |
PowerSampler
|
A sampler that is either available or a no-op. |
Example:
>>> sampler = resolve_power_sampler()
>>> sampler.available
False
export_onnx_to_ort
¶
export_onnx_to_ort(
model_path: str | Path,
output_dir: str | Path | None = None,
*,
optimization_style: OrtOptimizationStyleEnum = FIXED,
enable_type_reduction: bool = False,
target_platform: str | None = None,
save_optimized_onnx_model: bool = False,
allow_conversion_failures: bool = False,
custom_op_library: str | Path | None = None,
) -> list[ExportResult]
Convert one .onnx file — or a directory of them — to .ort.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
A |
required |
output_dir
|
str | Path | None
|
Where to write. Defaults to writing next to each input. |
None
|
optimization_style
|
OrtOptimizationStyleEnum
|
|
FIXED
|
enable_type_reduction
|
bool
|
Also record which data types each operator needs, so a minimal build can drop unused type implementations. Shrinks the runtime binary further; only useful together with a custom build. |
False
|
target_platform
|
str | None
|
|
None
|
save_optimized_onnx_model
|
bool
|
Also write the optimized |
False
|
allow_conversion_failures
|
bool
|
Keep going when one model in a directory fails, instead of aborting the batch. |
False
|
custom_op_library
|
str | Path | None
|
Shared library providing custom operators the model needs. |
None
|
Returns:
| Type | Description |
|---|---|
list[ExportResult]
|
list[ExportResult]: One entry per |
list[ExportResult]
|
the size comparison and the config side files. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
FileNotFoundError
|
When |
Example:
>>> from tempest_fastapi_sdk.modelops import export_onnx_to_ort
>>> results = export_onnx_to_ort(
... "models/classify.onnx",
... "models/mobile",
... target_platform="arm",
... enable_type_reduction=True,
... )
>>> results[0].output_path
export_torch_to_onnx
¶
export_torch_to_onnx(
module: Module,
output_path: str | Path,
*,
example_input: TorchExampleInput,
opset: int = 17,
input_names: list[str] | None = None,
output_names: list[str] | None = None,
dynamic_axes: dict[str, dict[int, str]] | None = None,
half: bool = False,
do_constant_folding: bool = True,
source_path: str | Path | None = None,
) -> ExportResult
Export a torch.nn.Module to ONNX.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
Module to export. It is switched to |
required |
output_path
|
str | Path
|
Where to write the |
required |
example_input
|
TorchExampleInput
|
A tensor, or tuple of tensors,
tracing runs through the model. Its shapes become the graph's
fixed shapes unless |
required |
opset
|
int
|
ONNX opset. Newer is more expressive; older is more
portable — mobile runtimes and third-party converters often lag,
and |
17
|
input_names
|
list[str] | None
|
Names for the graph inputs. |
None
|
output_names
|
list[str] | None
|
Names for the graph outputs. |
None
|
dynamic_axes
|
dict[str, dict[int, str]] | None
|
Axes that must stay
variable, e.g. |
None
|
half
|
bool
|
Convert the module and inputs to float16 before tracing. Mutates the module in place. Halves the artifact, but a float16 graph is slower than float32 on most CPUs — this is for GPU and for ARM cores with native half support. |
False
|
do_constant_folding
|
bool
|
Fold constant subgraphs at export. |
True
|
source_path
|
str | Path | None
|
Checkpoint the module came from, recorded for the size comparison. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ExportResult |
ExportResult
|
The written artifact with its size and opset. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When torch is not installed. |
Example:
>>> import torch
>>> from tempest_fastapi_sdk.modelops import export_torch_to_onnx
>>> result = export_torch_to_onnx(
... torch.nn.Linear(128, 10),
... "linear.onnx",
... example_input=torch.randn(1, 128),
... input_names=["features"],
... output_names=["logits"],
... dynamic_axes={"features": {0: "batch"}},
... )
>>> result.opset
17
optimize_onnx_graph
¶
optimize_onnx_graph(
model_path: str | Path,
output_path: str | Path,
*,
level: GraphOptimizationLevelEnum = ALL,
providers: list[str] | None = None,
) -> ExportResult
Run ONNX Runtime's graph optimizer and write the result back out.
This is constant folding plus operator fusion — the same work the
runtime does at every session start, done once and persisted. It changes
the graph, not the numerics, so accuracy is unaffected. Reach for it
when start-up latency matters but you cannot move to .ort.
An optimized graph is specialized for the providers it was optimized with: a model fused for CUDA can be slower, or fail to load, on a CPU-only host. Optimize per target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
Model to optimize. |
required |
output_path
|
str | Path
|
Where to write the optimized |
required |
level
|
GraphOptimizationLevelEnum
|
How aggressive to be. |
ALL
|
providers
|
list[str] | None
|
Providers to optimize for. Defaults to whatever the runtime offers. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ExportResult |
ExportResult
|
The written artifact with a before/after size ratio. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
FileNotFoundError
|
When the input does not exist. |
ValueError
|
When the installed runtime has no such level. |
Example:
>>> from tempest_fastapi_sdk.modelops import optimize_onnx_graph
>>> result = optimize_onnx_graph(
... "models/classify.onnx", "models/classify.opt.onnx"
... )
>>> result.size_ratio
baseline_from_samples
¶
baseline_from_samples(
features: TabularInput,
*,
labels: TabularInput | None = None,
names: Sequence[str] | None = None,
bins: int = DEFAULT_BINS,
) -> FeatureBaseline
Summarise a training set into a shippable baseline.
Run this on the training data, at training time, and ship the result with the model. Building it from early production traffic instead defeats the purpose: it would describe the drifted population as normal.
Example:
>>> baseline = baseline_from_samples(X_train, labels=y_train)
>>> Path("dist/baseline.json").write_text(baseline.model_dump_json())
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
TabularInput
|
The training rows — a 2-D array, nested
sequence, or DataFrame. Column names are taken from a DataFrame
when |
required |
labels
|
TabularInput | None
|
Training labels or the model's predictions on the training set, used as the baseline output distribution. Omit for a regressor. |
None
|
names
|
Sequence[str] | None
|
Feature names. Defaults to the DataFrame's columns, or positional indices. |
None
|
bins
|
int
|
Quantile bins per feature. |
DEFAULT_BINS
|
Returns:
| Name | Type | Description |
|---|---|---|
FeatureBaseline |
FeatureBaseline
|
Edges and proportions per feature, plus the |
FeatureBaseline
|
baseline class shares when labels were given. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When numpy (the |
ValueError
|
When |
population_stability_index
¶
Compute the PSI between two binned distributions.
PSI = sum((actual - expected) * ln(actual / expected)) over bins,
with :data:_PSI_EPSILON substituted for an empty bin so one unseen
value cannot produce an infinite score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expected
|
Sequence[float]
|
Baseline proportions per bin. |
required |
actual
|
Sequence[float]
|
Observed proportions per bin. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The index. Zero for identical distributions; read against |
float
|
data: |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the two distributions have different bin counts, which would silently compare unrelated bins. |
edge_pipeline_from_pickle
¶
edge_pipeline_from_pickle(
path: str | Path,
samples: TabularInput,
output_dir: str | Path,
*,
key: str | None = None,
expected_sha256: str | None = None,
feature_names: Sequence[str] | None = None,
**kwargs: Any,
) -> EdgePackage
Convert a pickled estimator into a shippable edge package.
The build-time half of the story: the pickle stays in your pipeline, the ONNX package goes to devices and browsers.
Example:
>>> package = edge_pipeline_from_pickle(
... "artifacts/risk.pkl", X_train, "dist/risk", labels=y_train,
... )
>>> package.manifest.source.file, package.manifest.verified
('risk.pkl', True)
Column order comes from the estimator's own feature_names_in_ when
it has one, so a model fitted on a DataFrame carries its columns into
the manifest without anyone retyping them — which is the field that
catches a browser sending features in the wrong order.
The manifest records the pickle's name, digest and the scikit-learn version that read it, so an artifact running on a device can be traced back to the file that produced it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Local path to the pickle. |
required |
samples
|
TabularInput
|
Training rows, used to trace the export and build the drift baseline. |
required |
output_dir
|
str | Path
|
Package directory to create. |
required |
key
|
str | None
|
Entry to take when the pickle holds a dict. |
None
|
expected_sha256
|
str | None
|
The SHA-256 the pickle must have,
checked before it is unpickled. See
:func: |
None
|
feature_names
|
Sequence[str] | None
|
Column order, overriding whatever the estimator recorded. |
None
|
**kwargs
|
Any
|
Forwarded to
:func: |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
EdgePackage |
EdgePackage
|
The written package, with provenance in its manifest. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the path is a URL, or when the exported graph does not reproduce the estimator. |
FileNotFoundError
|
When the pickle does not exist. |
ArtifactDigestMismatchError
|
When the pickle's SHA-256 differs from
|
TypeError
|
When the pickle holds something that cannot predict. |
load_sklearn_artifact
¶
load_sklearn_artifact(
path: str | Path, *, key: str | None = None, expected_sha256: str | None = None
) -> LoadedArtifact
Read a fitted estimator out of a pickle, recording its provenance.
Example:
>>> artifact = load_sklearn_artifact("artifacts/risk.pkl")
>>> artifact.estimator_type, artifact.sha256[:12]
('RandomForestClassifier', 'a1b2c3d4e5f6')
Pinning the digest the release recorded:
>>> artifact = load_sklearn_artifact(
... "artifacts/risk.pkl",
... expected_sha256="sha256:A1B2C3D4E5F6...",
... )
This executes the code in the file. Point it at artifacts your own pipeline produced, in your own build environment — never at an upload, and never at something a device downloaded.
The file is opened once: it is hashed through that handle, compared
with expected_sha256 when given, and only then unpickled from the
same handle — so the bytes that were checked are the bytes that run,
even if the path is swapped for another file in between.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Local path to a |
required |
key
|
str | None
|
Entry to take when the pickle holds a dict. Not needed when exactly one entry can predict. |
None
|
expected_sha256
|
str | None
|
The SHA-256 the file must have, as
hex in any case, optionally prefixed with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
LoadedArtifact |
LoadedArtifact
|
The estimator plus its digest, size, the |
LoadedArtifact
|
scikit-learn version that read it, any warnings raised, and the |
|
LoadedArtifact
|
column order when the estimator recorded one. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the path looks like a URL. Downloading and loading
in one call is the shape that turns a registry into remote code
execution; fetch deliberately first if that is what you mean.
Also raised when |
FileNotFoundError
|
When the file does not exist. |
ArtifactDigestMismatchError
|
When the file's SHA-256 differs from
|
TypeError
|
When the file holds something that cannot predict. |
ImportError
|
When |
optimize_hf_onnx
¶
optimize_hf_onnx(
model_dir: str | Path,
output_dir: str | Path,
*,
level: HFOptimizationLevelEnum = O2,
for_gpu: bool = False,
file_name: str | None = None,
model_type: str | None = None,
use_external_data_format: bool | None = None,
) -> ExportResult
Apply ONNX Runtime's transformer fusions to an exported model.
Unlike quantization this is lossless in precision at O1/O2: it
fuses attention, layer norm and friends into single kernels without
changing what the graph computes. O3 swaps in an approximate GELU and
O4 converts to float16, so those two do move the numbers.
The fusion engine is onnxruntime.transformers, which ships inside the
onnxruntime wheel — no HuggingFace optimum involved, and therefore no
bound on your transformers version. See this module's docstring for how
to produce the export in the first place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_dir
|
str | Path
|
Directory an ONNX export wrote — the graph plus
|
required |
output_dir
|
str | Path
|
Where to write the optimized model. The export's non-graph files are copied along. |
required |
level
|
HFOptimizationLevelEnum
|
Optimization preset. |
O2
|
for_gpu
|
bool
|
Target GPU kernels. A model optimized for GPU is not portable back to CPU. |
False
|
file_name
|
str | None
|
Specific graph inside |
None
|
model_type
|
str | None
|
Override the fusion type instead of deriving
it from |
None
|
use_external_data_format
|
bool | None
|
Write tensors outside the
protobuf. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ExportResult |
ExportResult
|
The optimized directory and its size. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When |
FileNotFoundError
|
When the export directory or its |
Example:
>>> from tempest_fastapi_sdk.modelops import optimize_hf_onnx
>>> result = optimize_hf_onnx(
... "exports/distilbert", "exports/distilbert-o2"
... )
>>> result.output_path
quantize_hf_bnb
¶
quantize_hf_bnb(
model_id: str,
output_dir: str | Path,
*,
bits: int = 4,
quant_type: str = "nf4",
compute_dtype: str = "float16",
double_quant: bool = True,
trust_remote_code: bool = False,
) -> QuantizationResult
Load a HuggingFace model in int8/int4 and save the quantized weights.
This is the PyTorch path, for generative models that stay in
transformers. Unlike the ONNX routes it keeps the model runnable through
AutoModelForCausalLM, which is what
:class:~tempest_fastapi_sdk.genai.TextGenerator consumes.
Quantizing requires a CUDA GPU — bitsandbytes has no CPU kernel for the conversion — and the saved artifact can only be reloaded on a machine that also has bitsandbytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
Hub id or local directory to load. |
required |
output_dir
|
str | Path
|
Where to save the quantized weights. |
required |
bits
|
int
|
|
4
|
quant_type
|
str
|
4-bit data type — |
'nf4'
|
compute_dtype
|
str
|
Dtype the dequantized matmul runs in;
|
'float16'
|
double_quant
|
bool
|
Quantize the quantization constants too. Saves roughly another 0.4 bits per parameter for no measurable quality cost. |
True
|
trust_remote_code
|
bool
|
Allow executing custom modelling code from the Hub repository. This runs arbitrary Python from a remote source — only enable it for a repository you audited. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
QuantizationResult |
QuantizationResult
|
Output directory and its size, with the source |
QuantizationResult
|
size left at zero because the original lives in the HuggingFace |
|
QuantizationResult
|
cache rather than at a path we were given. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When transformers, torch or bitsandbytes are missing. |
ValueError
|
When |
Example:
>>> from tempest_fastapi_sdk.modelops import quantize_hf_bnb
>>> result = quantize_hf_bnb(
... "Qwen/Qwen2.5-0.5B-Instruct", "models/qwen-int4", bits=4
... )
>>> result.backend
quantize_hf_onnx
¶
quantize_hf_onnx(
model_dir: str | Path,
output_dir: str | Path,
*,
target: HFQuantizationTargetEnum = AVX512_VNNI,
per_channel: bool = False,
reduce_range: bool = False,
symmetric_weights: bool = True,
file_name: str | None = None,
) -> QuantizationResult
Dynamically quantize an exported transformers model to int8.
Same engine as :func:quantize_onnx_dynamic, with the weight type and
saturation settings that suit transformer graphs on the CPU you will
actually deploy on, and with the export's tokenizer and config carried
forward so the output directory stays loadable.
Static quantization is deliberately not offered here: it needs a
calibration dataset, and building one is a modelling decision. Export
first, then call :func:quantize_onnx_static on the graph with your own
samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_dir
|
str | Path
|
Directory an ONNX export wrote. |
required |
output_dir
|
str | Path
|
Where to write the quantized model. |
required |
target
|
HFQuantizationTargetEnum
|
Instruction set to target. Choosing one your CPU lacks still yields a valid model, just a slow one. |
AVX512_VNNI
|
per_channel
|
bool
|
Quantize weights per output channel instead of per tensor. Better accuracy, slightly larger. |
False
|
reduce_range
|
bool
|
Use 7 bits instead of 8, avoiding the int8
saturation that pre-VNNI x86 is prone to. Only |
False
|
symmetric_weights
|
bool
|
Center the weight range on zero. On by default, matching ONNX Runtime. |
True
|
file_name
|
str | None
|
Specific graph inside |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
QuantizationResult |
QuantizationResult
|
The quantized directory and its size ratio. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When |
FileNotFoundError
|
When the export directory is missing. |
Example:
>>> from tempest_fastapi_sdk.modelops import quantize_hf_onnx
>>> result = quantize_hf_onnx(
... "exports/distilbert",
... "exports/distilbert-int8",
... target="arm64",
... )
>>> result.compression_ratio
quantize_onnx_dynamic
¶
quantize_onnx_dynamic(
model_path: str | Path,
output_path: str | Path,
*,
weight_type: QuantWeightTypeEnum = INT8,
per_channel: bool = False,
reduce_range: bool = False,
op_types: Sequence[str] | None = None,
nodes_to_exclude: Sequence[str] | None = None,
extra_options: Mapping[str, Any] | None = None,
) -> QuantizationResult
Quantize weights to int8 without any calibration data.
Weights are quantized ahead of time; activation ranges are computed at inference. That makes this the zero-friction option — no dataset, no calibration pass — and it is usually the right first attempt for transformer and MLP-heavy models, where the win comes from the weights.
Convolutional vision models often prefer
:func:quantize_onnx_static: their cost is in activations, which this
path leaves in float.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
Model to quantize. |
required |
output_path
|
str | Path
|
Where to write the quantized model. |
required |
weight_type
|
QuantWeightTypeEnum
|
Target weight type. |
INT8
|
per_channel
|
bool
|
Quantize convolution weights per output channel instead of per tensor. Better accuracy, slightly larger, and not supported by every provider. |
False
|
reduce_range
|
bool
|
Use 7 bits instead of 8. Costs accuracy, but avoids the int8 overflow that pre-VNNI x86 CPUs are prone to. |
False
|
op_types
|
Sequence[str] | None
|
Restrict quantization to these operator types. Defaults to the runtime's own selection. |
None
|
nodes_to_exclude
|
Sequence[str] | None
|
Node names to leave in float — the standard escape hatch for the one layer that collapses under int8. |
None
|
extra_options
|
Mapping[str, Any] | None
|
Passed straight through to ONNX Runtime. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
QuantizationResult |
QuantizationResult
|
Output path plus the compression ratio. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
FileNotFoundError
|
When the input does not exist. |
ValueError
|
When the runtime lacks the requested weight type. |
Example:
>>> from tempest_fastapi_sdk.modelops import quantize_onnx_dynamic
>>> result = quantize_onnx_dynamic(
... "models/classify.onnx", "models/classify.int8.onnx"
... )
>>> result.compression_ratio
quantize_onnx_static
¶
quantize_onnx_static(
model_path: str | Path,
output_path: str | Path,
*,
calibration_inputs: Iterable[Mapping[str, Any]],
weight_type: QuantWeightTypeEnum = INT8,
activation_type: QuantWeightTypeEnum = INT8,
quant_format: QuantizationFormatEnum = QDQ,
calibrate_method: CalibrationMethodEnum = MINMAX,
per_channel: bool = False,
op_types: Sequence[str] | None = None,
nodes_to_exclude: Sequence[str] | None = None,
extra_options: Mapping[str, Any] | None = None,
) -> QuantizationResult
Quantize weights and activations using calibration samples.
A calibration pass runs the model over real inputs to learn the range each activation actually occupies, then bakes those ranges in. Both the weight and the activation path become integer, which is what unlocks the fused int8 kernels — the speedup is larger than dynamic quantization, and so is the accuracy risk.
The calibration data must look like production data. A few hundred samples drawn from the real distribution beat tens of thousands of synthetic ones; a range learned from noise will clip real activations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
Model to quantize. |
required |
output_path
|
str | Path
|
Where to write the quantized model. |
required |
calibration_inputs
|
Iterable[Mapping[str, Any]]
|
Feed dicts, one
per calibration batch, shaped exactly like the dicts you would
pass to |
required |
weight_type
|
QuantWeightTypeEnum
|
Target weight type. |
INT8
|
activation_type
|
QuantWeightTypeEnum
|
Target activation type.
|
INT8
|
quant_format
|
QuantizationFormatEnum
|
|
QDQ
|
calibrate_method
|
CalibrationMethodEnum
|
Range-selection algorithm.
Try |
MINMAX
|
per_channel
|
bool
|
Quantize convolution weights per output channel. |
False
|
op_types
|
Sequence[str] | None
|
Restrict quantization to these operator types. |
None
|
nodes_to_exclude
|
Sequence[str] | None
|
Node names to leave float. |
None
|
extra_options
|
Mapping[str, Any] | None
|
Passed straight through. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
QuantizationResult |
QuantizationResult
|
Output path, compression ratio, and a note with |
QuantizationResult
|
the number of calibration batches consumed. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
FileNotFoundError
|
When the input does not exist. |
ValueError
|
When no calibration samples were supplied. |
Example:
>>> import numpy as np
>>> from tempest_fastapi_sdk.modelops import quantize_onnx_static
>>> batches = [
... {"images": np.zeros((1, 3, 224, 224), dtype=np.float32)}
... ]
>>> result = quantize_onnx_static(
... "models/classify.onnx",
... "models/classify.qdq.onnx",
... calibration_inputs=batches,
... )
>>> result.notes
composite_scores
¶
composite_scores(
profiles: Sequence[BenchmarkProfile], *, weights: Mapping[str, float] | None = None
) -> tuple[list[float | None], dict[str, float]]
Score each profile on weighted, min-max-normalized cost. Lower wins.
Two renormalizations keep a missing measurement from distorting the ranking:
- A dimension that no profile measured is dropped entirely, and the remaining weights are rescaled to sum to 1. Benchmarking on a laptop with no GPU counter therefore compares latency, memory and size on their own terms instead of handing every model the same free 25%.
- A dimension that some profile is missing is skipped for that profile only, and its score is divided by the weight it could actually be scored on. A model with no energy figure is neither rewarded nor punished for it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profiles
|
Sequence[BenchmarkProfile]
|
Profiles to score. Scores are relative to this set — adding a model changes everyone's score. |
required |
weights
|
Mapping[str, float] | None
|
Dimension to weight. Defaults
to :data: |
None
|
Returns:
| Type | Description |
|---|---|
list[float | None]
|
tuple[list[float | None], dict[str, float]]: Scores in input order |
dict[str, float]
|
( |
tuple[list[float | None], dict[str, float]]
|
effective weights after dropping empty dimensions. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Example:
>>> from tempest_fastapi_sdk.modelops import composite_scores
>>> scores, effective = composite_scores(profiles)
>>> effective
pareto_points
¶
pareto_points(profiles: Sequence[BenchmarkProfile]) -> list[ParetoPoint]
Annotate every profile with Pareto-frontier membership.
With no quality set on any profile this degrades to the pure-cost
frontier, which is still useful — it tells you which models are simply
never worth running — but it cannot tell you which one is best, since
the cheapest model is by definition on it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profiles
|
Sequence[BenchmarkProfile]
|
Profiles to compare. |
required |
Returns:
| Type | Description |
|---|---|
list[ParetoPoint]
|
list[ParetoPoint]: One point per profile, in input order, with |
list[ParetoPoint]
|
|
Example:
>>> from tempest_fastapi_sdk.modelops import pareto_points
>>> [p.name for p in pareto_points(profiles) if p.is_pareto]
rank
¶
rank(
profiles: Sequence[BenchmarkProfile],
*,
weights: Mapping[str, float] | None = None,
quality: Mapping[str, float] | None = None,
) -> BenchmarkReport
Score, annotate and sort a set of measured profiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profiles
|
Sequence[BenchmarkProfile]
|
Profiles measured under the same conditions. Comparing runs from different machines or different repetition counts produces a ranking of the machines, not of the models. |
required |
weights
|
Mapping[str, float] | None
|
Composite-score weights.
Defaults to :data: |
None
|
quality
|
Mapping[str, float] | None
|
Model name to task quality, higher is better. Without it the Pareto frontier is cost-only. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BenchmarkReport |
BenchmarkReport
|
Profiles sorted by composite score ascending |
BenchmarkReport
|
(unscored last), Pareto annotation, effective weights and the host |
|
BenchmarkReport
|
description. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
Example:
>>> from tempest_fastapi_sdk.modelops import rank
>>> report = rank(profiles, quality={"yolov8n": 0.80})
>>> report.profiles[0].name
make_prediction_router
¶
make_prediction_router(
predictor: OnnxPredictor,
*,
source: RegistryModelSource | None = None,
monitor: PredictionMonitor | None = None,
metrics: PredictionMetrics | None = None,
prefix: str = "/api/predict",
tags: list[str] | None = None,
max_rows: int | None = DEFAULT_MAX_PREDICT_ROWS,
dependencies: Sequence[Depends] | None = None,
admin_dependencies: Sequence[Depends] | None = None,
expose_model_path: bool = False,
docs_locale: str | None = None,
) -> APIRouter
Build a router serving one predictor.
Endpoints:
POST {prefix}/— predict for a batch of rows.GET {prefix}/model— what is loaded, which providers are actually in use, and the thread configuration.POST {prefix}/model/sync— check the registry and reload if a newer version is current (only with asource).GET {prefix}/monitor— latency, input drift and prediction distribution (only with amonitor).
Inference and reload run in a worker thread (asyncio.to_thread):
both are blocking ONNX Runtime calls, and on the event loop a 1 s
inference would stall every other request for 1 s.
The router ships no authentication of its own. GET /model,
POST /model/sync and GET /monitor are operational — pass the
guard as admin_dependencies to protect them while POST / stays
as open as the rest of the service, or as dependencies to protect
every route.
Example:
>>> predictor = OnnxPredictor("dist/classifier.onnx")
>>> app.include_router(
... make_prediction_router(
... predictor,
... admin_dependencies=[Depends(require_operator)],
... ),
... )
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictor
|
OnnxPredictor
|
The loaded model. |
required |
source
|
RegistryModelSource | None
|
Registry-backed updates. Without it the sync endpoint is not mounted, since there would be nothing to sync against. |
None
|
monitor
|
PredictionMonitor | None
|
Records every request and serves the monitor endpoint. Without it the endpoint is not mounted. |
None
|
metrics
|
PredictionMetrics | None
|
Publishes the same numbers to
Prometheus. Independent of |
None
|
prefix
|
str
|
URL prefix. |
'/api/predict'
|
tags
|
list[str] | None
|
OpenAPI tags. |
None
|
max_rows
|
int | None
|
Rows one request may carry; more is a
|
DEFAULT_MAX_PREDICT_ROWS
|
dependencies
|
Sequence[Depends] | None
|
Dependencies run before
every route, e.g. |
None
|
admin_dependencies
|
Sequence[Depends] | None
|
Dependencies run
before the operational routes only — |
None
|
expose_model_path
|
bool
|
Report the model's absolute path in
|
False
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
edge_bundle
¶
edge_bundle(
estimator: SklearnEstimator,
samples: TabularInput,
output_dir: str | Path,
*,
name: str = "model",
dtype: TensorDtypeEnum = FLOAT32,
opset: int = DEFAULT_OPSET,
verify_samples: TabularInput | None = None,
tolerance: float = 0.0001,
optimize: bool = True,
quantize: bool = True,
to_ort: bool = True,
target_platform: str | None = None,
) -> EdgeBundle
Take a fitted estimator to a deployable edge artifact, in one call.
Runs export → verify → optimise → int8 quantise → .ort, reporting
the size after each stage so you can see what actually paid off.
Example:
>>> bundle = edge_bundle(model, X_train[:50], "dist/",
... verify_samples=X_test[:500])
>>> bundle.deployable, round(bundle.size_reduction, 2)
('dist/model.ort', 0.28)
Verification runs before the lossy stages, against the plain export. Quantisation changes the numbers by design, so a check that ran after it could not tell a conversion bug from expected int8 drift — and the conversion bug is the one you need to catch.
Expect most stages to be skipped or useless here, and that is the
honest result. Classic scikit-learn models convert to
ai.onnx.ml operators whose parameters live in node attributes, so
integer quantisation does not apply to them at all; and because these
graphs are kilobytes rather than megabytes, the optimiser and the
.ort conversion often add more metadata than they remove. The
deployable is therefore the smallest artifact produced, not the
last one — see :func:_smallest_artifact.
Where the edge win actually comes from for scikit-learn: the model is
already tiny, so what you gain is dropping Python, NumPy and
scikit-learn from the device and linking a minimal ONNX Runtime
build instead. On GPU edge, keep the .onnx and pick a provider
at load time (CUDAExecutionProvider,
TensorrtExecutionProvider). Either way, measure with
:func:~tempest_fastapi_sdk.modelops.benchmark_onnx rather than
assuming a stage helped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
SklearnEstimator
|
A fitted estimator or |
required |
samples
|
TabularInput
|
Rows used to shape the graph. |
required |
output_dir
|
str | Path
|
Where the artifacts go. |
required |
name
|
str
|
Base filename. |
'model'
|
dtype
|
TensorDtypeEnum
|
Input element type. |
FLOAT32
|
opset
|
int
|
Target opset. |
DEFAULT_OPSET
|
verify_samples
|
TabularInput | None
|
Held-out rows to verify against.
|
None
|
tolerance
|
float
|
Numeric tolerance for verification. |
0.0001
|
optimize
|
bool
|
Run the graph optimiser. |
True
|
quantize
|
bool
|
Produce an int8 dynamic-quantised graph. |
True
|
to_ort
|
bool
|
Convert to the |
True
|
target_platform
|
str | None
|
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
EdgeBundle |
EdgeBundle
|
Every stage, the verification, and which artifact to |
EdgeBundle
|
ship. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When a required extra is missing. |
ValueError
|
When conversion fails or the samples are malformed. |
export_sklearn_to_onnx
¶
export_sklearn_to_onnx(
estimator: SklearnEstimator,
samples: TabularInput,
output_path: str | Path,
*,
dtype: TensorDtypeEnum = FLOAT32,
opset: int = DEFAULT_OPSET,
zipmap: bool = False,
input_name: str = "input",
options: dict[Any, Any] | None = None,
) -> SklearnExport
Convert a fitted estimator or Pipeline to ONNX.
Example:
>>> model = RandomForestClassifier().fit(X_train, y_train)
>>> export = export_sklearn_to_onnx(model, X_train[:10], "model.onnx")
>>> export.n_features, export.zipmap
(4, False)
samples are only used to derive the input shape and type — a
handful of rows is enough — but they must have the same number of
features the model was fitted on.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
SklearnEstimator
|
A fitted scikit-learn estimator or
|
required |
samples
|
TabularInput
|
Representative input rows (array, DataFrame or nested sequence). |
required |
output_path
|
str | Path
|
Where to write the |
required |
dtype
|
TensorDtypeEnum
|
Input element type. |
FLOAT32
|
opset
|
int
|
Target ONNX opset. See :data: |
DEFAULT_OPSET
|
zipmap
|
bool
|
Keep scikit-learn's ZipMap output wrapper. |
False
|
input_name
|
str
|
Name for the graph input. |
'input'
|
options
|
dict[Any, Any] | None
|
Extra |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
SklearnExport |
SklearnExport
|
Where it landed and what shape it expects. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When |
uses_ml_domain
¶
Return whether the graph uses ai.onnx.ml operators.
Most scikit-learn estimators convert to that domain —
TreeEnsembleClassifier for forests and boosting,
LinearClassifier for logistic regression, SVMClassifier, and
the scalers. Those operators hold their parameters as node attributes
rather than as weight tensors, so integer quantisation does not
apply to them: there is no matrix to requantise, and the ONNX
Runtime quantiser refuses with Failed to find proper ai.onnx
domain.
Knowing this up front turns a confusing failure into a skipped stage with a reason.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
onnx_path
|
str | Path
|
The graph to inspect. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
Whether any |
bool
|
when onnx is unavailable, since guessing would be worse than |
|
bool
|
letting the quantiser speak for itself. |
verify_sklearn_onnx
¶
verify_sklearn_onnx(
estimator: SklearnEstimator,
onnx_path: str | Path,
samples: TabularInput,
*,
dtype: TensorDtypeEnum = FLOAT32,
tolerance: float = 0.0001,
providers: Sequence[str] | None = None,
) -> ExportVerification
Check the exported graph still predicts what the estimator does.
Example:
>>> check = verify_sklearn_onnx(model, "model.onnx", X_test[:200])
>>> check.passed, check.label_agreement
(True, 1.0)
For a classifier, label agreement is the headline: a probability that drifts by 1e-6 is fine, a sample that flips class is not, and averaging the two into one number would hide the second behind the first. For a regressor the maximum absolute difference is what matters.
Run this on held-out data, not on the rows you exported with. The export samples only shaped the graph; they are not a test set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
SklearnEstimator
|
The original fitted estimator. |
required |
onnx_path
|
str | Path
|
The exported graph. |
required |
samples
|
TabularInput
|
Rows to compare on. |
required |
dtype
|
TensorDtypeEnum
|
The dtype the graph was exported with. |
FLOAT32
|
tolerance
|
float
|
Maximum absolute difference tolerated for a regressor, and for classifier probabilities. |
0.0001
|
providers
|
Sequence[str] | None
|
ONNX Runtime execution
providers. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ExportVerification |
ExportVerification
|
Whether it passed and by how much it differed. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When onnxruntime is unavailable. |
ValueError
|
When the samples are not 2-D. |
analyze_model
¶
analyze_model(model_path: str | Path, *, name: str | None = None) -> StaticModelMetrics
Analyze a model file, picking the reader from its suffix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
Path to a |
required |
name
|
str | None
|
Display name. Defaults to the file stem. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StaticModelMetrics |
StaticModelMetrics
|
Whatever the matching reader could collect. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the suffix is neither |
Example:
>>> from tempest_fastapi_sdk.modelops import analyze_model
>>> analyze_model("models/classify.ort").format
analyze_onnx
¶
analyze_onnx(model_path: str | Path, *, name: str | None = None) -> StaticModelMetrics
Read parameter count, opset, size and shapes out of an ONNX graph.
Parameters are summed from the initializer dimensions rather than from the tensor data, so a multi-gigabyte model is inspected without loading a single weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
Path to the |
required |
name
|
str | None
|
Display name. Defaults to the file stem. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StaticModelMetrics |
StaticModelMetrics
|
Populated metrics with |
StaticModelMetrics
|
— an ONNX graph carries no cheap FLOP count. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
FileNotFoundError
|
When |
Example:
>>> from tempest_fastapi_sdk.modelops import analyze_onnx
>>> metrics = analyze_onnx("models/classify.onnx")
>>> metrics.n_parameters, metrics.disk_size_mb
analyze_ort
¶
analyze_ort(
model_path: str | Path,
*,
name: str | None = None,
providers: list[str] | None = None,
) -> StaticModelMetrics
Read size and tensor shapes out of an .ort file.
The ORT format is the graph already optimized and serialized for the
minimal runtime; it does not keep the initializer table in a form the
Python API exposes, so n_parameters stays 0. Analyze the source
.onnx with :func:analyze_onnx when the parameter count matters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str | Path
|
Path to the |
required |
name
|
str | None
|
Display name. Defaults to the file stem. |
None
|
providers
|
list[str] | None
|
Execution providers to open the
session with. Defaults to :func: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StaticModelMetrics |
StaticModelMetrics
|
Size plus declared inputs and outputs. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
FileNotFoundError
|
When |
analyze_torch
¶
analyze_torch(
module: Module,
*,
name: str | None = None,
path: str | Path | None = None,
example_input: TorchExampleInput | None = None,
) -> StaticModelMetrics
Count parameters and (optionally) FLOPs of a live nn.Module.
FLOPs are counted with torch.utils.flop_counter.FlopCounterMode,
which runs one forward pass under a dispatch mode. Two consequences
worth knowing before you quote the number:
- It counts a multiply-accumulate as two FLOPs. Papers that report
"GFLOPs" from
thopor Ultralytics usually report MACs, i.e. half this figure. Say which convention you used. - It executes the model, so pass an
example_inputshaped like real input and expect it to cost one forward pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
The |
required |
name
|
str | None
|
Display name. Defaults to the class name. |
None
|
path
|
str | Path | None
|
Checkpoint path, when the module came from one, so the report can carry its on-disk size. |
None
|
example_input
|
TorchExampleInput | None
|
A tensor (or tuple of tensors) to run through the module for the FLOP count. Omit to skip counting. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
StaticModelMetrics |
StaticModelMetrics
|
Parameter counts, size and — when |
StaticModelMetrics
|
|
|
StaticModelMetrics
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When torch is not installed. |
Example:
>>> import torch
>>> from tempest_fastapi_sdk.modelops import analyze_torch
>>> model = torch.nn.Linear(128, 10)
>>> metrics = analyze_torch(
... model, example_input=torch.randn(1, 128)
... )
>>> metrics.n_parameters
1290
default_providers
¶
default_providers(onnxruntime: SupportsAvailableProviders) -> list[str]
Return the local execution providers, in priority order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
onnxruntime
|
SupportsAvailableProviders
|
The imported |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Available providers minus the remote ones. |