nirs4all.utils.backend module
Backend detection and lazy loading utilities for ML frameworks.
This module provides: - Lazy detection of framework availability (no imports at module load) - Cached availability checks for performance - Clean error messages guiding users to install missing dependencies - GPU availability detection across all frameworks
- Usage:
from nirs4all.utils.backend import require_backend, is_available, get_backend_info
# Check availability without importing if is_available(‘tensorflow’):
# Safe to import tensorflow here import tensorflow as tf
# Require a backend (raises helpful ImportError if missing) require_backend(‘torch’) import torch
- exception nirs4all.utils.backend.BackendNotAvailableError(backend: str, feature: str | None = None)[source]
Bases:
ImportErrorRaised when a required backend is not installed.
Provides helpful error messages with installation instructions.
- nirs4all.utils.backend.check_backend_available(backend_name: str) None[source]
Check if a backend is available, raising ImportError if not.
This is a legacy compatibility wrapper for require_backend. Use require_backend() for new code.
- Parameters:
backend_name – Name of the backend (‘tensorflow’, ‘torch’, ‘jax’).
- Raises:
BackendNotAvailableError – If the backend is not installed.
- nirs4all.utils.backend.clear_availability_cache()[source]
Clear the availability cache (useful for testing).
- nirs4all.utils.backend.framework(framework_name: str) Callable[[F], F][source]
Decorator to mark a function/class with its framework.
This enables automatic framework detection in the model factory.
- Parameters:
framework_name – Name of the framework (‘tensorflow’, ‘pytorch’, ‘jax’)
- Returns:
Decorator function that adds framework attribute.
Example
>>> @framework('tensorflow') ... def build_cnn(input_shape, params): ... import tensorflow as tf ... # ... build model
- nirs4all.utils.backend.get_backend_info() Dict[str, Dict[str, Any]][source]
Get comprehensive info about all backends.
- Returns:
Dictionary with availability and GPU info for each backend.
Example
>>> info = get_backend_info() >>> for name, details in info.items(): ... status = "✓" if details['available'] else "✗" ... print(f"{status} {name}")
- nirs4all.utils.backend.get_gpu_info() Dict[str, Any][source]
Get detailed GPU information for all available backends.
- Returns:
Dictionary with GPU info per backend, including device counts and names where available.
Example
>>> info = get_gpu_info() >>> if info.get('torch', {}).get('available'): ... print(f"GPU: {info['torch']['device_name']}")
- nirs4all.utils.backend.is_available(backend: str) bool[source]
Check if a backend is available without importing it.
Results are cached for performance.
- Parameters:
backend – Backend name (‘tensorflow’, ‘torch’, ‘jax’, etc.)
- Returns:
True if the backend is installed and can be imported.
Example
>>> if is_available('tensorflow'): ... import tensorflow as tf
- nirs4all.utils.backend.is_gpu_available(backend: str | None = None) bool[source]
Check if GPU is available for the specified backend or any backend.
Results are cached for performance. The first call for each backend will import the framework to check GPU availability.
- Parameters:
backend – Specific backend to check (‘tensorflow’, ‘torch’, ‘jax’), or None to check all available backends.
- Returns:
True if GPU is available for the specified backend(s).
Example
>>> if is_gpu_available('torch'): ... device = 'cuda' ... else: ... device = 'cpu'
- nirs4all.utils.backend.is_ikpls_available() bool[source]
Check if ikpls is installed.
- Returns:
True if ikpls is available.
- nirs4all.utils.backend.is_jax_available() bool[source]
Check if JAX is installed.
- Returns:
True if JAX is available.
- nirs4all.utils.backend.is_keras_available() bool[source]
Check if Keras is installed.
- Returns:
True if Keras is available.
- nirs4all.utils.backend.is_tensorflow_available() bool[source]
Check if TensorFlow is installed.
- Returns:
True if TensorFlow is available.
- nirs4all.utils.backend.is_torch_available() bool[source]
Check if PyTorch is installed.
- Returns:
True if PyTorch is available.
- nirs4all.utils.backend.lazy_import(module_name: str, backend: str | None = None)[source]
Create a lazy import that only loads the module when accessed.
- Parameters:
module_name – Full module path to import.
backend – Optional backend to check before importing.
- Returns:
A proxy object that imports the module on first access.
Example
>>> tf = lazy_import('tensorflow', backend='tensorflow') >>> # tensorflow not imported yet >>> model = tf.keras.Model() # Now tensorflow is imported
- nirs4all.utils.backend.print_backend_status()[source]
Print a formatted summary of backend availability.
Displays a table showing which backends are installed and whether GPU support is available for deep learning frameworks.
- nirs4all.utils.backend.require_backend(backend: str, feature: str | None = None) None[source]
Require a backend to be available, raising a helpful error if not.
- Parameters:
backend – Backend name (‘tensorflow’, ‘torch’, ‘jax’, etc.)
feature – Optional feature name for better error messages.
- Raises:
BackendNotAvailableError – If the backend is not installed.
Example
>>> require_backend('tensorflow', feature='NICON neural network') >>> import tensorflow as tf # Safe after require_backend