Inference: Build an ML Runtime with Rust and K3s | ML Engineering & MLOps
Hi All
Machine learning (ML) runtimes are the backbone of executing trained models in production, but understanding their inner workings can be daunting for beginners. In this post, we’ll build a ML Runtime in Rust from scratch and deploy it on Kubernetes—a minimal yet functional system that loads, executes, and manages simple ML models.
By focusing on core concepts like model serialization, inference, and basic error handling, we’ll demystify how ML runtimes operate under the hood. This is a hands-on guide for developers who want to bridge the gap between high-level ML frameworks and low-level system design.
View the architecture of the ML runtime below, source code available here:
Components Explained:
1. Rust Application (main.rs)
* Entry point of the program
* Uses tch-rs (PyTorch bindings) for ML operations
* Contains the model definition and inference logic
2. PyTorch Model (model.pt)
* Pre-trained model loaded at runtime
* Simple linear layer with ReLU activation (as in the minimal example)
3. Random Input Tensor:
* Synthetic data generated for demonstration.
* Shape: [1, 10] (batch size 1, 10 features)
* Created using Tensor::randn()
4. Inference:
* Forward pass through the model
* Output shape: [1, 5]
* Performed via model.forward(&input_tensor)
5. Result:
* Prints tensor shapes and values to console
* Uses println! for output
The full runtime source below, available here:
Let's break down the above code, block by block.
1. Imports
use tch::{nn, Device, Tensor, Kind};
* tch: The Rust bindings for PyTorch (Torch C++ backend)
* nn: Module for defining neural network layers.
* Device: Represents computation device (CPU/CUDA)
* Tensor: Core tensor type for numerical operations.
* Kind: Enum for tensor data types (eg. Float, Int)
2. Main Function
fn main() -> Result<(), Box< dyn std::error::Error >>{
* `main`: Entry point of the program.
* `Result<(), Box<dyn std::error::Error>>`:
* Returns `Ok(())` on success or a boxed error on failure.
* `Box<dyn std::error::Error>` allows any error type to returned.
3. Device Setup
let device = Device::cuda_if_available();
* Device::cuda_if_available():
* Automatically selects CUDA (GPU) if available, otherwise falls back to CPU
* GPU acceleration is critical for ML workloads.
4. Model Definition
let vs = nn::VarStore::new(device);
let model = nn::seq()
.add(nn::linear(&vs.root(), 10, 5, Default::default()))
.add_fn(|x| x.relu());
* nn::VarStore:
* Stores model parameters (weights/biases)
* Initialized for the selected device. * nn::seq()
* Creates a sequential neural network model.
* nn::Linear(&vs.root(, 10, 5, ...)):
* Adds a linear (fully connected) layer:
* Input size: 10
* Output size: 5
* Default initialization (weights sampled from a normal distribution).
* .add_fn(|x| x.relu()):
* Adds a ReLU activation function(non-linearity).
5. Model Loading (Commented Out)
// vs.load("model.pt")?;
* vs.load("model.pt")
* Loads a pre-trained model from a file (model.pt).
* In practice, you'd uncomment this and replace model.pt with the actual model path.
* The ? propagates errors (eg. file not found).
6. Input Tensor Creation
let input = Tensor::randn(&[1, 10], (Kind::Float, device));
* Tensor::randn(&[1, 10], ...):
* Creates a random tensor with shape [1, 10] (batch size 1, 10 features)
* Data type: Kind::Float (32-bit floating point).
* Device: Same as device (CPU/CUDA)
7. Inference
let output = model.forward(&input);
* model.forward(&input):
* Performs a forward pass through the model.
* Input tensor is passed through the linear layer and ReLU activation.
* Output shape: [1, 5] (batch size 1, 5 features).
8. Output Logging
println!("Input shape: {:?}", input.size()); println!("Output shape: {:?}", output.size()); println!("Output values: {:?}", output);
* input.size()/output.size():
* Returns tensor shapes as vectors (eg. [1, 10])
* output
* Prints the actual values of the output tensor.
9. Error Handling
Ok(())
* The main function returns Ok(()) to indicate success
* Errors (eg. file, loading, tensor operations) are propagated via ?.
Key Takeaways
1. Device Awareness: Automatically uses GPU if available.
2. Model Definition: Simple sequential model with one linear layer and ReLU.
3. Tensor Operations: Random input generation and inference.
4. Error Handling: Minimal but functional (propagates errors up the call stack).
Kubernetes Deployment (k3s)
Deployment Architecture:
Key components in the architecture:
1. k3s Cluster:
* Single control plane with embedded etcd.
* API server, controller manager and scheduler
* ML Runtime deployment with multiple replicas
* Each pod contains your ML runtime container.
2. Runtime Pods:
* Mount the model file (model.pt) as a volume
* Use ConfigMap for logging configuration
* Use Secret for any sensitive model-related credentials
3. Storage:
* Longhorn provides persistent storage for the model file
* Model file is shared across all runtime pods.
4. Monitoring:
* Prometheus collects metrics metrics from the runtime.
* Grafana for visualization
* Loki for log aggregation
5. Scaling:
* Horizontal Pod Autoscaler (HPA) can be configured based on CPU/memory usage.
* Cluster Autoscaler can add more nodes if needed
This architecture provides:
* High availability through multiple replicas.
* Persistent storage for the model file.
* Configurable logging
* Monitoring capabilities
* Scalability options
This Minimal ML Runtime demonstrates the foundational principles of executing ML models in a controlled environment. While it lacks advanced features like GPU acceleration or distributed computing, it serves as a stepping stone for understanding more complex systems. Full source code available here.
In the next post, we’ll scale this prototype into a Production-Grade ML Runtime, incorporating robustness, performance optimizations, and real-world deployment considerations. Stay tuned!
Later
- Ed

.png)
.png)
Comments
Post a Comment