Functions for retrieving version information about the AMDSMI library, ROCm installation, and converting status codes to human-readable strings. These utilities help with version checking, debugging, and error handling.
Retrieve the version information of the AMDSMI library.
def amdsmi_get_lib_version() -> Dict[str, Union[int, str]]:
"""
Get the version information of the AMDSMI library.
This function returns the version details of the currently loaded AMDSMI library,
including major, minor, release, and build information. Useful for version checking
and compatibility verification.
Returns:
- Dict[str, Union[int, str]]: Dictionary containing version information:
- "major" (int): Major version number
- "minor" (int): Minor version number
- "release" (int): Release version number
- "build" (str): Build identifier string
Raises:
- AmdSmiLibraryException: If unable to retrieve library version
Example:
```python
import amdsmi
# Get library version (no initialization required)
version = amdsmi.amdsmi_get_lib_version()
print(f"AMDSMI Library Version: {version['major']}.{version['minor']}.{version['release']}")
print(f"Build: {version['build']}")
# Example output:
# AMDSMI Library Version: 7.0.2
# Build: 7.0.2-20240101
```
"""Retrieve the version of the ROCm installation.
def amdsmi_get_rocm_version() -> Tuple[bool, str]:
"""
Get the ROCm version for the rocm-core library.
This function attempts to retrieve the ROCm version by loading the librocm-core.so
shared library and calling its getROCmVersion function. The version is returned as
a string in the format "major.minor.patch".
The function searches for librocm-core.so in the following locations (in priority order):
1. ROCM_HOME/lib or ROCM_PATH/lib (from environment variables)
2. Paths determined by the linker (LD_LIBRARY_PATH or /etc/ld.so.conf.d/)
3. Relative to amdsmi installation (/opt/rocm/share/amd_smi parent directory)
Returns:
- Tuple[bool, str]: A tuple containing:
- bool: True if successful, False if an error occurred
- str: ROCm version string (e.g., "6.0.0") if successful, or error message if failed
Example:
```python
import amdsmi
# Get ROCm version (no initialization required)
success, version_or_error = amdsmi.amdsmi_get_rocm_version()
if success:
print(f"ROCm version: {version_or_error}")
# Example output: ROCm version: 6.0.0
else:
print(f"Error retrieving ROCm version: {version_or_error}")
# Example error: Could not find librocm-core.so
# Check for minimum ROCm version
if success:
major, minor, patch = map(int, version_or_error.split('.'))
if major >= 6:
print("ROCm 6.0 or later detected")
else:
print("Older ROCm version detected")
```
"""Convert an AMDSMI status code to a human-readable string.
def amdsmi_status_code_to_string(status: amdsmi_status_t) -> Union[str, bytes, None]:
"""
Convert an AMDSMI status code to a descriptive string.
This utility function translates numeric status codes returned by AMDSMI functions
into human-readable error messages. Useful for debugging and error reporting.
Parameters:
- status (amdsmi_status_t): Status code to convert (c_uint32 enum value)
Common status codes include:
- AMDSMI_STATUS_SUCCESS (0): Operation successful
- AMDSMI_STATUS_INVAL (1): Invalid parameter
- AMDSMI_STATUS_NOT_SUPPORTED (2): Operation not supported
- AMDSMI_STATUS_NOT_YET_IMPLEMENTED (3): Feature not yet implemented
- And 40+ other status codes
Returns:
- Union[str, bytes, None]: Human-readable status message string, or None if conversion fails
Raises:
- AmdSmiParameterException: If status is not a valid amdsmi_status_t type
- AmdSmiLibraryException: If unable to convert status code
Example:
```python
import amdsmi
from amdsmi import amdsmi_wrapper
# Convert a status code to string
status_code = amdsmi_wrapper.amdsmi_status_t(1) # AMDSMI_STATUS_INVAL
status_msg = amdsmi.amdsmi_status_code_to_string(status_code)
print(f"Status {status_code}: {status_msg}")
# Output: Status 1: Invalid parameter
# Use in error handling
try:
amdsmi.amdsmi_init()
# ... perform operations ...
except amdsmi.AmdSmiLibraryException as e:
if hasattr(e, 'err_code'):
status_msg = amdsmi.amdsmi_status_code_to_string(e.err_code)
print(f"Error: {status_msg}")
finally:
amdsmi.amdsmi_shut_down()
```
"""The package version as a string constant.
__version__: str
"""
Package version string.
This module-level constant contains the version of the amdsmi Python package,
which may differ from the underlying C library version returned by
amdsmi_get_lib_version().
The version follows semantic versioning (MAJOR.MINOR.PATCH).
Example:
```python
import amdsmi
# Get package version
print(f"amdsmi package version: {amdsmi.__version__}")
# Output: amdsmi package version: 7.0.2
# Compare with library version
lib_version = amdsmi.amdsmi_get_lib_version()
pkg_version = amdsmi.__version__
print(f"Package: {pkg_version}")
print(f"Library: {lib_version['major']}.{lib_version['minor']}.{lib_version['release']}")
```
"""Check version compatibility before using advanced features:
import amdsmi
def check_version_compatibility():
"""Check if the installed versions meet requirements."""
# Get package version
pkg_version = amdsmi.__version__
print(f"amdsmi package version: {pkg_version}")
# Get library version
lib_version = amdsmi.amdsmi_get_lib_version()
lib_version_str = f"{lib_version['major']}.{lib_version['minor']}.{lib_version['release']}"
print(f"AMDSMI library version: {lib_version_str}")
print(f"Build: {lib_version['build']}")
# Get ROCm version
success, rocm_version = amdsmi.amdsmi_get_rocm_version()
if success:
print(f"ROCm version: {rocm_version}")
# Check minimum requirements
rocm_major = int(rocm_version.split('.')[0])
if rocm_major < 6:
print("Warning: ROCm 6.0 or later recommended")
return False
else:
print(f"Could not detect ROCm version: {rocm_version}")
return False
# Check library version
if lib_version['major'] >= 7:
print("Version check passed!")
return True
else:
print("Warning: Library version 7.0 or later recommended")
return False
# Run compatibility check
if check_version_compatibility():
# Proceed with AMDSMI operations
passUse status code conversion for better error messages:
import amdsmi
from amdsmi import amdsmi_wrapper
def monitored_operation(processor_handle):
"""Perform operation with detailed error reporting."""
try:
# Attempt to get GPU activity
activity = amdsmi.amdsmi_get_gpu_activity(processor_handle)
return activity
except amdsmi.AmdSmiLibraryException as e:
# Convert error code to readable message
if hasattr(e, 'err_code') and isinstance(e.err_code, amdsmi_wrapper.amdsmi_status_t):
status_msg = amdsmi.amdsmi_status_code_to_string(e.err_code)
print(f"AMDSMI Error: {status_msg}")
print(f"Error code: {e.err_code}")
# Handle specific error types
if e.err_code == 2: # AMDSMI_STATUS_NOT_SUPPORTED
print("This operation is not supported on this device")
elif e.err_code == 1: # AMDSMI_STATUS_INVAL
print("Invalid parameter provided")
else:
print(f"AMDSMI Error: {e}")
return None
# Usage
amdsmi.amdsmi_init()
try:
processors = amdsmi.amdsmi_get_processor_handles()
if processors:
result = monitored_operation(processors[0])
finally:
amdsmi.amdsmi_shut_down()Display comprehensive version information:
import amdsmi
def display_version_info():
"""Display all version information in a formatted way."""
print("=" * 60)
print("AMDSMI Version Information")
print("=" * 60)
# Package version
print(f"\nPackage Version: {amdsmi.__version__}")
# Library version
try:
lib_ver = amdsmi.amdsmi_get_lib_version()
print(f"\nLibrary Version:")
print(f" Major: {lib_ver['major']}")
print(f" Minor: {lib_ver['minor']}")
print(f" Release: {lib_ver['release']}")
print(f" Build: {lib_ver['build']}")
print(f" Full: {lib_ver['major']}.{lib_ver['minor']}.{lib_ver['release']}")
except Exception as e:
print(f"\nLibrary Version: Error - {e}")
# ROCm version
success, rocm_info = amdsmi.amdsmi_get_rocm_version()
print(f"\nROCm Version:")
if success:
print(f" Version: {rocm_info}")
major, minor, patch = rocm_info.split('.')
print(f" Major: {major}")
print(f" Minor: {minor}")
print(f" Patch: {patch}")
else:
print(f" Status: Not detected - {rocm_info}")
print("=" * 60)
# Display version information
display_version_info()Enable features based on version availability:
import amdsmi
def get_advanced_metrics(processor_handle):
"""Use advanced features only if version supports them."""
# Check library version
lib_version = amdsmi.amdsmi_get_lib_version()
# Get basic metrics (available in all versions)
metrics = {
'activity': amdsmi.amdsmi_get_gpu_activity(processor_handle),
'temperature': amdsmi.amdsmi_get_temp_metric(
processor_handle,
amdsmi.AmdSmiTemperatureType.EDGE,
amdsmi.AmdSmiTemperatureMetric.CURRENT
)
}
# Advanced features only in newer versions
if lib_version['major'] >= 7:
try:
# Try to get advanced metrics
metrics['pm_metrics'] = amdsmi.amdsmi_get_gpu_pm_metrics_info(processor_handle)
except amdsmi.AmdSmiLibraryException:
# Feature not available on this hardware
pass
return metrics
# Usage
amdsmi.amdsmi_init()
try:
processors = amdsmi.amdsmi_get_processor_handles()
if processors:
metrics = get_advanced_metrics(processors[0])
print(f"Collected {len(metrics)} metric types")
finally:
amdsmi.amdsmi_shut_down()Common AMDSMI status codes and their meanings:
import amdsmi
from amdsmi import amdsmi_wrapper
def demonstrate_status_codes():
"""Demonstrate common status codes and their messages."""
# Common status codes
status_codes = [
(0, "AMDSMI_STATUS_SUCCESS"),
(1, "AMDSMI_STATUS_INVAL"),
(2, "AMDSMI_STATUS_NOT_SUPPORTED"),
(3, "AMDSMI_STATUS_NOT_YET_IMPLEMENTED"),
(4, "AMDSMI_STATUS_FAIL_LOAD_MODULE"),
(5, "AMDSMI_STATUS_FAIL_LOAD_SYMBOL"),
(6, "AMDSMI_STATUS_DRM_ERROR"),
]
print("Common AMDSMI Status Codes:")
print("-" * 60)
for code, name in status_codes:
status = amdsmi_wrapper.amdsmi_status_t(code)
try:
message = amdsmi.amdsmi_status_code_to_string(status)
print(f"{code:3d} | {name:35s} | {message}")
except Exception as e:
print(f"{code:3d} | {name:35s} | Error: {e}")
# Run demonstration
demonstrate_status_codes()amdsmi_status_t = ctypes.c_uint32 # enum
"""
Status code enumeration type.
Represents the return status of AMDSMI C library functions. This is a 32-bit
unsigned integer enum with 40+ predefined values.
Common values:
- 0: AMDSMI_STATUS_SUCCESS - Operation successful
- 1: AMDSMI_STATUS_INVAL - Invalid parameter
- 2: AMDSMI_STATUS_NOT_SUPPORTED - Operation not supported
- 3: AMDSMI_STATUS_NOT_YET_IMPLEMENTED - Feature not implemented
- 4: AMDSMI_STATUS_FAIL_LOAD_MODULE - Failed to load module
- 5: AMDSMI_STATUS_FAIL_LOAD_SYMBOL - Failed to load symbol
- 6: AMDSMI_STATUS_DRM_ERROR - DRM (Direct Rendering Manager) error
And 30+ additional status codes for various error conditions.
"""amdsmi_get_lib_version() and amdsmi_get_rocm_version() can be called without initializing the library__version__ constant represents the Python package version, which may differ from the C library versionamdsmi_get_lib_version() returns the underlying C library version detailsamdsmi_get_rocm_version() searches multiple standard locations for the ROCm installationROCM_HOME or ROCM_PATH environment variables to help locate librocm-core.soamdsmi_get_rocm_version() before using the version string