The official SnoozeML Python SDK (snoozeml, located under python/) provides a high-performance, developer-friendly interface to the SnoozeML inference daemon. It bridges machine learning workflows (PyTorch, scikit-learn, XGBoost, Hugging Face) with SnoozeML’s scale-to-zero memory reclamation, dynamic micro-batching, and dual HTTP/gRPC transports.
# High-performance native gRPC transport + NumPy array support
pipinstall"snoozeml[grpc]"
# Model conversion toolkit (Scikit-Learn, ONNX, and XGBoost)
pipinstall"snoozeml[converters]"
# Complete toolkit (client, gRPC, custom worker, and all converters)
pipinstall"snoozeml[full]"
Dependency Profiles & Extras
SnoozeML provides modular optional dependencies (extras) so your client applications and container images remain lean and avoid bloated dependencies:
Extra
Command
Included Packages
Purpose & Technical Details
Base
pip install snoozeml
requests>=2.28.0
Ultra-lightweight HTTP REST client for model lifecycle management (load, unload, pin, unpin), status polling, health probes, Prometheus metrics, and basic inference. Pure Python with zero compiled binary dependencies or C-extensions.
[grpc]
pip install "snoozeml[grpc]"
grpcio, grpcio-health-checking, protobuf, numpy
High-throughput, low-latency binary gRPC transport with compiled protobuf stubs, health checking, and automatic NumPy ndarray marshaling to raw little-endian bytes.
All-in-one distribution bundle combining [grpc], [worker], and [converters] with zero GPU/CUDA bloat.
[onnx]
pip install "snoozeml[onnx]"
numpy, scikit-learn, onnx, skl2onnx
Scikit-learn estimator and pipeline export (export_sklearn, deploy_sklearn) to ONNX runtime format.
[xgboost]
pip install "snoozeml[xgboost]"
numpy, xgboost-cpu (Linux) / xgboost (macOS/Win)
XGBoost model export to .xgb.json for pure-Rust hessboost tree execution. Dynamically resolves to xgboost-cpu on Linux via PEP 508 environment markers to prevent dragging heavy nvidia-nccl / CUDA packages into CPU environments.
[torch]
pip install "snoozeml[torch]"
torch>=2.0.0
PyTorch nn.Module export to ONNX (export_torch, deploy_torch). Note: If PyTorch is already present in your environment, snoozeml automatically duck-types PyTorch tensors without requiring this extra.
[worker]
pip install "snoozeml[worker]"
numpy>=1.24.0
Minimal runtime dependency profile for process-isolated custom Python worker models (snooze_model.py) using NumPy tensor format.
[!TIP]
You can pass use_grpc=True globally on the client, or override it on individual inference calls: client.infer("model_id", inputs, use_grpc=False). Lifecycle methods (client.models.*, client.upload_model) always use HTTP REST.
Asynchronous Client (AsyncSnoozeClient)
For high-concurrency event loops, web frameworks (FastAPI, Quart), or concurrent micro-batching:
import asyncio
import numpy as np
from snoozeml import AsyncSnoozeClient
asyncdefrun_concurrent_requests():
asyncwithAsyncSnoozeClient("http://localhost:8080",grpc_endpoint="localhost:50051",use_grpc=True) as client:
# Launch 10 concurrent inference requests
# SnoozeML's dynamic batcher will coalesce these into a single Axis(0) forward pass!
When scoring large offline datasets or processing bulk feature sets (e.g., 50,000 rows), sending the entire batch in a single HTTP request can trigger payload limits, network timeouts, or out-of-memory errors on GPU backends. Conversely, sending rows one-by-one incurs severe network latency.
The infer_dataset() method automatically chunks your inputs along Axis(0) into optimal batch sizes, dispatches requests sequentially, and concatenates all responses into a single seamless InferenceResponse:
[!NOTE]
infer_dataset() handles multiple input bindings simultaneously, slicing every tensor in inputs along Axis(0) proportionally.
5. Scale-to-Zero Resilience & Automatic Retries
SnoozeML’s signature architectural feature is Scale-to-Zero Memory Reclamation. Idle models are automatically evicted from GPU VRAM or host RAM after a configurable timeout (idle_timeout_secs).
The Scale-to-Zero Lifecycle
[Request Arrives]
│
├──> Model Ready in RAM/VRAM ──> Instant Forward Pass
When an inference request hits an unloaded model, SnoozeML triggers asynchronous weight loading and responds with HTTP status 503 Service Unavailable (InferenceError::Loading) accompanied by a Retry-After: 5 header. Similarly, if GPU memory is saturated, an LRU deallocation occurs (ResourceExhausted).
Built-in Exponential Retry Engine
The Python SDK handles transient loading states transparently:
from snoozeml import SnoozeClient
# Initialize client with automatic retry capabilities
client =SnoozeClient(
"http://localhost:8080",
max_retries=4,# Retry up to 4 times
retry_backoff=0.5,# Base delay in seconds (0.5s, 1.0s, 2.0s, ...)
)
# If 'bert_embeddings' is sleeping on disk, the client automatically waits and retries!
print(f" Is Loaded: {m.is_loaded}") # True if resident in RAM/VRAM
print(f" Pinned: {m.pinned}") # True if exempt from scale-to-zero
print(f" Last accessed: {m.last_accessed_secs_ago}s ago")
# 2. Inspect single model metadata
info = client.models.get("iris_classifier")
print(f"Format: {info.format}, Max Batch Size: {info.max_batch_size}")
# 3. Pin a critical model in memory
# Pinned models are eagerly loaded and NEVER unloaded by the scale-to-zero sweeper
client.models.pin("iris_classifier")
# 4. Unpin a model to restore normal scale-to-zero sweeping
client.models.unpin("iris_classifier")
# 5. Explicitly evict/unload weights immediately to free VRAM for other workloads
client.models.evict("iris_classifier")
# 6. Dynamically refresh the models directory on disk without restarting the daemon
refreshed_list = client.refresh_models()
print(f"Refreshed {len(refreshed_list)} models from disk.")
7. One-Step Model Deployment & Framework Helpers
Deploying trained models to an inference server traditionally requires manual ONNX export, writing configuration files, creating directories, and uploading files. SnoozeML reduces this to a single Python call.
One-Step Scikit-Learn Deployment
import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
[!NOTE]
PyTorch model export and tensor conversion only require the lightweight CPU wheel. To avoid downloading ~2.5 GB of unused CUDA packages on Linux, install PyTorch via its official CPU index:
For models that require proprietary Python preprocessing, PyTorch generative logic, Hugging Face pipelines, or libraries like Amazon Chronos-Bolt, SnoozeML supports Process-Isolated Python Workers.
flowchart LR
Daemon["SnoozeML Daemon (Rust)"]
IPC["Binary IPC Stream (Stdin/Stdout)"]
Worker["Child Process (snoozeml.worker)"]
PyModel["User Model (snooze_model.py)"]
Daemon <-->|Magic 0x534E5A31 + FP32 Bytes| IPC
IPC <--> Worker
Worker <--> PyModel
Scaffolding a Worker Directory
Use scaffold_worker() to generate a production-ready worker directory:
from snoozeml import scaffold_worker
# Generates models/custom_forecaster/snooze_model.py and snooze_model.json
# and performs a verification smoke test in an isolated child process
scaffold_worker(
target_dir="models/custom_forecaster",
tensor_format="numpy",# "numpy" or "raw"
verify=True,# Run smoke-test verification before returning
)
Implementing Your Custom Worker (snooze_model.py)
Every worker directory contains snooze_model.py implementing load() and predict():
You can configure models, scale-to-zero parameters, RBAC keys, and streaming bindings programmatically, and even launch the SnoozeML daemon as a Python context manager.
Fluent Configuration Builder (SnoozeConfig)
from snoozeml import SnoozeConfig, GlobalDefaultsConfig
# When exiting the with block, the daemon process is gracefully stopped!
11. Event Streaming Pipelines
SnoozeML includes a high-throughput event streaming engine supporting Apache Kafka, RabbitMQ, Redis Streams, and Mock streams. The Python SDK provides envelope builders and clients for these streams.
Streaming Request & Response Envelopes
from snoozeml import StreamInferRequest, StreamWireFormat
# 1. Create a streaming inference request envelope
request =StreamInferRequest(
model_id="fraud_detector",
inputs={"features": [[0.5, 1.2, -0.4, 3.1]]},
request_id="req-tx-9921",
client_timeout_ms=500,
)
# 2. Serialize to JSON wire format
json_payload = request.to_json()
# 3. Or serialize to Protobuf binary bytes
proto_bytes = request.to_protobuf()
Testing Pipelines Locally with MockStreamClient
Test your end-to-end event streaming pipeline without running Kafka or RabbitMQ clusters:
from snoozeml import SnoozeClient, MockStreamClient
SnoozeML exposes Prometheus metrics at GET /metrics. The Python SDK includes a lock-free metrics parser (parse_prometheus_metrics) that converts exposition text into a structured DaemonMetrics object.
# Option B: Single-line JSON output for Datadog, Loki, or CloudWatch
configure_logging(level="DEBUG",format_json=True)
Automatic Credential Scrubbing
snoozeml.logging attaches a RedactingFilter to all loggers. Any API key, JWT Bearer token, or private header passed to SnoozeClient or logged in payloads is automatically masked: