GPU Acceleration with CuPy

This example demonstrates how to use optional GPU acceleration for conformal prediction operations.

Key features:

Note: GPU acceleration requires CuPy, which is an optional dependency. Install with: pip install conformalpy[gpu] or pip install cupy-cuda12x (for CUDA 12.x). If no GPU is available, all operations fall back to NumPy.

Installation:

pip install conformalpy[gpu]
# or manually:
pip install cupy-cuda12x  # For CUDA 12.x
pip install cupy-cuda11x  # For CUDA 11.x

Check GPU Availability

First, let’s check if a GPU is available.

Code
import time

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

from conformalpy.backends import (
    get_array_module,
    get_backend,
    get_device_info,
    is_gpu_available,
    set_backend,
    to_numpy,
)
from conformalpy.backends.array_backend import GPUAccelerator
from conformalpy.classifier import ConformalClassifier
from conformalpy.nonconformity.classification import lac_nonconformity

print("=== Device Information ===")
info = get_device_info()

print(f"CuPy installed: {info['cupy_installed']}")
print(f"GPU available: {info['gpu_available']}")
print(f"Number of GPUs: {info['n_gpus']}")

if info["gpu_available"]:
    print(f"GPU name: {info['gpu_name']}")
    print(f"GPU memory: {info['gpu_memory'] / 1e9:.1f} GB")
    print(f"CUDA version: {info['cuda_version']}")
else:
    print("\nNo GPU detected. Examples will run on CPU.")
    print("To use GPU, install CuPy: pip install cupy-cuda12x")

Backend Configuration

You can configure the backend globally or use it explicitly.

Code
# Check current backend
print(f"\nCurrent backend: {get_backend()}")

# Force CPU mode (useful for testing)
set_backend("cpu")
print(f"After set_backend('cpu'): {get_backend()}")

# Auto mode (uses GPU if available)
set_backend("auto")
print(f"After set_backend('auto'): {get_backend()}")

# Get the appropriate array module
xp = get_array_module()
print(f"Array module: {xp.__name__}")

Using the Array Module

The array module provides a unified interface that works with either NumPy or CuPy.

Code
# Create array using the selected backend
arr = xp.array([1.0, 2.0, 3.0, 4.0, 5.0])
print(f"\nArray type: {type(arr)}")

# Perform operations
mean = xp.mean(arr)
std = xp.std(arr)
print(f"Mean: {mean}, Std: {std}")

# Convert back to NumPy (always works)
np_arr = to_numpy(arr)
print(f"NumPy array: {np_arr}")

GPU Accelerator for Conformal Prediction

The GPUAccelerator class provides optimized operations for conformal prediction tasks.

Code
# Generate synthetic data
np.random.seed(42)

X, y = make_classification(
    n_samples=5000,
    n_features=20,
    n_informative=10,
    n_classes=5,
    n_clusters_per_class=1,
    random_state=42,
)

X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42, stratify=y)
X_calib, X_test, y_calib, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42, stratify=y_temp)

print(f"\nData: {len(X_train)} train, {len(X_calib)} calib, {len(X_test)} test")

# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

Compare CPU vs GPU Performance

Let’s compare the performance of CPU and GPU for calibration.

Code
# Get probability predictions (this happens on CPU via sklearn)
probas_calib = model.predict_proba(X_calib)
probas_test = model.predict_proba(X_test)

# Initialize accelerators
accel_cpu = GPUAccelerator(use_gpu=False)
accel_gpu = GPUAccelerator(use_gpu=True)  # Falls back to CPU if no GPU

print("\nCPU Accelerator backend: numpy")
print(f"GPU Accelerator backend: {accel_gpu.xp.__name__}")

# Benchmark LAC score computation
n_iterations = 100

# CPU timing
start = time.perf_counter()
for _ in range(n_iterations):
    scores_cpu = accel_cpu.compute_lac_scores(y_calib, probas_calib)
cpu_time = (time.perf_counter() - start) / n_iterations * 1000

# GPU timing (or CPU fallback)
start = time.perf_counter()
for _ in range(n_iterations):
    scores_gpu = accel_gpu.compute_lac_scores(y_calib, probas_calib)
gpu_time = (time.perf_counter() - start) / n_iterations * 1000

print(f"\nLAC Score Computation ({len(y_calib)} samples):")
print(f"  CPU: {cpu_time:.3f} ms per iteration")
print(f"  GPU: {gpu_time:.3f} ms per iteration")
if gpu_time < cpu_time:
    print(f"  Speedup: {cpu_time / gpu_time:.1f}x")

# Verify results match
np.testing.assert_array_almost_equal(scores_cpu, scores_gpu, decimal=5)
print("  Results verified: CPU and GPU outputs match!")

Benchmark Prediction Set Generation

Code
qhat = accel_cpu.compute_quantile(scores_cpu, alpha=0.1)
print(f"\nQuantile threshold: {qhat:.4f}")

# CPU timing
start = time.perf_counter()
for _ in range(n_iterations):
    sets_cpu = accel_cpu.predict_sets_batch(probas_test, qhat)
cpu_time = (time.perf_counter() - start) / n_iterations * 1000

# GPU timing
start = time.perf_counter()
for _ in range(n_iterations):
    sets_gpu = accel_gpu.predict_sets_batch(probas_test, qhat)
gpu_time = (time.perf_counter() - start) / n_iterations * 1000

print(f"\nPrediction Set Generation ({len(probas_test)} samples):")
print(f"  CPU: {cpu_time:.3f} ms per iteration")
print(f"  GPU: {gpu_time:.3f} ms per iteration")

Standard Conformal Classifier (for comparison)

The standard ConformalClassifier uses NumPy internally. GPU acceleration is most beneficial for large batches.

Code
cc = ConformalClassifier(
    model=model,
    alpha=0.10,
    nonconformity_function=lac_nonconformity,
)
cc.calibrate(X_calib, y_calib)

# Standard prediction
start = time.perf_counter()
for _ in range(10):
    pred_sets = cc.predict(X_test)
std_time = (time.perf_counter() - start) / 10 * 1000

print("\nStandard ConformalClassifier.predict():")
print(f"  Time: {std_time:.1f} ms per call")

When GPU Acceleration Helps

GPU acceleration provides the most benefit for:

  • Large calibration sets (>10,000 samples)
  • Large batch predictions
  • Repeated operations (e.g., hyperparameter tuning)
  • Real-time applications with many predictions

For small datasets (<1,000 samples), CPU may be faster due to data transfer overhead.

Code
# Visualize scaling behavior
batch_sizes = [100, 500, 1000, 2000, 5000]
cpu_times = []
gpu_times = []

for size in batch_sizes:
    # Generate test batch
    test_probas = np.random.dirichlet(np.ones(5), size)

    # CPU
    start = time.perf_counter()
    for _ in range(50):
        accel_cpu.predict_sets_batch(test_probas, qhat)
    cpu_times.append((time.perf_counter() - start) / 50 * 1000)

    # GPU
    start = time.perf_counter()
    for _ in range(50):
        accel_gpu.predict_sets_batch(test_probas, qhat)
    gpu_times.append((time.perf_counter() - start) / 50 * 1000)

fig, ax = plt.subplots(figsize=(10, 6))

ax.plot(batch_sizes, cpu_times, "o-", label="CPU (NumPy)", linewidth=2, markersize=8)
ax.plot(batch_sizes, gpu_times, "s-", label="GPU (CuPy)", linewidth=2, markersize=8)

ax.set_xlabel("Batch Size")
ax.set_ylabel("Time (ms)")
ax.set_title("Prediction Set Generation: CPU vs GPU")
ax.legend()
ax.grid(True, alpha=0.3)

# Add note about GPU availability
if not is_gpu_available():
    ax.text(
        0.5,
        0.95,
        "Note: GPU not available, both lines show CPU performance",
        transform=ax.transAxes,
        ha="center",
        fontsize=10,
        style="italic",
        color="gray",
    )

plt.tight_layout()
plt.show()

Summary

GPU acceleration is optional and provides:

  • Drop-in replacement for NumPy operations
  • Automatic fallback to CPU when GPU unavailable
  • Best for large-scale or real-time applications

To enable GPU:

  1. Install CuPy: pip install cupy-cuda12x
  2. Use set_backend("gpu") to force GPU
  3. Or use set_backend("auto") for automatic selection

For most use cases, the standard ConformalClassifier with NumPy is fast enough. Consider GPU for:

  • Batch sizes > 10,000
  • Real-time prediction systems
  • Repeated calibration/prediction loops