Torch Device Manager
A lightweight PyTorch utility for automatic hardware detection and memory optimization across different devices (CPU, CUDA, MPS).
Features
- 🔍 Automatic Device Detection: Detects the best available hardware (CUDA, Apple Silicon MPS, or CPU)
- 🧠 Memory Optimization: Automatically adjusts batch sizes and gradient accumulation based on available memory
- ⚡ Mixed Precision Support: Optional automatic mixed precision with gradient scaling
- 📊 Memory Monitoring: Real-time memory usage tracking and logging
- 🛡️ Fallback Protection: Graceful fallback to CPU when requested devices aren't available
Installation
pip install torch-device-manager
Quick Start
from torch_device_manager import DeviceManager
import torch
# Initialize device manager (auto-detects best device)
device_manager = DeviceManager(device="auto", mixed_precision=True)
# Get the torch device
device = device_manager.get_device()
# Move your model to the optimal device
model = YourModel().to(device)
# Optimize batch size based on available memory
optimal_batch_size, gradient_steps = device_manager.optimize_for_memory(
model=model,
batch_size=32
)
print(f"Using device: {device}")
print(f"Optimized batch size: {optimal_batch_size}")
print(f"Gradient accumulation steps: {gradient_steps}")
Usage in Training Scripts
Basic Integration
import torch
import torch.nn as nn
from torch_device_manager import DeviceManager
def train_model():
# Initialize device manager
device_manager = DeviceManager(device="auto", mixed_precision=True)
device = device_manager.get_device()
# Setup model
model = YourModel().to(device)
optimizer = torch.optim.Adam(model.parameters())
# Optimize memory usage
batch_size, gradient_steps = device_manager.optimize_for_memory(model, 32)
# Training loop
for epoch in range(num_epochs):
for batch_idx, (data, target) in enumerate(dataloader):
data, target = data.to(device), target.to(device)
# Use mixed precision if available
if device_manager.mixed_precision and device_manager.scaler:
with torch.cuda.amp.autocast():
output = model(data)
loss = criterion(output, target)
device_manager.scaler.scale(loss).backward()
if (batch_idx + 1) % gradient_steps == 0:
device_manager.scaler.step(optimizer)
device_manager.scaler.update()
optimizer.zero_grad()
else:
output = model(data)
loss = criterion(output, target)
loss.backward()
if (batch_idx + 1) % gradient_steps == 0:
optimizer.step()
optimizer.zero_grad()
# Log memory usage
device_manager.log_memory_usage()
Advanced Usage
from torch_device_manager import DeviceManager
# Force specific device
device_manager = DeviceManager(device="cuda", mixed_precision=False)
# Check memory info
memory_info = device_manager.get_memory_info()
print(f"Available memory: {memory_info}")
# Manual memory optimization
if memory_info.get("free_gb", 0) < 2.0:
print("Low memory detected, reducing batch size")
batch_size = 4
API Reference
DeviceManager
Constructor
device(str, default="auto"): Device to use ("auto", "cuda", "mps", "cpu")mixed_precision(bool, default=True): Enable mixed precision training
Methods
get_device(): Returns torch.device objectget_memory_info(): Returns memory information dictlog_memory_usage(): Logs current memory usageoptimize_for_memory(model, batch_size): Returns optimized (batch_size, gradient_steps)
Device Support
- CUDA: Full support with memory optimization and mixed precision
- Apple Silicon (MPS): Basic support with conservative memory settings
- CPU: Fallback support with optimized batch sizes
Requirements
- Python >= 3.8
- PyTorch >= 2.1.1
License
MIT License
Contributing
Contributions are welcome!
Metadata
Release files for torch-device-manager 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| torch_device_manager-0.1.0.tar.gz | 7.7 kB | With provenance | Details for torch_device_manager-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| torch_device_manager-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for torch_device_manager-0.1.0-py3-none-any.whl |
Total release size: 13.5 kB
Release files / torch_device_manager-0.1.0.tar.gz
| Download URL | torch_device_manager-0.1.0.tar.gz |
|---|---|
| Size | 7.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
31bbdec42054c410e12f800ad80b7efd44b48d6caf6a05b77d33f45cacb02960
|
|
BLAKE2b-256 checksum How to use checksums |
9172d12f8a63d9d98c9ed509b721e5e4c1362324ab9ef85bf9245952e1c18623
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.12.9
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 19, 2025.
Transparency logRelease files / torch_device_manager-0.1.0-py3-none-any.whl
| Download URL | torch_device_manager-0.1.0-py3-none-any.whl |
|---|---|
| Size | 5.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6fc555669c43b7e81ee7a26ca8897628f8d45bb8b4aa9bf481c26c500c820858
|
|
BLAKE2b-256 checksum How to use checksums |
667cf33aa97897703c0ef9d234642ec8310d4f3214603f0671cc5b148a27da52
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.12.9
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 19, 2025.
Transparency logSecurity for torch-device-manager 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for torch_device_manager-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 19, 2025.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.