The Training Duo: DeepSpeed & PyTorch with ONNX | ML Engineering & MLOps
Hi All
Deep learning models often demand significant computational resources, making training slow and memory intensive. PyTorch, a popular deep learning framework, provides flexibility but requires manual optimization for large scale training.
Enter DeepSpeed, a library designed to accelerate training by automating mixed precision, gradient accumulation, and memory optimization techniques like ZeRO (Zero Redundancy Optimizer).
In this post, we'll walk though a simple PyTorch model enhanced with DeepSpeed, demonstrating how it can dramatically improve training efficiency with minimal code changes, then running inference on ONNX runtime. Whether you're working with a single GPU or scaling to multi-GPU setups, DeepSpeed simplifies the process while maximizing performance.
Full training.py source and architecture below:
Let's breakdown the above code, block by block.
1. Simple Neural Network (`Simple Model` class)
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
import deepspeed
# 1. Define a simple model
class SimpleModel(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(10, 5)
self.fc1 = nn.Linear(5, 1)
def forward(self, x)
x = torch.relu(self.fci(x))
return self.fc2(x)
A simple feedforward neural network with:
* One hidden layer (fc1) with 5 neurons and ReLU activation
* One output layer (fc2) with a single neuron (regression task)
* Input/Output: Takes 10-dimentional input, outputs a scalar.
2. Data Preparation
X = torch.randn(1000, 10) # 1000 samples, 10 features
y = torch.randn(1000, 1) # 1000 targets
dataset = TensorDataset(X, y)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
* Dummy Data: Random tensors for 1000 samples.
* DataLoader: Batches of 32 samples, shuffled for training.
3. DeepSpeed Initialization
model = SimpleModel()
parameters = filter(lambda p: p.requires_grad, model.parameters())
model_engine, optimizer, _, _ = deepspeed.initialize(
model=model,
model_parameters=parameters,
config_params={
"train_batch_size": 32,
"gradient_accumulation_steps": 2, # Simulates batch_size=64
"fp16": {"enabled": True}, # Mixed precision (FP16)
"zero_optimization": {"stage": 1} # ZeRO-1 (optimizer sharding)
}
)
DeepSpeed Features:
* Mixed Precision (fp16): Speeds up training by using 16-bit floats.
* Gradient Accumulation: Simulates larger batches (effective batch size = 64)
* ZeRO Stage 1: Shards optimizer states across GPUs to reduce memory usage.
4. Training Loop
Steps:
for epoch in range(5):
for batch_X, batch_y in dataloader:
outputs = model_engine(batch_X) # Forward pass
loss = nn.MSELoss()(outputs, batch_y) # MSE loss
model_engine.backward(loss) # Backward pass
model_engine.step() # Update weights
print(f"Epoch {epoch+1}, Loss: {loss.item():.4f}")
* Forward Pass: Computer predictions.
* Loss Calculation: Mean Squared Error (MSE) for regression
* Backward Pass: Compute gradients (handled by Deepspeed)
* Optimization: Update weights (ZeRO sharding reduces memory overhead)
Full ONNX server.py code and breakdown below:
import onnxruntime as ort
import numpy as np
# Initialize ONNX Runtime session
sess = ort.InferenceSession(
"model.onnx",
providers=["CPUExecutionProvider"] # Use "CudaExecutionProvider" for GPU
)
# Example inference
input_data = np.random.randn(1, 10).astype(np.float32) # Match input shape
outputs = sess.run(
["output"], # Output names (must match ONNX export)
{"input": input_data} # Input dict (keys = input names)
)
print("ONNX Output: ", outputs[0])
1. ONNX Imports
import onnxruntime as ort
import numpy as np
* onnxruntime (ort): A library for running ONNX (Open Neural Network Exchange) models. It provides APIs to load and execute models.
* numpy (np): A library for numerical operations, used here to create input data.
2. Initialize ONNX Runtime Session
sess = ort.InferenceSession(
"model.onnx",
providers=["CPUExecutionProvider"] # Use "CudaExecutionProvider" for GPU
)
* ort.InferenceSession: Loads the ONNX model (model.onnx) for inference.
providers
* CPUExecutionProvider: Runs inference on the CPU (default)
* CudaExecutionProvider: Runs inference on an NVIDIA GPU (requires CUDA/cuDNN installed).
* The session is stored in the variable sess.
3. Prepare Input Data
input_data = np.random.randn(1, 10).astype(np.float32) # Match input shape
* np.random.randn(1, 10): generates random data with shape (1, 10) (1 sample, 10 features).
* .astype(np.float32): Ensures the data is in float32 format (common for ONNX models).
4. Run Inference
outputs = sess.run(
["output"], # Output names (must match ONNX export)
{"input": input_data} # Input dict (keys = input names)
)
sess.run: Executes the model with the given inputs.
* First argument (["output"]): List of output names (must match the names defined in the ONNX model)
* Second argument({"input": input_data})
* The outputs are stored in the variable outputs
5. Print Output
print("ONNX Output: ", outputs[0])
* Prints the first output (assuming the model has a single output named "output")
ONNX Notes
* Input/Outputnames: The names (input and output) must match those defined in the ONNX model. If unsure, inspect the model using:
print("Inputs:", [input.name for input in sess.get_inputs()])
print("Outputs:", [output.name for output in sess.get_outputs()])
* Shape/Type Matching: The input shape (1, 10) and data type (float32) must match the model's expected input.
* GPU Support: Replace CPUExecutionProvider with CudaExecutionProvider for GPU acceleration (requires CUDA setup).
Final Notes
DeepSpeed transforms the way we train PyTorch handling the heavy lifting behind the scenes - mixed precision, gradient sharding and memory optimization - so you don't have to.
As shown in this example, integrating DeepSpeed into your workflow requires just a few lines of configuration, unlocking significant, unlocking significant speedups and scalability. Whether you're experimenting with small models or pushing the limits of large scale training. Please find the full source code with a Docker config here.
Later
- Ed (@lightspeed001)

.png)
.png)
.png)
Comments
Post a Comment