qbiocode.apps.quvine.utils.torch_utils module#

PyTorch Utilities and Wrappers

This module provides utilities for handling PyTorch dependencies gracefully, including availability checks, error handling, and fallback mechanisms.

Summary#

Exceptions:

TorchNotAvailableError

Custom exception for when PyTorch is required but not available.

Functions:

check_torch_available

Check if PyTorch is available.

get_device

Get the best available device for PyTorch.

get_torch_info

Get information about PyTorch installation.

log_torch_info

Log PyTorch availability and configuration.

require_torch

Decorator to require PyTorch for a function.

safe_torch_import

Safely import a PyTorch module or class.

torch_optional

Decorator for functions that optionally use PyTorch.

validate_torch_tensor

Validate that an object is a PyTorch tensor.

Data:

TORCH_AVAILABLE

bool(x) -> bool

__all__: TORCH_AVAILABLE, TORCH_VERSION, TorchNotAvailableError, check_torch_available, get_device, get_torch_info, log_torch_info, require_torch, safe_torch_import, torch_optional, validate_torch_tensor

Reference#

check_torch_available()[source]#

Check if PyTorch is available.

Returns:

True if PyTorch is available, False otherwise

Return type:

bool

require_torch(func)[source]#

Decorator to require PyTorch for a function.

Raises ImportError with helpful message if PyTorch is not available.

Parameters:

func (Callable) – Function to wrap

Return type:

Callable

Returns:

Wrapped function that checks for PyTorch

Example

>>> @require_torch
... def train_model(data):
...     # PyTorch code here
...     pass
torch_optional(fallback_value=None, log_warning=True)[source]#

Decorator for functions that optionally use PyTorch.

If PyTorch is not available, returns fallback_value instead of raising error.

Parameters:
  • fallback_value (Any) – Value to return if PyTorch is not available

  • log_warning (bool) – Whether to log a warning when falling back

Return type:

Callable

Returns:

Decorator function

Example

>>> @torch_optional(fallback_value=None)
... def optional_gpu_computation(data):
...     # PyTorch code here
...     pass
get_device(prefer_gpu=True)[source]#

Get the best available device for PyTorch.

Parameters:

prefer_gpu (bool) – Whether to prefer GPU if available

Return type:

Optional[str]

Returns:

Device string (‘cuda’, ‘mps’, ‘cpu’) or None if PyTorch not available

Example

>>> device = get_device()
>>> if device:
...     tensor = torch.tensor([1, 2, 3], device=device)
safe_torch_import(module_name, class_name=None)[source]#

Safely import a PyTorch module or class.

Parameters:
  • module_name (str) – Name of the module to import (e.g., ‘torch.nn’)

  • class_name (Optional[str]) – Optional class name to import from module

Return type:

Optional[Any]

Returns:

Imported module/class or None if not available

Example

>>> nn = safe_torch_import('torch.nn')
>>> if nn:
...     model = nn.Linear(10, 5)
exception TorchNotAvailableError(method_name='This method')[source]#

Bases: ImportError

Custom exception for when PyTorch is required but not available.

validate_torch_tensor(tensor, name='tensor')[source]#

Validate that an object is a PyTorch tensor.

Parameters:
  • tensor (Any) – Object to validate

  • name (str) – Name of the tensor for error messages

Raises:
Return type:

None

Example

>>> validate_torch_tensor(my_tensor, "input")
get_torch_info()[source]#

Get information about PyTorch installation.

Return type:

dict

Returns:

Dictionary with PyTorch information

Example

>>> info = get_torch_info()
>>> print(f"PyTorch version: {info['version']}")
log_torch_info()[source]#

Log PyTorch availability and configuration.