Deep Learning and GPU
GPU Acceleration (Optional)
conformalpy supports optional GPU acceleration using CuPy for large-scale applications where performance is critical.
Installation
CuPy is an optional dependency:
# Install conformalpy with GPU support
pip install conformalpy[gpu]
# Or install CuPy directly for your CUDA version
pip install cupy-cuda12x # CUDA 12.x
pip install cupy-cuda11x # CUDA 11.xCheck GPU Availability
from conformalpy.backends import is_gpu_available, get_device_info
# Check if GPU is available
if is_gpu_available():
print("GPU acceleration available!")
# Get detailed device info
info = get_device_info()
print(f"GPU: {info['gpu_name']}")
print(f"Memory: {info['gpu_memory'] / 1e9:.1f} GB")Backend Configuration
Configure the compute backend globally:
from conformalpy.backends import set_backend, get_backend
# Force CPU (useful for testing)
set_backend("cpu")
# Force GPU (raises error if unavailable)
set_backend("gpu")
# Auto-detect (default): uses GPU if available
set_backend("auto")
# Check current backend
print(get_backend())Using the Array Module
The array module provides a unified interface for NumPy/CuPy:
from conformalpy.backends import get_array_module, to_numpy
# Get the appropriate module (numpy or cupy)
xp = get_array_module()
# Create arrays using the selected backend
arr = xp.array([1.0, 2.0, 3.0])
# Perform operations
result = xp.sum(arr)
# Convert back to NumPy (always works)
np_arr = to_numpy(arr)GPU Accelerator
For optimized conformal prediction operations:
from conformalpy.backends.array_backend import GPUAccelerator
# Initialize (falls back to CPU if no GPU)
accel = GPUAccelerator(use_gpu=True)
# Compute LAC scores
scores = accel.compute_lac_scores(y_true, probas)
# Compute quantile
qhat = accel.compute_quantile(scores, alpha=0.1)
# Generate prediction sets
pred_sets = accel.predict_sets_batch(probas_test, qhat)When to Use GPU
GPU acceleration helps with:
- Large calibration sets (>10,000 samples)
- Large batch predictions
- Repeated operations (hyperparameter tuning)
- Real-time applications
CPU is sufficient for:
- Small to medium datasets (<10,000 samples)
- One-time calibration and prediction
- Development and prototyping
For most use cases, the standard NumPy-based implementation is fast enough. Consider GPU for production systems with high throughput requirements.
See the GPU acceleration example for performance benchmarks.
Deep Learning Integration (Optional)
conformalpy supports PyTorch and Keras/TensorFlow models through wrapper classes that adapt them to the sklearn-like interface.
Installation
PyTorch and Keras are optional dependencies:
# PyTorch support
pip install conformalpy[torch]
# or: pip install torch
# Keras/TensorFlow support
pip install conformalpy[keras]
# or: pip install tensorflow
# Both
pip install conformalpy[deep-learning]Check Availability
from conformalpy.deep_learning import is_torch_available, is_keras_available
print(f"PyTorch available: {is_torch_available()}")
print(f"Keras available: {is_keras_available()}")PyTorch Wrappers
For PyTorch models, use TorchClassifierWrapper or TorchRegressorWrapper:
import torch
import torch.nn as nn
from conformalpy.deep_learning import TorchClassifierWrapper
from conformalpy.classifier import ConformalClassifier
from conformalpy.nonconformity.classification import lac_nonconformity
# Define your PyTorch model
class Classifier(nn.Module):
def __init__(self, n_features, n_classes):
super().__init__()
self.fc1 = nn.Linear(n_features, 64)
self.fc2 = nn.Linear(64, n_classes)
def forward(self, x):
x = torch.relu(self.fc1(x))
return self.fc2(x)
# Create and train model
model = Classifier(20, 3)
# ... train the model ...
model.eval()
# Wrap for conformal prediction
wrapped = TorchClassifierWrapper(
model,
output_activation="softmax", # Apply softmax to outputs
device="cuda", # Use GPU if available
batch_size=256, # Batch size for inference
)
# Use with ConformalClassifier
cc = ConformalClassifier(
model=wrapped,
alpha=0.1,
nonconformity_function=lac_nonconformity,
)
cc.calibrate(X_calib, y_calib)
pred_sets = cc.predict(X_test)For regression:
from conformalpy.deep_learning import TorchRegressorWrapper
from conformalpy.regressor import ConformalRegressor
wrapped = TorchRegressorWrapper(
pytorch_regressor,
device="cuda",
batch_size=256,
)
cr = ConformalRegressor(model=wrapped, alpha=0.1)
cr.calibrate(X_calib, y_calib)
intervals = cr.predict_interval(X_test)Keras Wrappers
For Keras/TensorFlow models, use KerasClassifierWrapper or KerasRegressorWrapper:
from keras.models import Sequential
from keras.layers import Dense
from conformalpy.deep_learning import KerasClassifierWrapper
from conformalpy.classifier import ConformalClassifier
# Build Keras model
keras_model = Sequential([
Dense(64, activation='relu', input_shape=(20,)),
Dense(32, activation='relu'),
Dense(3, activation='softmax'),
])
keras_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
# keras_model.fit(X_train, y_train, epochs=50)
# Wrap for conformal prediction
wrapped = KerasClassifierWrapper(
keras_model,
batch_size=256,
output_activation="auto", # Auto-detect from final layer
)
# Use with ConformalClassifier
cc = ConformalClassifier(model=wrapped, alpha=0.1)
cc.calibrate(X_calib, y_calib)
pred_sets = cc.predict(X_test)Output Activation Options
The wrappers handle different model output formats:
| Setting | Behavior | Use When |
|---|---|---|
| “auto” | Detect from model architecture | Default choice |
| “softmax” | Apply softmax (classification) | Logits output |
| “sigmoid” | Apply sigmoid (binary) | Binary logits |
| “none” | No transformation | Already probabilities |
Key Features
Lazy Loading: PyTorch and Keras are only imported when you use the corresponding wrapper, not when importing conformalpy.
import conformalpy # Does NOT require PyTorch/Keras
# Only imports PyTorch when you need it
from conformalpy.deep_learning import TorchClassifierWrappersklearn Compatibility: Wrappers implement __sklearn_is_fitted__ to pass sklearn’s fitted checks.
Batch Processing: Both wrappers support configurable batch_size for efficient inference on large datasets.
Device Management: PyTorch wrapper supports GPU acceleration via the device parameter.
When to Use Wrappers
Use wrappers when:
- You have a trained deep learning model
- You want conformal prediction guarantees
- You need the sklearn-like interface
No wrapper needed if:
- Your model already has
predict_probamethod - You’re using sklearn-compatible deep learning (e.g., skorch, scikeras)
See the deep learning example for a complete deep learning workflow.