pax_global_header 0000666 0000000 0000000 00000000064 14027501566 0014520 g ustar 00root root 0000000 0000000 52 comment=09044167c05fb47b1ae9cfd9505ec15584087b37
gpu-utils-3.6.0/ 0000775 0000000 0000000 00000000000 14027501566 0013457 5 ustar 00root root 0000000 0000000 gpu-utils-3.6.0/GPUmodules/ 0000775 0000000 0000000 00000000000 14027501566 0015503 5 ustar 00root root 0000000 0000000 gpu-utils-3.6.0/GPUmodules/GPUgui.py 0000775 0000000 0000000 00000024672 14027501566 0017233 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
""" gpu-utils: GPUgui module to support gui in rickslab-gpu-utils.
Copyright (C) 2020 RicksLab
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
"""
__author__ = 'RueiKe'
__copyright__ = 'Copyright (C) 2020 RicksLab'
__credits__ = ['@berturion - Testing and Verification']
__license__ = 'GNU General Public License'
__program_name__ = 'gpu-utils'
__maintainer__ = 'RueiKe'
__docformat__ = 'reStructuredText'
# pylint: disable=multiple-statements
# pylint: disable=line-too-long
# pylint: disable=bad-continuation
from typing import Tuple, Dict
import sys
import re
import logging
import warnings
try:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
except ModuleNotFoundError as error:
print('gi import error: {}'.format(error))
print('gi is required for {}'.format(__program_name__))
print(' In a venv, first install vext: pip install --no-cache-dir vext')
print(' Then install vext.gi: pip install --no-cache-dir vext.gi')
sys.exit(0)
try:
from GPUmodules import env
except ImportError:
import env
from GPUmodules import __version__, __status__
ColorDict = Dict[str, str]
LOGGER = logging.getLogger('gpu-utils')
PATTERNS = env.GutConst.PATTERNS
def get_color(value: str) -> str:
"""
Get the rgb hex string for the provided color name.
:param value: A valid project color name.
:return: rrb value as a hex string.
"""
return GuiProps.color_name_to_hex(value)
class GuiProps:
"""
Class to manage style properties of Gtk widgets.
"""
_colors: ColorDict = {'white': '#FFFFFF',
'white_off': '#FCFCFC',
'white_pp': '#F0E5D3',
'cream': '#FFFDD1',
'gray20': '#CCCCCC',
'gray50': '#7F7F7F',
'gray60': '#666666',
'gray70': '#4D4D4D',
'gray80': '#333333',
'gray95': '#0D0D0D',
'gray_dk': '#6A686E',
'black': '#000000',
# Colors Low Contrast - For table fields
'green': '#8EC3A7',
'green_dk': '#6A907C',
'teal': '#218C8D',
'olive': '#6C9040',
'red': '#B73743',
'orange': '#E86850',
'yellow': '#C9A100',
'blue': '#587498',
'purple': '#6264A7',
# Colors Bright - For plot lines
'br_red': '#FF2D2D',
'br_orange': '#FF6316',
'br_blue': '#66CCFF',
'br_pink': '#CC00FF',
'br_green': '#99FF99',
'br_yellow': '#FFFF66',
# Slate - For table fields
'slate_lt': '#A0A0AA',
'slate_md': '#80808d',
'slate_dk': '#5D5D67',
'slate_vdk': '#3A3A40'}
@staticmethod
def color_name_to_hex(value: str) -> str:
"""
Return the hex code for the given string. The specified string must exist in the project color list.
:param value: Color name
:return: Color hex code
"""
if value not in GuiProps._colors.keys():
raise ValueError('Invalid color name {} not in {}'.format(value, GuiProps._colors))
return GuiProps._colors[value]
@staticmethod
def color_name_to_rgba(value: str) -> Tuple[float, ...]:
"""
Convert the given color name to a color tuple. The given color string mus exist in the project
color list.
:param value: Color name
:return: Color tuple
"""
if value not in GuiProps._colors.keys():
raise ValueError('Invalid color name {} not in {}'.format(value, GuiProps._colors))
return GuiProps.hex_to_rgba(GuiProps._colors[value])
@staticmethod
def hex_to_rgba(value: str) -> Tuple[float, ...]:
"""
Return rgba tuple for give hex color name.
:param value: hex color value as string
:return: rgba tuple
.. note:: Code copied from Stack Overflow
"""
if not re.fullmatch(PATTERNS['HEXRGB'], value):
raise ValueError('Invalid hex color format in {}'.format(value))
value = value.lstrip('#')
if len(value) != 6:
raise ValueError('Invalid hex color format in {}'.format(value))
(r_1, g_1, b_1, a_1) = tuple(int(value[i:i + 2], 16) for i in range(0, 6, 2)) + (1,)
(r_1, g_1, b_1, a_1) = (r_1 / 255.0, g_1 / 255.0, b_1 / 255.0, a_1)
return tuple([r_1, g_1, b_1, a_1])
@staticmethod
def set_gtk_prop(gui_item, top: int = None, bottom: int = None, right: int = None,
left: int = None, width: int = None, width_chars: int = None, width_max: int = None,
max_length: int = None, align: tuple = None, xalign: float = None) -> None:
"""
Set properties of Gtk objects.
:param gui_item: Gtk object
:param top: Top margin
:param bottom: Bottom margin
:param right: Right margin
:param left: Left margin
:param width: Width of request field
:param width_chars: Width of label
:param width_max: Max Width of object
:param max_length: max length of entry
:param align: Alignment parameters
:param xalign: X Alignment parameter
"""
if top:
gui_item.set_property('margin-top', top)
if bottom:
gui_item.set_property('margin-bottom', bottom)
if right:
gui_item.set_property('margin-right', right)
if left:
gui_item.set_property('margin-left', left)
if width:
gui_item.set_property('width-request', width)
if width_max:
gui_item.set_max_width_chars(width_max)
if width_chars:
gui_item.set_width_chars(width_chars)
if max_length:
gui_item.set_max_length(max_length)
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
if xalign:
# FIXME - This is deprecated in latest Gtk, need to use halign
gui_item.set_alignment(xalign=xalign)
if align:
# FIXME - This is deprecated in latest Gtk, need to use halign
gui_item.set_alignment(*align)
@classmethod
def set_style(cls, css_str=None) -> None:
"""
Set the specified css style, or set default styles if no css string is specified.
:param css_str: A valid css format string.
"""
css_list = []
if css_str is None:
# Initialize formatting colors.
css_list.append("grid { background-image: image(%s); }" % cls._colors['gray80'])
css_list.append("#light_grid { background-image: image(%s); }" % cls._colors['gray20'])
css_list.append("#dark_grid { background-image: image(%s); }" % cls._colors['gray70'])
css_list.append("#dark_box { background-image: image(%s); }" % cls._colors['slate_dk'])
css_list.append("#med_box { background-image: image(%s); }" % cls._colors['slate_md'])
css_list.append("#light_box { background-image: image(%s); }" % cls._colors['slate_lt'])
css_list.append("#head_box { background-image: image(%s); }" % cls._colors['blue'])
css_list.append("#warn_box { background-image: image(%s); }" % cls._colors['red'])
css_list.append("#button_box { background-image: image(%s); }" % cls._colors['slate_dk'])
css_list.append("#message_box { background-image: image(%s); }" % cls._colors['gray50'])
css_list.append("#message_label { color: %s; }" % cls._colors['white_off'])
css_list.append("#warn_label { color: %s; }" % cls._colors['white_pp'])
css_list.append("#white_label { color: %s; }" % cls._colors['white_off'])
css_list.append("#black_label { color: %s; }" % cls._colors['gray95'])
css_list.append("#ppm_combo { background-image: image(%s); color: %s; }" %
(cls._colors['green'], cls._colors['black']))
css_list.append("button { background-image: image(%s); color: %s; }" %
(cls._colors['slate_lt'], cls._colors['black']))
css_list.append("entry { background-image: image(%s); color: %s; }" %
(cls._colors['green'], cls._colors['gray95']))
# Below format does not work.
css_list.append("entry:selected { background-image: image(%s); color: %s; }" %
(cls._colors['yellow'], cls._colors['white']))
else:
css_list.append(css_str)
LOGGER.info('css %s', css_list)
screen = Gdk.Screen.get_default()
for css_item in css_list:
provider = Gtk.CssProvider()
css = css_item.encode('utf-8')
provider.load_from_data(css)
style_context = Gtk.StyleContext()
style_context.add_provider_for_screen(screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
def about() -> None:
"""
Display details of this module.
"""
print(__doc__)
print('Author: ', __author__)
print('Copyright: ', __copyright__)
print('Credits: ', *['\n {}'.format(item) for item in __credits__])
print('License: ', __license__)
print('Version: ', __version__)
print('Maintainer: ', __maintainer__)
print('Status: ', __status__)
sys.exit(0)
if __name__ == '__main__':
about()
gpu-utils-3.6.0/GPUmodules/GPUmodule.py 0000775 0000000 0000000 00000325054 14027501566 0017732 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
"""GPUmodules - Classes to represent GPUs and sets of GPUs used in rickslab-gpu-utils.
Copyright (C) 2019 RicksLab
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
"""
__author__ = 'RueiKe'
__copyright__ = 'Copyright (C) 2019 RicksLab'
__credits__ = ['Craig Echt - Testing, Debug, Verification, and Documentation',
'Keith Myers - Testing, Debug, Verification of NV Capability']
__license__ = 'GNU General Public License'
__program_name__ = 'gpu-utils'
__maintainer__ = 'RueiKe'
__docformat__ = 'reStructuredText'
# pylint: disable=multiple-statements
# pylint: disable=line-too-long
# pylint: disable=bad-continuation
import re
import subprocess
import shlex
import os
import sys
import logging
from typing import Union, List, Dict, TextIO, IO, Generator, Any
from pathlib import Path
from uuid import uuid4
from enum import Enum
import glob
from numpy import nan as np_nan
from GPUmodules import __version__, __status__
try:
from GPUmodules import env
except ImportError:
import env
LOGGER = logging.getLogger('gpu-utils')
PATTERNS = env.GutConst.PATTERNS
class GpuEnum(Enum):
"""
Replace __str__ method of Enum so that name excludes type and can be used as key in other dicts.
"""
def __str__(self):
return self.name
class ObjDict(dict):
"""
Allow access of dictionary keys by key name.
"""
# pylint: disable=attribute-defined-outside-init
# pylint: disable=too-many-instance-attributes
def __getattr__(self, name):
if name in self:
return self[name]
raise AttributeError('No such attribute: {}'.format(name))
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
if name in self:
del self[name]
else:
raise AttributeError('No such attribute: {}'.format(name))
class GpuItem:
"""An object to store GPU details.
"""
# pylint: disable=attribute-defined-outside-init
# pylint: disable=too-many-instance-attributes
_finalized: bool = False
_button_labels: Dict[str, str] = {'loading': 'Load%',
'power': 'Power',
'power_cap': 'PowerCap',
'temp_val': 'Temp',
'vddgfx_val': 'VddGfx',
'sclk_ps_val': 'SCLK Pstate',
'sclk_f_val': 'SCLK',
'mclk_ps_val': 'MCLK Pstate',
'mclk_f_val': 'MCLK'}
_fan_item_list: List[str] = ['fan_enable', 'pwm_mode', 'fan_target',
'fan_speed', 'fan_pwm', 'fan_speed_range', 'fan_pwm_range']
short_list: List[str] = ['vendor', 'readable', 'writable', 'compute', 'card_num', 'id', 'model_device_decode',
'gpu_type', 'card_path', 'sys_card_path', 'hwmon_path', 'pcie_id']
_GPU_NC_Param_List: List[str] = ['compute', 'readable', 'writable', 'vendor', 'model', 'card_num',
'sys_card_path', 'gpu_type', 'card_path', 'hwmon_path', 'pcie_id',
'driver', 'id', 'model_device_decode']
# Vendor and Type skip lists for reporting
AMD_Skip_List: List[str] = ['frequencies_max', 'compute_mode', 'serial_number', 'card_index']
NV_Skip_List: List[str] = ['fan_enable', 'fan_speed', 'fan_pwm_range', 'fan_speed_range', 'pwm_mode',
'mem_gtt_total', 'mem_gtt_used', 'mem_gtt_usage',
'mclk_ps', 'mclk_f_range', 'sclk_f_range', 'vddc_range', 'power_dpm_force',
'temp_crits', 'voltages']
LEGACY_Skip_List: List[str] = ['vbios', 'loading', 'mem_loading', 'sclk_ps', 'mclk_ps', 'ppm', 'power',
'power_cap', 'power_cap_range', 'mem_vram_total', 'mem_vram_used',
'mem_gtt_total', 'mem_gtt_used', 'mem_vram_usage', 'mem_gtt_usage',
'fan_speed_range', 'fan_enable', 'fan_target', 'fan_speed', 'voltages',
'vddc_range', 'frequencies', 'sclk_f_range', 'mclk_f_range']
# Define Class Labels
GPU_Type = GpuEnum('type', 'Undefined Unsupported Supported Legacy APU PStatesNE PStates CurvePts')
GPU_Comp = GpuEnum('Compatibility', 'None ALL ReadWrite ReadOnly WriteOnly Readable Writable')
GPU_Vendor = GpuEnum('vendor', 'Undefined ALL AMD NVIDIA INTEL ASPEED MATROX PCIE')
_apu_gpus: List[str] = ['Carrizo', 'Renoir', 'Cezanne', 'Wrestler', 'Llano', 'Ontario', 'Trinity',
'Richland', 'Kabini', 'Kaveri', 'Picasso', 'Bristol Ridge', 'Raven Ridge',
'Hondo', 'Desna', 'Zacate', 'Weatherford', 'Godavari', 'Temash', 'WinterPark',
'BeaverCreek']
# Table parameters labels.
table_parameters: List[str] = ['model_display', 'loading', 'mem_loading', 'mem_vram_usage', 'mem_gtt_usage',
'power', 'power_cap', 'energy', 'temp_val', 'vddgfx_val',
'fan_pwm', 'sclk_f_val', 'sclk_ps_val', 'mclk_f_val', 'mclk_ps_val', 'ppm']
table_param_labels: Dict[str, str] = {
'model_display': 'Model',
'loading': 'GPU Load %',
'mem_loading': 'Mem Load %',
'mem_vram_usage': 'VRAM Usage %',
'mem_gtt_usage': 'GTT Usage %',
'power': 'Power (W)',
'power_cap': 'Power Cap (W)',
'energy': 'Energy (kWh)',
'temp_val': 'T (C)',
'vddgfx_val': 'VddGFX (mV)',
'fan_pwm': 'Fan Spd (%)',
'sclk_f_val': 'Sclk (MHz)',
'sclk_ps_val': 'Sclk Pstate',
'mclk_f_val': 'Mclk (MHz)',
'mclk_ps_val': 'Mclk Pstate',
'ppm': 'Perf Mode'}
# Complete GPU print items, use skip lists where appropriate
_GPU_CLINFO_Labels: Dict[str, str] = {
'sep4': '#',
'opencl_version': ' Device OpenCL C Version',
'device_name': ' Device Name',
'device_version': ' Device Version',
'driver_version': ' Driver Version',
'max_cu': ' Max Compute Units',
'simd_per_cu': ' SIMD per CU',
'simd_width': ' SIMD Width',
'simd_ins_width': ' SIMD Instruction Width',
'max_mem_allocation': ' CL Max Memory Allocation',
'max_wi_dim': ' Max Work Item Dimensions',
'max_wi_sizes': ' Max Work Item Sizes',
'max_wg_size': ' Max Work Group Size',
'prf_wg_size': ' Preferred Work Group Size',
'prf_wg_multiple': ' Preferred Work Group Multiple'}
_GPU_Param_Labels: Dict[str, str] = {
'card_num': 'Card Number',
'vendor': 'Vendor',
'readable': 'Readable',
'writable': 'Writable',
'compute': 'Compute',
'unique_id': 'GPU UID',
'serial_number': 'GPU S/N',
'id': 'Device ID',
'model_device_decode': 'Decoded Device ID',
'model': 'Card Model',
'model_display': 'Display Card Model',
'card_index': 'Card Index',
'pcie_id': 'PCIe ID',
'link_spd': ' Link Speed',
'link_wth': ' Link Width',
'sep1': '#',
'driver': 'Driver',
'vbios': 'vBIOS Version',
'compute_platform': 'Compute Platform',
'compute_mode': 'Compute Mode',
'gpu_type': 'GPU Type',
'hwmon_path': 'HWmon',
'card_path': 'Card Path',
'sys_card_path': 'System Card Path',
'sep2': '#',
'power': 'Current Power (W)',
'power_cap': 'Power Cap (W)',
'power_cap_range': ' Power Cap Range (W)',
'fan_enable': 'Fan Enable',
'pwm_mode': 'Fan PWM Mode',
'fan_target': 'Fan Target Speed (rpm)',
'fan_speed': 'Current Fan Speed (rpm)',
'fan_pwm': 'Current Fan PWM (%)',
'fan_speed_range': ' Fan Speed Range (rpm)',
'fan_pwm_range': ' Fan PWM Range (%)',
'sep3': '#',
'loading': 'Current GPU Loading (%)',
'mem_loading': 'Current Memory Loading (%)',
'mem_gtt_usage': 'Current GTT Memory Usage (%)',
'mem_gtt_used': ' Current GTT Memory Used (GB)',
'mem_gtt_total': ' Total GTT Memory (GB)',
'mem_vram_usage': 'Current VRAM Usage (%)',
'mem_vram_used': ' Current VRAM Used (GB)',
'mem_vram_total': ' Total VRAM (GB)',
'temperatures': 'Current Temps (C)',
'temp_crits': 'Critical Temps (C)',
'voltages': 'Current Voltages (V)',
'vddc_range': ' Vddc Range',
'frequencies': 'Current Clk Frequencies (MHz)',
'frequencies_max': 'Maximum Clk Frequencies (MHz)',
'sclk_ps': 'Current SCLK P-State',
'sclk_f_range': ' SCLK Range',
'mclk_ps': 'Current MCLK P-State',
'mclk_f_range': ' MCLK Range',
'ppm': 'Power Profile Mode',
'power_dpm_force': 'Power DPM Force Performance Level'}
# GPU sensor reading details
SensorSet = Enum('set', 'None Test Static Dynamic Info State Monitor All')
sensor_sets = {SensorSet.Static: {'HWMON': ['power_cap_range', 'temp_crits',
'fan_speed_range', 'fan_pwm_range']},
SensorSet.Dynamic: {'HWMON': ['power', 'power_cap', 'temperatures', 'voltages',
'frequencies', 'fan_enable', 'fan_target',
'fan_speed', 'pwm_mode', 'fan_pwm']},
SensorSet.Info: {'DEVICE': ['unique_id', 'vbios', 'mem_vram_total', 'mem_gtt_total']},
SensorSet.State: {'DEVICE': ['loading', 'mem_loading', 'mem_gtt_used', 'mem_vram_used',
'link_spd', 'link_wth', 'sclk_ps', 'mclk_ps', 'ppm',
'power_dpm_force']},
SensorSet.Monitor: {'HWMON': ['power', 'power_cap', 'temperatures', 'voltages',
'frequencies', 'fan_pwm'],
'DEVICE': ['loading', 'mem_loading', 'mem_gtt_used', 'mem_vram_used',
'sclk_ps', 'mclk_ps', 'ppm']},
SensorSet.All: {'DEVICE': ['unique_id', 'vbios', 'loading', 'mem_loading',
'link_spd', 'link_wth', 'sclk_ps', 'mclk_ps', 'ppm',
'power_dpm_force', 'mem_vram_total', 'mem_gtt_total',
'mem_vram_used', 'mem_gtt_used'],
'HWMON': ['power_cap_range', 'temp_crits', 'power', 'power_cap',
'temperatures', 'voltages', 'frequencies',
'fan_speed_range', 'fan_pwm_range', 'fan_enable', 'fan_target',
'fan_speed', 'pwm_mode', 'fan_pwm']}}
SensorType = Enum('type', 'SingleParam SingleString SingleStringSelect MinMax MLSS InputLabel InputLabelX MLMS')
_gbcf: float = 1.0/(1024*1024*1024)
_sensor_details = {GPU_Vendor.AMD: {
'HWMON': {
'power': {'type': SensorType.SingleParam,
'cf': 0.000001, 'sensor': ['power1_average']},
'power_cap': {'type': SensorType.SingleParam,
'cf': 0.000001, 'sensor': ['power1_cap']},
'power_cap_range': {'type': SensorType.MinMax,
'cf': 0.000001, 'sensor': ['power1_cap_min', 'power1_cap_max']},
'fan_enable': {'type': SensorType.SingleParam,
'cf': 1, 'sensor': ['fan1_enable']},
'fan_target': {'type': SensorType.SingleParam,
'cf': 1, 'sensor': ['fan1_target']},
'fan_speed': {'type': SensorType.SingleParam,
'cf': 1, 'sensor': ['fan1_input']},
'fan_speed_range': {'type': SensorType.MinMax,
'cf': 1, 'sensor': ['fan1_min', 'fan1_max']},
'pwm_mode': {'type': SensorType.SingleParam,
'cf': 1, 'sensor': ['pwm1_enable']},
'fan_pwm': {'type': SensorType.SingleParam,
'cf': 0.39216, 'sensor': ['pwm1']},
'fan_pwm_range': {'type': SensorType.MinMax,
'cf': 0.39216, 'sensor': ['pwm1_min', 'pwm1_max']},
'temp_crits': {'type': SensorType.InputLabelX,
'cf': 0.001, 'sensor': ['temp*_crit']},
'frequencies': {'type': SensorType.InputLabelX,
'cf': 0.000001, 'sensor': ['freq*_input']},
'voltages': {'type': SensorType.InputLabelX,
'cf': 1, 'sensor': ['in*_input']},
'temperatures': {'type': SensorType.InputLabelX,
'cf': 0.001, 'sensor': ['temp*_input']},
'vddgfx': {'type': SensorType.InputLabelX,
'cf': 0.001, 'sensor': ['in*_input']}},
'DEVICE': {
'id': {'type': SensorType.MLMS,
'cf': None, 'sensor': ['vendor', 'device',
'subsystem_vendor', 'subsystem_device']},
'unique_id': {'type': SensorType.SingleString,
'cf': None, 'sensor': ['unique_id']},
'loading': {'type': SensorType.SingleParam,
'cf': 1, 'sensor': ['gpu_busy_percent']},
'mem_loading': {'type': SensorType.SingleParam,
'cf': 1, 'sensor': ['mem_busy_percent']},
'mem_vram_total': {'type': SensorType.SingleParam,
'cf': _gbcf, 'sensor': ['mem_info_vram_total']},
'mem_vram_used': {'type': SensorType.SingleParam,
'cf': _gbcf, 'sensor': ['mem_info_vram_used']},
'mem_gtt_total': {'type': SensorType.SingleParam,
'cf': _gbcf, 'sensor': ['mem_info_gtt_total']},
'mem_gtt_used': {'type': SensorType.SingleParam,
'cf': _gbcf, 'sensor': ['mem_info_gtt_used']},
'link_spd': {'type': SensorType.SingleString,
'cf': None, 'sensor': ['current_link_speed']},
'link_wth': {'type': SensorType.SingleString,
'cf': None, 'sensor': ['current_link_width']},
'sclk_ps': {'type': SensorType.MLSS,
'cf': None, 'sensor': ['pp_dpm_sclk']},
'mclk_ps': {'type': SensorType.MLSS,
'cf': None, 'sensor': ['pp_dpm_mclk']},
'power_dpm_force': {'type': SensorType.SingleString,
'cf': None,
'sensor': ['power_dpm_force_performance_level']},
'ppm': {'type': SensorType.SingleStringSelect,
'cf': None, 'sensor': ['pp_power_profile_mode']},
'vbios': {'type': SensorType.SingleString,
'cf': None, 'sensor': ['vbios_version']}}},
GPU_Vendor.PCIE: {
'DEVICE': {
'id': {'type': SensorType.MLMS,
'cf': None, 'sensor': ['vendor', 'device',
'subsystem_vendor',
'subsystem_device']}}}}
nv_query_items = {SensorSet.Static: {
'power_cap': ['power.limit'],
'power_cap_range': ['power.min_limit', 'power.max_limit'],
'mem_vram_total': ['memory.total'],
'frequencies_max': ['clocks.max.gr', 'clocks.max.sm', 'clocks.max.mem'],
'vbios': ['vbios_version'],
'compute_mode': ['compute_mode'],
'driver': ['driver_version'],
'model': ['name'],
'serial_number': ['serial'],
'card_index': ['index'],
'unique_id': ['gpu_uuid']},
SensorSet.Dynamic: {
'power': ['power.draw'],
'temperatures': ['temperature.gpu', 'temperature.memory'],
'frequencies': ['clocks.gr', 'clocks.sm', 'clocks.mem', 'clocks.video'],
'loading': ['utilization.gpu'],
'mem_loading': ['utilization.memory'],
'mem_vram_used': ['memory.used'],
'fan_speed': ['fan.speed'],
'ppm': ['gom.current'],
'link_wth': ['pcie.link.width.current'],
'link_spd': ['pcie.link.gen.current'],
'pstates': ['pstate']},
SensorSet.Monitor: {
'power': ['power.draw'],
'power_cap': ['power.limit'],
'temperatures': ['temperature.gpu'],
'frequencies': ['clocks.gr', 'clocks.mem'],
'loading': ['utilization.gpu'],
'mem_loading': ['utilization.memory'],
'mem_vram_used': ['memory.used'],
'fan_speed': ['fan.speed'],
'ppm': ['gom.current'],
'pstates': ['pstate']},
SensorSet.All: {
'power_cap': ['power.limit'],
'power_cap_range': ['power.min_limit', 'power.max_limit'],
'mem_vram_total': ['memory.total'],
'vbios': ['vbios_version'],
'driver': ['driver_version'],
'compute_mode': ['compute_mode'],
'model': ['name'],
'serial_number': ['serial'],
'card_index': ['index'],
'unique_id': ['gpu_uuid'],
'power': ['power.draw'],
'temperatures': ['temperature.gpu', 'temperature.memory'],
'frequencies': ['clocks.gr', 'clocks.sm', 'clocks.mem', 'clocks.video'],
'frequencies_max': ['clocks.max.gr', 'clocks.max.sm', 'clocks.max.mem'],
'loading': ['utilization.gpu'],
'mem_loading': ['utilization.memory'],
'mem_vram_used': ['memory.used'],
'fan_speed': ['fan.speed'],
'ppm': ['gom.current'],
'link_wth': ['pcie.link.width.current'],
'link_spd': ['pcie.link.gen.current'],
'pstates': ['pstate']}}
def __repr__(self) -> Dict[str, Any]:
"""
Return dictionary representing all parts of the GpuItem object.
:return: Dictionary of core GPU parameters.
"""
return {'params': self.prm, 'clinfo': self.clinfo,
'sclk_state': self.sclk_state, 'mclk_state': self.mclk_state,
'vddc_curve': self.vddc_curve, 'vddc_curve_range': self.vddc_curve_range,
'ppm_modes': self.ppm_modes}
def __str__(self) -> str:
"""
Return simple string representing the GpuItem object.
:return: GPU_item informational string
"""
return 'GPU_Item: uuid={}'.format(self.prm.uuid)
def __init__(self, item_id: str):
"""
Initialize GpuItem object.
:param item_id: UUID of the new item.
"""
time_0 = env.GUT_CONST.now(env.GUT_CONST.USELTZ)
self.validated_sensors: bool = False
self.energy: Dict[str, Any] = {'t0': time_0, 'tn': time_0, 'cumulative': 0.0}
self.read_disabled: List[str] = [] # List of parameters that failed during read.
self.write_disabled: List[str] = [] # List of parameters that failed during write.
self.prm: ObjDict = ObjDict({
'uuid': item_id,
'unique_id': '',
'card_num': None,
'pcie_id': '',
'driver': '',
'vendor': self.GPU_Vendor.Undefined,
'readable': False,
'writable': False,
'compute': False,
'compute_platform': None,
'compute_mode': None,
'gpu_type': self.GPU_Type.Undefined,
'id': {'vendor': '', 'device': '', 'subsystem_vendor': '', 'subsystem_device': ''},
'model_device_decode': 'UNDETERMINED',
'model': '',
'model_display': '',
'serial_number': '',
'card_index': '',
'card_path': '',
'sys_card_path': '',
'hwmon_path': '',
'energy': 0.0,
'power': None,
'power_cap': None,
'power_cap_range': [None, None],
'fan_enable': None,
'pwm_mode': [None, 'UNK'],
'fan_pwm': None,
'fan_speed': None,
'fan_speed_range': [None, None],
'fan_pwm_range': [None, None],
'fan_target': None,
'temp_crits': None,
'vddgfx': None,
'vddc_range': ['', ''],
'temperatures': None,
'voltages': None,
'frequencies': None,
'frequencies_max': None,
'loading': None,
'mem_loading': None,
'mem_vram_total': None,
'mem_vram_used': None,
'mem_vram_usage': None,
'mem_gtt_total': None,
'mem_gtt_used': None,
'mem_gtt_usage': None,
'pstate': None,
'mclk_ps': ['', ''],
'mclk_f_range': ['', ''],
'mclk_mask': '',
'sclk_ps': ['', ''],
'sclk_f_range': ['', ''],
'sclk_mask': '',
'link_spd': '',
'link_wth': '',
'ppm': '',
'power_dpm_force': '',
'vbios': ''})
self.clinfo: ObjDict = ObjDict({
'device_name': '',
'device_version': '',
'driver_version': '',
'opencl_version': '',
'pcie_id': '',
'max_cu': '',
'simd_per_cu': '',
'simd_width': '',
'simd_ins_width': '',
'max_mem_allocation': '',
'max_wi_dim': '',
'max_wi_sizes': '',
'max_wg_size': '',
'prf_wg_size': '',
'prf_wg_multiple': ''})
self.sclk_dpm_state: Dict[int, str] = {} # {1: 'Mhz'}
self.mclk_dpm_state: Dict[int, str] = {} # {1: 'Mhz'}
self.sclk_state: Dict[int, List[str]] = {} # {1: ['Mhz', 'mV']}
self.mclk_state: Dict[int, List[str]] = {} # {1: ['Mhz', 'mV']}
self.vddc_curve: Dict[int, List[str]] = {} # {1: ['Mhz', 'mV']}
self.vddc_curve_range: Dict[int, dict] = {} # {1: {'SCLK': ['val1', 'val2'], 'VOLT': ['val1', 'val2']}
self.ppm_modes: Dict[str, List[str]] = {} # {'1': ['Name', 'Description']}
self.finalize_fan_option()
@classmethod
def finalize_fan_option(cls) -> None:
"""
Finalize class variables of gpu parameters based on command line options. This must be
done after setting of env. Doing at at the instantiation of a GpuItem assures that.
"""
if cls._finalized:
return
cls.finalized = True
if not env.GUT_CONST.show_fans:
for fan_item in cls._fan_item_list:
# Remove fan params from GPU_Param_Labels
if fan_item in cls._GPU_Param_Labels.keys():
del cls._GPU_Param_Labels[fan_item]
# Remove fan params from Table_Param_Labels
if fan_item in cls.table_param_labels.keys():
del cls.table_param_labels[fan_item]
# Remove fan params from SensorSets
if fan_item in cls.sensor_sets[cls.SensorSet.Static]['HWMON']:
cls.sensor_sets[cls.SensorSet.Static]['HWMON'].remove(fan_item)
if fan_item in cls.sensor_sets[cls.SensorSet.Dynamic]['HWMON']:
cls.sensor_sets[cls.SensorSet.Dynamic]['HWMON'].remove(fan_item)
if fan_item in cls.sensor_sets[cls.SensorSet.Monitor]['HWMON']:
cls.sensor_sets[cls.SensorSet.Monitor]['HWMON'].remove(fan_item)
if fan_item in cls.sensor_sets[cls.SensorSet.All]['HWMON']:
cls.sensor_sets[cls.SensorSet.All]['HWMON'].remove(fan_item)
# Remove fan params from table param list
if fan_item in cls.table_parameters:
cls.table_parameters.remove(fan_item)
@classmethod
def is_apu(cls, name: str) -> bool:
"""
Check if given GPU name is an APU.
:param name: Target GPU name
:return: True if name matches APU name
"""
if not name:
return False
for apu_name in cls._apu_gpus:
if re.search(apu_name, name, re.IGNORECASE):
return True
return False
@classmethod
def get_button_label(cls, name: str) -> str:
"""
Return button label for given parameter name.
:param name: Parameter name
:return: Button label
"""
if name not in cls._button_labels.keys():
raise KeyError('{} not in button_label dict'.format(name))
return cls._button_labels[name]
def set_params_value(self, name: str, value: Union[int, float, str, list, None]) -> None:
"""
Set parameter value for give name.
:param name: Parameter name
:param value: parameter value
"""
if isinstance(value, tuple):
self.prm[name] = list(value)
elif name == 'pwm_mode':
self.prm[name][0] = value
if value == 0: self.prm[name][1] = 'None'
elif value == 1: self.prm[name][1] = 'Manual'
else: self.prm[name][1] = 'Dynamic'
elif name == 'ppm':
self.prm[name] = re.sub(PATTERNS['PPM_CHK'], '', value).strip()
self.prm[name] = re.sub(PATTERNS['PPM_NOTCHK'], '-', self.prm[name])
elif name == 'power':
time_n = env.GUT_CONST.now(env.GUT_CONST.USELTZ)
self.prm[name] = value
delta_hrs = ((time_n - self.energy['tn']).total_seconds()) / 3600
self.energy['tn'] = time_n
self.energy['cumulative'] += delta_hrs * value / 1000
self.prm['energy'] = round(self.energy['cumulative'], 6)
elif name == 'sclk_ps':
mask = ''
ps_key = 'NA'
for ps_val in value:
if not mask:
mask = ps_val.split(':')[0].strip()
else:
mask += ',' + ps_val.split(':')[0].strip()
sclk_ps = ps_val.strip('*').strip().split(': ')
if sclk_ps[0].isnumeric():
ps_key = int(sclk_ps[0])
self.sclk_dpm_state.update({ps_key: sclk_ps[1]})
if '*' in ps_val:
self.prm.sclk_ps[0] = ps_key
self.prm.sclk_ps[1] = sclk_ps[1]
self.prm.sclk_mask = mask
LOGGER.debug('Mask: [%s], ps: [%s, %s]', mask, self.prm.sclk_ps[0], self.prm.sclk_ps[1])
elif name == 'mclk_ps':
mask = ''
ps_key = 'NA'
for ps_val in value:
if not mask:
mask = ps_val.split(':')[0].strip()
else:
mask += ',' + ps_val.split(':')[0].strip()
mclk_ps = ps_val.strip('*').strip().split(': ')
if mclk_ps[0].isnumeric():
ps_key = int(mclk_ps[0])
self.mclk_dpm_state.update({ps_key: mclk_ps[1]})
if '*' in ps_val:
self.prm.mclk_ps[0] = ps_key
self.prm.mclk_ps[1] = mclk_ps[1]
self.prm.mclk_mask = mask
LOGGER.debug('Mask: [%s], ps: [%s, %s]', mask, self.prm.mclk_ps[0], self.prm.mclk_ps[1])
elif name == 'fan_pwm':
if isinstance(value, int):
self.prm.fan_pwm = value
elif isinstance(value, float):
self.prm.fan_pwm = int(value)
elif isinstance(value, str):
self.prm.fan_pwm = int(value) if value.isnumeric() else None
else:
self.prm.fan_pwm = None
elif re.fullmatch(PATTERNS['GPUMEMTYPE'], name):
self.prm[name] = value
self.set_memory_usage()
elif name == 'id':
self.prm.id = dict(zip(['vendor', 'device', 'subsystem_vendor', 'subsystem_device'], list(value)))
self.prm.model_device_decode = self.read_pciid_model()
self.prm.model_display = self.fit_display_name(self.prm.model_device_decode)
else:
self.prm[name] = value
@staticmethod
def fit_display_name(name: str, length: int = env.GUT_CONST.mon_field_width) -> str:
"""
Convert the given name to a display name which is optimally simplified and truncated.
:param name: The GPU name to be converted.
:param length: The target length, default is the monitor field width.
:return: Simplified and truncated string
"""
fit_name = ''
model_display_components = re.sub(PATTERNS['GPU_GENERIC'], '', name).split()
for name_component in model_display_components:
if len(name_component) + len(fit_name) + 1 > length:
break
fit_name = re.sub(r'\s*/\s*', '/', '{} {}'.format(fit_name, name_component))
return fit_name
def get_params_value(self, name: str, num_as_int: bool = False) -> Union[int, float, str, list, None]:
"""
Get parameter value for given name.
:param name: Parameter name
:param num_as_int: Convert float to in if True
:return: Parameter value
"""
# Parameters with '_val' as a suffix are derived from a direct source.
if re.fullmatch(PATTERNS['VAL_ITEM'], name):
if self.prm.gpu_type == self.GPU_Type.Legacy:
return None
if name == 'temp_val':
if not self.prm['temperatures']:
return None
for temp_name in ['edge', 'temperature.gpu', 'temp1_input']:
if temp_name in self.prm['temperatures'].keys():
if num_as_int:
return int(self.prm['temperatures'][temp_name])
return round(self.prm['temperatures'][temp_name], 1)
for value in self.prm['temperatures'].values():
return value
# return list(self.prm['temperatures'].keys())[0] - Not sure what I was doing here
return None
if name == 'vddgfx_val':
if not self.prm['voltages']:
return np_nan
if 'vddgfx' not in self.prm['voltages']:
return np_nan
return int(self.prm['voltages']['vddgfx'])
if name == 'sclk_ps_val':
return self.prm['sclk_ps'][0]
if name == 'sclk_f_val':
if not self.prm['frequencies']:
return None
for clock_name in ['sclk', 'clocks.gr']:
if clock_name in self.prm['frequencies'].keys():
return int(self.prm['frequencies'][clock_name])
return self.prm['sclk_ps'][1]
if name == 'mclk_ps_val':
return self.prm['mclk_ps'][0]
if name == 'mclk_f_val':
if not self.prm['frequencies']:
return None
for clock_name in ['mclk', 'clocks.mem']:
if clock_name in self.prm['frequencies'].keys():
return int(self.prm['frequencies'][clock_name])
return self.prm['mclk_ps'][1]
# Set type for params that could be float or int
if name in ['fan_pwm', 'fan_speed', 'power_cap', 'power']:
if num_as_int:
if isinstance(self.prm[name], int):
return self.prm[name]
if isinstance(self.prm[name], float):
return int(self.prm[name])
if isinstance(self.prm[name], str):
return int(self.prm[name]) if self.prm[name].isnumeric() else None
return self.prm[name]
return self.prm[name]
def set_memory_usage(self) -> None:
"""
Set system and vram memory usage percentage.
:return: A tuple of the system and vram memory usage percentage.
"""
if self.prm.mem_gtt_used is None or self.prm.mem_gtt_total is None:
self.prm.mem_gtt_usage = None
else:
self.prm.mem_gtt_usage = 100.0 * self.prm.mem_gtt_used / self.prm.mem_gtt_total
if self.prm.mem_vram_used is None or self.prm.mem_vram_total is None:
self.prm.mem_vram_usage = None
else:
self.prm.mem_vram_usage = 100.0 * self.prm.mem_vram_used / self.prm.mem_vram_total
def read_pciid_model(self) -> str:
"""
Read the model name from the system pcid.ids file
:return: GPU model name
"""
if not env.GUT_CONST.sys_pciid:
message = 'Error: pciid file not defined'
print(message)
LOGGER.debug(message)
return ''
if not os.path.isfile(env.GUT_CONST.sys_pciid):
message = 'Error: Can not access system pci.ids file [{}]'.format(env.GUT_CONST.sys_pciid)
print(message)
LOGGER.debug(message)
return ''
with open(env.GUT_CONST.sys_pciid, 'r', encoding='utf8') as pci_id_file_ptr:
model_str = ''
level = 0
for line_item in pci_id_file_ptr:
line = line_item.rstrip()
if len(line) < 4:
continue
if line[0] == '#':
continue
if level == 0:
if re.fullmatch(PATTERNS['PCIIID_L0'], line):
if line[:4] == self.prm.id['vendor'].replace('0x', ''):
level += 1
continue
elif level == 1:
if re.fullmatch(PATTERNS['PCIIID_L0'], line):
break
if re.fullmatch(PATTERNS['PCIIID_L1'], line):
if line[1:5] == self.prm.id['device'].replace('0x', ''):
model_str = line[5:]
level += 1
continue
elif level == 2:
if re.fullmatch(PATTERNS['PCIIID_L0'], line):
break
if re.fullmatch(PATTERNS['PCIIID_L1'], line):
break
if re.fullmatch(PATTERNS['PCIIID_L2'], line):
if line[2:6] == self.prm.id['subsystem_vendor'].replace('0x', ''):
if line[7:11] == self.prm.id['subsystem_device'].replace('0x', ''):
model_str = line[11:]
break
return model_str.strip()
def populate_prm_from_dict(self, params: Dict[str, any]) -> None:
"""
Populate elements of a GpuItem with items from a dict with keys that align to elements of GpuItem.
:param params: A dictionary of parameters with keys that align to GpuItem elements.
"""
LOGGER.debug('prm dict:\n%s', params)
set_ocl_ver = None
for source_name, source_value in params.items():
# Set primary parameter
if source_name not in self.prm.keys():
raise KeyError('Populate dict contains unmatched key: {}'.format(source_name))
self.prm[source_name] = source_value
# Set secondary parameters
if source_name == 'card_path' and source_value:
card_num_str = source_value.replace('{}card'.format(env.GUT_CONST.card_root), '').replace('/device', '')
self.prm.card_num = int(card_num_str) if card_num_str.isnumeric() else None
elif source_name == 'compute_platform':
set_ocl_ver = source_value
elif source_name == 'gpu_type' and source_value:
self.prm.gpu_type = source_value
if source_value == GpuItem.GPU_Type.Legacy:
self.read_disabled = GpuItem.LEGACY_Skip_List[:]
elif source_value == GpuItem.GPU_Type.APU:
self.read_disabled = GpuItem._fan_item_list[:]
# compute platform requires that the compute bool be set first
if set_ocl_ver:
self.prm.compute_platform = set_ocl_ver if self.prm.compute else 'None'
def populate_ocl(self, ocl_dict: dict) -> None:
"""
Populate ocl parameters in GpuItem.
:param ocl_dict: Dictionary of parameters for specific pcie_id
"""
for ocl_name, ocl_val in ocl_dict.items():
if ocl_name in self.clinfo.keys():
self.set_clinfo_value(ocl_name, ocl_val)
def set_clinfo_value(self, name: str, value: Union[int, str, list]) -> None:
"""
Set clinfo values in GPU item dictionary.
:param name: clinfo parameter name
:param value: parameter value
"""
self.clinfo[name] = value
def get_clinfo_value(self, name: str) -> Union[int, str, list]:
"""
Get clinfo parameter value for give name.
:param name: clinfo Parameter name
:return: clinfo Parameter value
.. note: Maybe not needed
"""
return self.clinfo[name]
def get_nc_params_list(self) -> List[str]:
"""
Get list of parameter names for use with non-compatible cards.
:return: List of parameter names
"""
return self._GPU_NC_Param_List
def is_valid_power_cap(self, power_cap: int) -> bool:
"""
Check if a given power_cap value is valid.
:param power_cap: Target power cap value to be tested.
:return: True if valid
"""
power_cap_range = self.prm.power_cap_range
if power_cap_range[0] <= power_cap <= power_cap_range[1]:
return True
if power_cap < 0:
# negative values will be interpreted as reset request
return True
return False
def is_valid_fan_pwm(self, pwm_value: int) -> bool:
"""
Check if a given fan_pwm value is valid.
:param pwm_value: Target fan_pwm value to be tested.
:return: True if valid
"""
pwm_range = self.prm.fan_pwm_range
if pwm_range[0] <= pwm_value <= pwm_range[1]:
return True
if pwm_value < 0:
# negative values will be interpreted as reset request
return True
return False
def is_valid_mclk_pstate(self, pstate: List[int]) -> bool:
"""
Check if given mclk pstate value is valid.
:param pstate: pstate = [pstate_number, clk_value, vddc_value]
:return: Return True if valid
"""
mclk_range = self.prm.mclk_f_range
mclk_min = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(mclk_range[0])))
mclk_max = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(mclk_range[1])))
if pstate[1] < mclk_min or pstate[1] > mclk_max:
return False
if self.prm.gpu_type in [self.GPU_Type.PStatesNE, self.GPU_Type.PStates]:
vddc_range = self.prm.vddc_range
vddc_min = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(vddc_range[0])))
vddc_max = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(vddc_range[1])))
if pstate[2] < vddc_min or pstate[2] > vddc_max:
return False
return True
def is_valid_sclk_pstate(self, pstate: List[int]) -> bool:
"""
Check if given sclk pstate value is valid.
:param pstate: pstate = [pstate_number, clk_value, vddc_value]
:return: Return True if valid
"""
sclk_range = self.prm.sclk_f_range
sclk_min = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(sclk_range[0])))
sclk_max = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(sclk_range[1])))
if pstate[1] < sclk_min or pstate[1] > sclk_max:
return False
if self.prm.gpu_type in [self.GPU_Type.PStatesNE, self.GPU_Type.PStates]:
vddc_range = self.prm.vddc_range
vddc_min = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(vddc_range[0])))
vddc_max = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(vddc_range[1])))
if pstate[2] < vddc_min or pstate[2] > vddc_max:
return False
return True
def is_changed_sclk_pstate(self, pstate: List[int]) -> bool:
"""
Check if given sclk pstate value different from current.
:param pstate: pstate = [pstate_number, clk_value, vddc_value]
:return: Return True if changed
"""
if int(re.sub(PATTERNS['END_IN_ALPHA'], '', self.sclk_state[pstate[0]][0])) != pstate[1]:
return True
if self.prm.gpu_type in [self.GPU_Type.PStatesNE, self.GPU_Type.PStates]:
if int(re.sub(PATTERNS['END_IN_ALPHA'], '', self.sclk_state[pstate[0]][1])) != pstate[2]:
return True
return False
def is_changed_mclk_pstate(self, pstate: List[int]) -> bool:
"""
Check if given mclk pstate value different from current.
:param pstate: pstate = [pstate_number, clk_value, vddc_value]
:return: Return True if changed
"""
if int(re.sub(PATTERNS['END_IN_ALPHA'], '', self.mclk_state[pstate[0]][0])) != pstate[1]:
return True
if self.prm.gpu_type in [self.GPU_Type.PStatesNE, self.GPU_Type.PStates]:
if int(re.sub(PATTERNS['END_IN_ALPHA'], '', self.mclk_state[pstate[0]][1])) != pstate[2]:
return True
return False
def is_changed_vddc_curve_pt(self, pstate: List[int]) -> bool:
"""
Check if given vddc curve point value different from current.
:param pstate: curve_point = [point_number, clk_value, vddc_value]
:return: Return True if changed
"""
if int(re.sub(PATTERNS['END_IN_ALPHA'], '', self.vddc_curve[pstate[0]][0])) != pstate[1]:
return True
if int(re.sub(PATTERNS['END_IN_ALPHA'], '', self.vddc_curve[pstate[0]][1])) != pstate[2]:
return True
return False
def is_valid_vddc_curve_pts(self, curve_pts: List[int]) -> bool:
"""
Check if given sclk pstate value is valid.
:param curve_pts: curve_point = [point_number, clk_value, vddc_value]
:return: Return True if valid
"""
sclk_min = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(self.vddc_curve_range[curve_pts[0]]['SCLK'][0])))
sclk_max = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(self.vddc_curve_range[curve_pts[0]]['SCLK'][1])))
if curve_pts[1] < sclk_min or curve_pts[1] > sclk_max:
return False
vddc_min = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str('650mV')))
vddc_max = int(re.sub(PATTERNS['END_IN_ALPHA'], '', str(self.vddc_curve_range[curve_pts[0]]['VOLT'][1])))
if curve_pts[2] < vddc_min or curve_pts[2] > vddc_max:
return False
return True
def is_valid_pstate_list_str(self, ps_str: str, clk_name: str) -> bool:
"""
Check if the given p-states are valid for the given clock.
:param ps_str: String of comma separated pstate numbers
:param clk_name: The target clock name
:return: True if valid
"""
if ps_str == '':
return True
if not re.fullmatch(PATTERNS['VALID_PS_STR'], ps_str):
return False
ps_list = self.prm.mclk_mask.split(',') if clk_name == 'MCLK' else self.prm.sclk_mask.split(',')
for ps_val in ps_str.split():
if ps_val not in ps_list:
return False
return True
def get_current_ppm_mode(self) -> Union[None, List[Union[int, str]]]:
"""
Read GPU ppm definitions and current settings from driver files.
:return: ppm state
:rtype: list
"""
if self.prm.vendor != GpuItem.GPU_Vendor.AMD:
return None
if self.prm.power_dpm_force.lower() == 'auto':
return [-1, 'AUTO']
ppm_item = self.prm.ppm.split('-')
return [int(ppm_item[0]), ppm_item[1]]
def read_gpu_ppm_table(self) -> None:
"""
Read the ppm table.
"""
if self.prm.vendor != GpuItem.GPU_Vendor.AMD:
return
if not self.prm.readable or self.prm.gpu_type in [GpuItem.GPU_Type.Legacy, GpuItem.GPU_Type.Unsupported]:
return
file_path = os.path.join(self.prm.card_path, 'pp_power_profile_mode')
if not os.path.isfile(file_path):
print('Error getting power profile modes: {}'.format(file_path), file=sys.stderr)
sys.exit(-1)
with open(file_path) as card_file:
for line in card_file:
linestr = line.strip()
# Check for mode name: begins with '[ ]+[0-9].*'
if re.fullmatch(r'[ ]+[0-9].*', line[0:3]):
linestr = re.sub(r'[ ]*[*]*:', ' ', linestr)
line_items = linestr.split()
LOGGER.debug('PPM line: %s', linestr)
if len(line_items) < 2:
print('Error: invalid ppm: {}'.format(linestr), file=sys.stderr)
continue
LOGGER.debug('Valid ppm line: %s', linestr)
self.ppm_modes[line_items[0]] = line_items[1:]
self.ppm_modes['-1'] = ['AUTO', 'Auto']
rdata = self.read_gpu_sensor('power_dpm_force', vendor=GpuItem.GPU_Vendor.AMD, sensor_type='DEVICE')
if rdata is False:
message = 'Error: card file does not exist: {}'.format(file_path)
print(message, file=sys.stderr)
LOGGER.debug(message)
self.prm.readable = False
else:
self.set_params_value('power_dpm_force', rdata)
def read_gpu_pstates(self) -> None:
"""
Read GPU pstate definitions and parameter ranges from driver files.
Set card type based on pstate configuration
"""
if self.prm.vendor != GpuItem.GPU_Vendor.AMD:
return
if not self.prm.readable or self.prm.gpu_type in [GpuItem.GPU_Type.Legacy,
GpuItem.GPU_Type.Unsupported,
GpuItem.GPU_Type.APU]:
return
range_mode = False
file_path = os.path.join(self.prm.card_path, 'pp_od_clk_voltage')
if not os.path.isfile(file_path):
print('Error getting p-states: {}'.format(file_path), file=sys.stderr)
self.prm.readable = False
return
with open(file_path) as card_file:
for line in card_file:
line = line.strip()
if re.fullmatch('OD_.*:$', line):
if re.fullmatch('OD_.CLK:$', line):
clk_name = line.strip()
elif re.fullmatch('OD_VDDC_CURVE:$', line):
clk_name = line.strip()
elif re.fullmatch('OD_RANGE:$', line):
clk_name = ''
range_mode = True
continue
line = re.sub(r'@', ' ', line)
lineitems: List[any] = line.split()
lineitems_len = len(lineitems)
if self.prm.gpu_type in [self.GPU_Type.Undefined, self.GPU_Type.Supported]:
if len(lineitems) == 3:
self.prm.gpu_type = self.GPU_Type.PStates
elif len(lineitems) == 2:
self.prm.gpu_type = self.GPU_Type.CurvePts
else:
print('Error: Invalid pstate entry length {} for{}: '.format(lineitems_len,
os.path.join(self.prm.card_path, 'pp_od_clk_voltage')), file=sys.stderr)
LOGGER.debug('Invalid line length for pstate line item: %s', line)
continue
if not range_mode:
lineitems[0] = int(re.sub(':', '', lineitems[0]))
if self.prm.gpu_type in [self.GPU_Type.PStatesNE, self.GPU_Type.PStates]:
if clk_name == 'OD_SCLK:':
self.sclk_state[lineitems[0]] = [lineitems[1], lineitems[2]]
elif clk_name == 'OD_MCLK:':
self.mclk_state[lineitems[0]] = [lineitems[1], lineitems[2]]
else:
# Type GPU_Type.CurvePts
if clk_name == 'OD_SCLK:':
self.sclk_state[lineitems[0]] = [lineitems[1], '-']
elif clk_name == 'OD_MCLK:':
self.mclk_state[lineitems[0]] = [lineitems[1], '-']
elif clk_name == 'OD_VDDC_CURVE:':
self.vddc_curve[lineitems[0]] = [lineitems[1], lineitems[2]]
else:
if lineitems[0] == 'SCLK:':
self.prm.sclk_f_range = [lineitems[1], lineitems[2]]
elif lineitems[0] == 'MCLK:':
self.prm.mclk_f_range = [lineitems[1], lineitems[2]]
elif lineitems[0] == 'VDDC:':
self.prm.vddc_range = [lineitems[1], lineitems[2]]
elif re.fullmatch('VDDC_CURVE_.*', line):
if len(lineitems) == 3:
index = re.sub(r'VDDC_CURVE_.*\[', '', lineitems[0])
index = re.sub(r'\].*', '', index)
if not index.isnumeric():
print('Error: Invalid index for line item: {}'.format(line))
LOGGER.debug('Invalid index for pstate line item: %s', line)
continue
index = int(index)
param = re.sub(r'VDDC_CURVE_', '', lineitems[0])
param = re.sub(r'\[[0-9]\]:', '', param)
LOGGER.debug('Curve: index: %s param: %s, val1 %s, val2: %s',
index, param, lineitems[1], lineitems[2])
if index in self.vddc_curve_range.keys():
self.vddc_curve_range[index].update({param: [lineitems[1], lineitems[2]]})
else:
self.vddc_curve_range[index] = {}
self.vddc_curve_range[index].update({param: [lineitems[1], lineitems[2]]})
else:
print('Error: Invalid CURVE entry: {}'.format(file_path), file=sys.stderr)
def read_gpu_sensor(self, parameter: str, vendor: GpuEnum = GPU_Vendor.AMD,
sensor_type: str = 'HWMON') -> Union[None, bool, int, str, tuple, list, dict]:
"""
Read sensor for the given parameter name. Process per sensor_details dict using the specified
vendor name and sensor_type.
:param parameter: GpuItem parameter name (AMD)
:param vendor: GPU vendor name enum object
:param sensor_type: GPU sensor name (HWMON or DEVICE)
:return: Value from reading sensor.
"""
if vendor in [self.GPU_Vendor.AMD, self.GPU_Vendor.PCIE]:
return self.read_gpu_sensor_generic(parameter, vendor, sensor_type)
if vendor == self.GPU_Vendor.NVIDIA:
return self.read_gpu_sensor_nv(parameter)
print('Error: Invalid vendor [{}]'.format(vendor))
return None
def read_gpu_sensor_nv(self, parameter: str) -> Union[None, bool, int, str, tuple, list, dict]:
"""
Function to read a single sensor from NV GPU.
:param parameter: Target parameter for reading
:return: read results
"""
if parameter in self.read_disabled:
return False
cmd_str = '{} -i {} --query-gpu={} --format=csv,noheader,nounits'.format(
env.GUT_CONST.cmd_nvidia_smi, self.prm.pcie_id, parameter)
LOGGER.debug('NV command:\n%s', cmd_str)
nsmi_item = None
try:
nsmi_item = subprocess.check_output(shlex.split(cmd_str), shell=False).decode().split('\n')
LOGGER.debug('NV raw query response: [%s]', nsmi_item)
except (subprocess.CalledProcessError, OSError) as except_err:
LOGGER.debug('NV query %s error: [%s]', nsmi_item, except_err)
self.read_disabled.append(parameter)
return False
return_item = nsmi_item[0].strip() if nsmi_item else None
LOGGER.debug('NV query result: [%s]', return_item)
return return_item
def read_gpu_sensor_generic(self, parameter: str, vendor: GpuEnum = GPU_Vendor.AMD,
sensor_type: str = 'HWMON') -> Union[None, bool, int, str, tuple, list, dict]:
"""
Read sensor for the given parameter name. Process per sensor_details dict using the specified
vendor name and sensor_type.
:param parameter: GpuItem parameter name (AMD)
:param vendor: GPU vendor name enum object
:param sensor_type: GPU sensor name (HWMON or DEVICE)
:return: Value from reading sensor.
"""
if self.prm.gpu_type in [GpuItem.GPU_Type.Unsupported] and parameter != 'id':
return None
if not self.prm.readable and parameter != 'id':
return None
if sensor_type not in self._sensor_details[vendor].keys():
print('Error: Invalid sensor_type [{}]'.format(sensor_type))
return None
sensor_dict = self._sensor_details[vendor][sensor_type]
if parameter not in sensor_dict.keys():
print('Error: Invalid parameter [{}]'.format(parameter))
return None
if parameter in self.read_disabled:
return None
device_sensor_path = self.prm.card_path if self.prm.card_path else self.prm.sys_card_path
LOGGER.debug('sensor path set to [%s]', device_sensor_path)
sensor_path = self.prm.hwmon_path if sensor_type == 'HWMON' else device_sensor_path
values = []
ret_value = []
ret_dict = {}
target_sensor = sensor_dict[parameter]
if target_sensor['type'] == self.SensorType.InputLabelX:
sensor_files = glob.glob(os.path.join(sensor_path, target_sensor['sensor'][0]))
else:
sensor_files = target_sensor['sensor']
for sensor_file in sensor_files:
file_path = os.path.join(sensor_path, sensor_file)
if os.path.isfile(file_path):
try:
with open(file_path) as hwmon_file:
if target_sensor['type'] in [self.SensorType.SingleStringSelect, self.SensorType.MLSS]:
lines = hwmon_file.readlines()
for line in lines:
values.append(line.strip())
else:
values.append(hwmon_file.readline().strip())
if target_sensor['type'] == self.SensorType.InputLabelX:
if '_input' in file_path:
file_path = file_path.replace('_input', '_label')
elif '_crit' in file_path:
file_path = file_path.replace('_crit', '_label')
else:
print('Error in sensor label pair: {}'.format(target_sensor))
if os.path.isfile(file_path):
with open(file_path) as hwmon_file:
values.append(hwmon_file.readline().strip())
else:
values.append(os.path.basename(sensor_file))
except OSError as err:
LOGGER.debug('Exception [%s]: Can not read HW file: %s', err, file_path)
self.read_disabled.append(parameter)
return False
else:
LOGGER.debug('HW file does not exist: %s', file_path)
self.read_disabled.append(parameter)
return False
if target_sensor['type'] == self.SensorType.SingleParam:
if target_sensor['cf'] == 1:
return int(values[0])
return int(values[0]) * target_sensor['cf']
if target_sensor['type'] == self.SensorType.InputLabel:
ret_value.append(int(values[0]) * target_sensor['cf'])
ret_value.append(values[1])
return tuple(ret_value)
if target_sensor['type'] in [self.SensorType.MLSS, self.SensorType.MLMS]:
return values
if target_sensor['type'] == self.SensorType.MinMax:
ret_value.append(int(int(values[0]) * target_sensor['cf']))
ret_value.append(int(int(values[1]) * target_sensor['cf']))
return tuple(ret_value)
if target_sensor['type'] == self.SensorType.InputLabelX:
for i in range(0, len(values), 2):
ret_dict.update({values[i+1]: int(values[i]) * target_sensor['cf']})
return ret_dict
if target_sensor['type'] == self.SensorType.SingleStringSelect:
for item in values:
if '*' in item:
return item
return None
if target_sensor['type'] == self.SensorType.SingleString:
return values[0]
raise ValueError('Invalid sensor type: {}'.format(target_sensor['type']))
def read_gpu_sensor_set(self, data_type: Enum = SensorSet.All) -> bool:
"""
Read GPU sensor data from HWMON and DEVICE sensors using the sensor set defined
by data_type.
:param data_type: Specifies the sensor set: Dynamic, Static, Info, State, All Monitor
"""
if self.prm.vendor == self.GPU_Vendor.AMD:
return self.read_gpu_sensor_set_amd(data_type)
if self.prm.vendor == self.GPU_Vendor.NVIDIA:
return self.read_gpu_sensor_set_nv(data_type)
return False
def read_gpu_sensor_set_nv(self, data_type: Enum = SensorSet.All) -> bool:
"""
Use the nvidia_smi tool to query GPU parameters.
:param data_type: specifies the set of sensors to read
:return: True if successful, else False and card will have read disabled
"""
if data_type not in self.nv_query_items.keys():
raise TypeError('Invalid SensorSet value: [{}]'.format(data_type))
sensor_dict = GpuItem.nv_query_items[data_type]
nsmi_items = []
query_list = [item for sublist in sensor_dict.values() for item in sublist]
query_list = [item for item in query_list if item not in self.read_disabled]
if self.validated_sensors:
qry_string = ','.join(query_list)
cmd_str = '{} -i {} --query-gpu={} --format=csv,noheader,nounits'.format(
env.GUT_CONST.cmd_nvidia_smi, self.prm.pcie_id, qry_string)
LOGGER.debug('NV command:\n%s', cmd_str)
try:
nsmi_items = subprocess.check_output(shlex.split(cmd_str), shell=False).decode().split('\n')
LOGGER.debug('NV query (single-call) result: [%s]', nsmi_items)
except (subprocess.CalledProcessError, OSError) as except_err:
LOGGER.debug('NV query %s error: [%s]', nsmi_items, except_err)
return False
if nsmi_items:
nsmi_items = nsmi_items[0].split(',')
nsmi_items = [item.strip() for item in nsmi_items]
else:
# Read sensors one at a time if SensorSet.All has not been validated
if data_type == GpuItem.SensorSet.All:
self.validated_sensors = True
for query_item in query_list:
query_data = self.read_gpu_sensor_nv(query_item)
nsmi_items.append(query_data)
LOGGER.debug('NV query (each-call) query item [%s], result: [%s]', query_item, query_data)
if not nsmi_items:
LOGGER.debug('NV query (each-call) failed for all sensors, disabling read for card [%s]',
self.prm.card_num)
self.prm.readable = False
return False
results = dict(zip(query_list, nsmi_items))
LOGGER.debug('NV query result: %s', results)
# Populate GpuItem data from results dictionary
for param_name, sensor_list in sensor_dict.items():
if param_name == 'power_cap_range':
if results['power.min_limit'] and re.fullmatch(PATTERNS['IS_FLOAT'], results['power.min_limit']):
power_min = float(results['power.min_limit'])
else:
power_min = results['power.min_limit']
if results['power.max_limit'] and re.fullmatch(PATTERNS['IS_FLOAT'], results['power.max_limit']):
power_max = float(results['power.max_limit'])
else:
power_max = results['power.max_limit']
self.prm.power_cap_range = [power_min, power_max]
elif param_name == 'power':
if results['power.draw'] and re.fullmatch(PATTERNS['IS_FLOAT'], results['power.draw']):
power = float(results['power.draw'])
else:
power = None
self.set_params_value('power', power)
elif param_name == 'pstates':
pstate_str = re.sub(PATTERNS['ALPHA'], '', results['pstate'])
pstate = int(pstate_str) if pstate_str.isnumeric() else None
self.prm['sclk_ps'][0] = pstate
self.prm['mclk_ps'][0] = pstate
elif param_name in ['temperatures', 'voltages', 'frequencies', 'frequencies_max']:
self.prm[param_name] = {}
for sn_k in sensor_list:
if sn_k not in results: continue
if results[sn_k] and re.fullmatch(PATTERNS['IS_FLOAT'], results[sn_k]):
param_val = float(results[sn_k])
else:
param_val = None
self.prm[param_name].update({sn_k: param_val})
elif re.fullmatch(PATTERNS['GPUMEMTYPE'], param_name):
for sn_k in sensor_list:
if sn_k not in results: continue
mem_value = int(results[sn_k]) if results[sn_k].isnumeric else None
self.prm[param_name] = mem_value / 1024.0
self.set_memory_usage()
elif param_name == 'fan_speed':
sn_k = sensor_list[0]
if re.fullmatch(PATTERNS['IS_FLOAT'], results[sn_k]):
self.prm[param_name] = float(results[sn_k])
self.prm.fan_pwm = self.prm[param_name]
elif param_name == 'link_spd':
self.prm.link_spd = 'GEN{}'.format(results['pcie.link.gen.current'])
elif param_name == 'model':
self.prm.model = results['name']
self.prm.model_display = self.prm.model_device_decode
if results['name'] and len(results['name']) < len(self.prm.model_device_decode):
self.prm.model_display = results['name']
self.prm.model_display = self.fit_display_name(self.prm.model_display)
elif len(sensor_list) == 1:
sn_k = sensor_list[0]
if re.fullmatch(PATTERNS['IS_FLOAT'], results[sn_k]):
self.prm[param_name] = float(results[sn_k])
elif not results[sn_k]:
self.prm[param_name] = None
self.prm[param_name] = results[sn_k]
return True
def read_gpu_sensor_set_amd(self, data_type: Enum = SensorSet.All) -> bool:
"""
Read GPU sensor data from HWMON and DEVICE sensors using the sensor set defined
by data_type.
:param data_type: Specifies the sensor set: Dynamic, Static, Info, State, All Monitor
:return: True if successful
"""
if not self.prm.readable:
return False
return_status = False
param_list = self.sensor_sets[data_type]
for sensor_type, param_names in param_list.items():
for param in param_names:
LOGGER.debug('Processing parameter: %s', param)
rdata = self.read_gpu_sensor(param, vendor=self.prm.vendor, sensor_type=sensor_type)
if rdata is False:
if param != 'unique_id':
message = 'Warning: Can not read parameter: {}, ' \
'disabling for this GPU: {}'.format(param, self.prm.card_num)
LOGGER.debug(message)
print(message)
elif rdata is None:
LOGGER.debug('Read data [%s], Invalid or disabled parameter: %s', rdata, param)
else:
LOGGER.debug('Valid data [%s] for parameter: %s', rdata, param)
self.set_params_value(param, rdata)
return_status = True
return return_status
def print_ppm_table(self) -> None:
"""
Print human friendly table of ppm parameters.
"""
if self.prm.vendor != GpuItem.GPU_Vendor.AMD:
return
if not self.prm.readable or self.prm.gpu_type in [GpuItem.GPU_Type.Legacy, GpuItem.GPU_Type.Unsupported]:
LOGGER.debug('PPM for card number %s not readable.', self.prm.card_num)
return
pre = ' '
print('{}: {}'.format(self._GPU_Param_Labels['card_num'], self.prm.card_num))
print('{}{}: {}'.format(pre, self._GPU_Param_Labels['model'], self.prm.model))
print('{}{}: {}'.format(pre, self._GPU_Param_Labels['card_path'], self.prm.card_path))
print('{}{}: {}'.format(pre, self._GPU_Param_Labels['gpu_type'], self.prm.gpu_type.name))
print('{}{}: {}'.format(pre, self._GPU_Param_Labels['power_dpm_force'], self.prm.power_dpm_force))
print('{}{}{}'.format(pre, '', '#'.ljust(50, '#')))
file_path = os.path.join(self.prm.card_path, 'pp_power_profile_mode')
with open(file_path, 'r') as file_ptr:
lines = file_ptr.readlines()
for line in lines:
print(' {}'.format(line.strip('\n')))
def print_pstates(self) -> None:
"""
Print human friendly table of p-states.
"""
if self.prm.vendor != GpuItem.GPU_Vendor.AMD:
return
if not self.prm.readable or self.prm.gpu_type in [GpuItem.GPU_Type.Legacy, GpuItem.GPU_Type.Unsupported]:
LOGGER.debug('P-states for card number %s not readable.', self.prm.card_num)
return
pre = ' '
print('{}: {}'.format(self._GPU_Param_Labels['card_num'], self.prm.card_num))
print('{}{}: {}'.format(pre, self._GPU_Param_Labels['model'], self.prm.model))
print('{}{}: {}'.format(pre, self._GPU_Param_Labels['card_path'], self.prm.card_path))
print('{}{}: {}'.format(pre, self._GPU_Param_Labels['gpu_type'], self.prm.gpu_type.name))
# DPM States
if self.prm.gpu_type == self.GPU_Type.CurvePts:
print('{}{}{}'.format(pre, '', '#'.ljust(50, '#')))
print('{}DPM States:'.format(pre))
print('{}SCLK: {:<17} MCLK:'.format(pre, ' '))
for ps_num, ps_freq in self.sclk_dpm_state.items():
print('{} {:>1}: {:<8} '.format(pre, ps_num, ps_freq), end='')
if ps_num in self.mclk_dpm_state.keys():
print('{:3>}: {:<8}'.format(ps_num, self.mclk_dpm_state[ps_num]))
else:
print('')
# pp_od_clk_voltage states
print('{}{}{}'.format(pre, '', '#'.ljust(50, '#')))
print('{}PP OD States:'.format(pre))
print('{}SCLK: {:<17} MCLK:'.format(pre, ' '))
for ps_num, ps_vals in self.sclk_state.items():
print('{} {:>1}: {:<8} {:<8} '.format(pre, ps_num, ps_vals[0], ps_vals[1]), end='')
if ps_num in self.mclk_state.keys():
print('{:3>}: {:<8} {:<8}'.format(ps_num, self.mclk_state[ps_num][0], self.mclk_state[ps_num][1]))
else:
print('')
if self.prm.gpu_type == self.GPU_Type.CurvePts:
# Curve points
print('{}{}{}'.format(pre, '', '#'.ljust(50, '#')))
print('{}VDDC_CURVE:'.format(pre))
for vc_index, vc_vals in self.vddc_curve.items():
print('{} {}: {}'.format(pre, vc_index, vc_vals))
print('')
def print(self, short: bool = False, clflag: bool = False) -> None:
"""
Display ls like listing function for GPU parameters.
:param clflag: Display clinfo data if True
:param short: Display short listing
"""
pre = ''
for param_name, param_label in self._GPU_Param_Labels.items():
if short:
if param_name not in self.short_list:
continue
if self.prm.vendor == GpuItem.GPU_Vendor.NVIDIA:
if param_name in self.NV_Skip_List:
continue
elif self.prm.vendor == GpuItem.GPU_Vendor.AMD:
if param_name in self.AMD_Skip_List:
continue
if self.prm.gpu_type == self.GPU_Type.APU:
if param_name in self._fan_item_list:
continue
if 'Range' in param_label:
continue
if self.prm.gpu_type == self.GPU_Type.Legacy:
if param_name in self.LEGACY_Skip_List:
continue
if not self.prm.readable:
if param_name not in self.get_nc_params_list():
continue
pre = '' if param_name == 'card_num' else ' '
if re.search(r'sep[0-9]', param_name):
print('{}{}'.format(pre, param_label.ljust(50, param_label)))
continue
if param_name == 'unique_id':
if self.prm.unique_id is None:
continue
if self.prm.gpu_type == self.GPU_Type.CurvePts and param_name == 'vddc_range':
continue
if isinstance(self.get_params_value(param_name), float):
print('{}{}: {:.3f}'.format(pre, param_label, self.get_params_value(param_name)))
elif isinstance(self.get_params_value(param_name), dict):
param_dict = self.get_params_value(param_name)
print('{}{}: {}'.format(pre, param_label, {key: param_dict[key] for key in sorted(param_dict)}))
elif self.get_params_value(param_name) == '':
print('{}{}: {}'.format(pre, param_label, None))
else:
print('{}{}: {}'.format(pre, param_label, self.get_params_value(param_name)))
if clflag and self.prm.compute:
for param_name, param_label in self._GPU_CLINFO_Labels.items():
if re.search(r'sep[0-9]', param_name):
print('{}{}'.format(pre, param_label.ljust(50, param_label)))
continue
print('{}: {}'.format(param_label, self.get_clinfo_value(param_name)))
print('')
def get_plot_data(self) -> dict:
"""
Return a dictionary of dynamic gpu parameters used by gpu-plot to populate a df.
:return: Dictionary of GPU state info for plot data.
"""
gpu_state = {'Time': str(self.energy['tn'].strftime(env.GUT_CONST.TIME_FORMAT)),
'Card#': int(self.prm.card_num)}
for table_item in self.table_parameters:
gpu_state_str = str(re.sub(PATTERNS['MHz'], '', str(self.get_params_value(table_item)))).strip()
if gpu_state_str == 'nan':
gpu_state[table_item] = np_nan
elif gpu_state_str.isnumeric():
gpu_state[table_item] = int(gpu_state_str)
elif re.fullmatch(PATTERNS['IS_FLOAT'], gpu_state_str):
gpu_state[table_item] = float(gpu_state_str)
elif gpu_state_str == '' or gpu_state_str == '-1' or gpu_state_str == 'NA' or gpu_state_str is None:
gpu_state[table_item] = 'NA'
else:
gpu_state[table_item] = gpu_state_str
return gpu_state
GpuDict = Dict[str, GpuItem]
class GpuList:
"""
A list of GpuItem indexed with uuid. It also contains a table of parameters used for tabular printouts
"""
def __init__(self) -> None:
self.list: GpuDict = {}
self.opencl_map: dict = {}
self.amd_featuremask: Union[int, None] = None
self.amd_wattman: bool = False
self.amd_writable: bool = False
self.nv_readwritable: bool = False
def __repr__(self) -> dict:
return self.list
def __str__(self) -> str:
return 'GPU_List: Number of GPUs: {}'.format(self.num_gpus())
def __getitem__(self, uuid: str) -> GpuItem:
if uuid in self.list:
return self.list[uuid]
raise KeyError('KeyError: invalid uuid: {}'.format(uuid))
def __setitem__(self, uuid: str, value: GpuItem) -> None:
self.list[uuid] = value
def __iter__(self) -> Generator[GpuItem, None, None]:
for value in self.list.values():
yield value
def items(self) -> Generator[Union[str, GpuItem], None, None]:
"""
Get uuid, gpu pairs from a GpuList object.
:return: uuid, gpu pair
"""
for key, value in self.list.items():
yield key, value
def uuids(self) -> Generator[str, None, None]:
"""
Get uuids of the GpuList object.
:return: uuids from the GpuList object.
"""
for key in self.list:
yield key
def gpus(self) -> Generator[GpuItem, None, None]:
"""
Get GpuItems from a GpuList object.
:return: GpuUItem
"""
return self.__iter__()
def add(self, gpu_item: GpuItem) -> None:
"""
Add given GpuItem to the GpuList.
:param gpu_item: Item to be added
"""
self[gpu_item.prm.uuid] = gpu_item
LOGGER.debug('Added GPU Item %s to GPU List', gpu_item.prm.uuid)
def get_pcie_map(self) -> dict:
"""
Get mapping of card number to pcie address as dict.
:return: dict of num: pcieid
"""
pcie_dict = {}
for gpu in self.gpus():
pcie_dict.update({gpu.prm.card_num: gpu.prm.pcie_id})
return pcie_dict
def wattman_status(self) -> str:
"""
Display Wattman status.
:return: Status string
"""
LOGGER.debug('AMD featuremask: %s', hex(self.amd_featuremask))
if self.amd_wattman:
return 'Wattman features enabled: {}'.format(hex(self.amd_featuremask))
return 'Wattman features not enabled: {}, See README file.'.format(hex(self.amd_featuremask))
@staticmethod
def table_param_labels() -> dict:
"""
Get dictionary of parameter labels to be used in table reports.
:return: Dictionary of table parameters/labels
"""
return GpuItem.table_param_labels
@staticmethod
def table_parameters() -> List[str]:
"""
Get list of parameters to be used in table reports.
:return: List of table parameters
"""
return GpuItem.table_parameters
@staticmethod
def get_gpu_pci_list() -> Union[List[str], None]:
"""
Use call to lspci to get a list of pci addresses of all GPUs.
:return: List of GPU pci addresses.
"""
pci_list = []
try:
lspci_output = subprocess.check_output(env.GUT_CONST.cmd_lspci, shell=False).decode().split('\n')
except (subprocess.CalledProcessError, OSError) as except_err:
print('Error [{}]: lspci failed to find GPUs'.format(except_err))
return None
for lspci_line in lspci_output:
if re.search(PATTERNS['PCI_GPU'], lspci_line):
LOGGER.debug('Found GPU pci: %s', lspci_line)
pciid = re.search(env.GUT_CONST.PATTERNS['PCI_ADD'], lspci_line)
if pciid:
pci_list.append(pciid.group(0))
return pci_list
def set_gpu_list(self, clinfo_flag: bool = False) -> bool:
"""
Use lspci to populate list of all installed GPUs.
:return: True on success
"""
if not env.GUT_CONST.cmd_lspci:
return False
if clinfo_flag:
self.read_gpu_opencl_data()
LOGGER.debug('OpenCL map: %s', self.opencl_map)
# Check AMD writability
try:
self.amd_featuremask = env.GUT_CONST.read_amdfeaturemask()
except FileNotFoundError:
self.amd_wattman = self.amd_writable = False
self.amd_wattman = self.amd_writable = (self.amd_featuremask == int(0xffff7fff) or
self.amd_featuremask == int(0xffffffff) or
self.amd_featuremask == int(0xfffd7fff))
# Check NV read/writability
if env.GUT_CONST.cmd_nvidia_smi:
self.nv_readwritable = True
pcie_ids = self.get_gpu_pci_list()
if not pcie_ids:
print('Error [{}]: lspci failed to find GPUs')
return False
LOGGER.debug('Found %s GPUs', len(pcie_ids))
for pcie_id in pcie_ids:
# Initial GPU Item
gpu_uuid = uuid4().hex
self.add(GpuItem(gpu_uuid))
LOGGER.debug('GPU: %s', pcie_id)
gpu_name = 'UNKNOWN'
driver_module = 'UNKNOWN'
card_path = ''
sys_card_path = ''
hwmon_path = ''
readable = writable = compute = False
gpu_type = GpuItem.GPU_Type.Undefined
vendor = GpuItem.GPU_Vendor.Undefined
opencl_device_version = None if clinfo_flag else 'UNKNOWN'
# Get more GPU details from lspci -k -s
cmd_str = '{} -k -s {}'.format(env.GUT_CONST.cmd_lspci, pcie_id)
try:
lspci_items = subprocess.check_output(shlex.split(cmd_str), shell=False).decode().split('\n')
except (subprocess.CalledProcessError, OSError) as except_err:
message = 'Fatal Error [{}]: Can not get GPU details with lspci.'.format(except_err)
LOGGER.debug(message)
print(message)
sys.exit(-1)
LOGGER.debug('lspci output items:\n %s', lspci_items)
# Get Long GPU Name
gpu_name_items = lspci_items[0].split(': ', maxsplit=1)
if len(gpu_name_items) >= 2:
gpu_name = gpu_name_items[1]
# Check for Fiji ProDuo
if re.search('Fiji', gpu_name):
if re.search(r'Radeon Pro Duo', lspci_items[1].split('[AMD/ATI]')[1]):
gpu_name = 'Radeon Fiji Pro Duo'
LOGGER.debug('gpu_name: [%s]', gpu_name)
# Get GPU brand: AMD, INTEL, NVIDIA, ASPEED
if re.search(PATTERNS['AMD_GPU'], gpu_name):
vendor = GpuItem.GPU_Vendor.AMD
gpu_type = GpuItem.GPU_Type.Supported
if self.opencl_map:
if pcie_id in self.opencl_map.keys():
if 'device_version' in self.opencl_map[pcie_id].keys():
opencl_device_version = self.opencl_map[pcie_id]['device_version']
compute = True
else:
compute = True
if re.search(PATTERNS['NV_GPU'], gpu_name):
vendor = GpuItem.GPU_Vendor.NVIDIA
if env.GUT_CONST.cmd_nvidia_smi:
readable = True
gpu_type = GpuItem.GPU_Type.Supported
if self.opencl_map:
if pcie_id in self.opencl_map.keys():
if 'device_version' in self.opencl_map[pcie_id].keys():
opencl_device_version = self.opencl_map[pcie_id]['device_version']
compute = True
else:
compute = True
if re.search(PATTERNS['INTC_GPU'], gpu_name):
vendor = GpuItem.GPU_Vendor.INTEL
gpu_type = GpuItem.GPU_Type.Unsupported
if self.opencl_map:
if pcie_id in self.opencl_map.keys():
if 'device_version' in self.opencl_map[pcie_id].keys():
opencl_device_version = self.opencl_map[pcie_id]['device_version']
compute = True
else:
compute = not bool(re.search(r' 530', gpu_name))
if re.search(PATTERNS['ASPD_GPU'], gpu_name):
vendor = GpuItem.GPU_Vendor.ASPEED
gpu_type = GpuItem.GPU_Type.Unsupported
if re.search(PATTERNS['MTRX_GPU'], gpu_name):
vendor = GpuItem.GPU_Vendor.MATROX
gpu_type = GpuItem.GPU_Type.Unsupported
# Get Driver Name
for lspci_line in lspci_items:
if re.search(r'([kK]ernel)', lspci_line):
driver_module_items = lspci_line.split(': ')
if len(driver_module_items) >= 2:
driver_module = driver_module_items[1].strip()
# Get full card path
device_dirs = glob.glob(os.path.join(env.GUT_CONST.card_root, 'card?/device'))
# Match system device directory to pcie ID.
for device_dir in device_dirs:
sysfspath = str(Path(device_dir).resolve())
LOGGER.debug('sysfpath: %s\ndevice_dir: %s', sysfspath, device_dir)
if pcie_id == sysfspath[-7:]:
card_path = device_dir
sys_card_path = sysfspath
LOGGER.debug('card_path set to: %s', device_dir)
# No card path could be found. Set readable/writable to False and type to Unsupported
if not card_path:
LOGGER.debug('card_path not set for: %s', pcie_id)
LOGGER.debug('GPU[%s] type set to Unsupported', gpu_uuid)
gpu_type = GpuItem.GPU_Type.Unsupported
readable = writable = False
try_path = '/sys/devices/pci*:*/'
sys_pci_dirs = None
for _ in range(6):
search_path = os.path.join(try_path, '????:{}'.format(pcie_id))
sys_pci_dirs = glob.glob(search_path)
if sys_pci_dirs:
# Found a match
break
try_path = os.path.join(try_path, '????:??:??.?')
if not sys_pci_dirs:
LOGGER.debug('/sys/device file search found no match to pcie_id: %s', pcie_id)
else:
if len(sys_pci_dirs) > 1:
LOGGER.debug('/sys/device file search found multiple matches to pcie_id %s:\n%s',
pcie_id, sys_pci_dirs)
else:
LOGGER.debug('/sys/device file search found match to pcie_id %s:\n%s',
pcie_id, sys_pci_dirs)
sys_card_path = sys_pci_dirs[0]
# Get full hwmon path
if card_path:
LOGGER.debug('Card dir [%s] contents:\n%s', card_path, list(os.listdir(card_path)))
hw_file_srch = glob.glob(os.path.join(card_path, env.GUT_CONST.hwmon_sub) + '?')
LOGGER.debug('HW file search: %s', hw_file_srch)
if len(hw_file_srch) > 1:
print('More than one hwmon file found: {}'.format(hw_file_srch))
elif len(hw_file_srch) == 1:
hwmon_path = hw_file_srch[0]
LOGGER.debug('HW dir [%s] contents:\n%s', hwmon_path, list(os.listdir(hwmon_path)))
# Check AMD write capability
if vendor == GpuItem.GPU_Vendor.AMD and card_path:
pp_od_clk_voltage_file = os.path.join(card_path, 'pp_od_clk_voltage')
if os.path.isfile(pp_od_clk_voltage_file):
gpu_type = GpuItem.GPU_Type.Supported
readable = True
if self.amd_writable:
writable = True
elif os.path.isfile(os.path.join(card_path, 'power_dpm_state')):
# if os.path.isfile(os.path.join(card_path, 'pp_dpm_mclk')) or GpuItem.is_apu(gpu_name):
if GpuItem.is_apu(gpu_name):
readable = True
gpu_type = GpuItem.GPU_Type.APU
else:
# if no pp_od_clk_voltage but has power_dpm_state, assume legacy, and disable some sensors
readable = True
gpu_type = GpuItem.GPU_Type.Legacy
elif GpuItem.is_apu(gpu_name):
readable = True
gpu_type = GpuItem.GPU_Type.APU
else:
gpu_type = GpuItem.GPU_Type.Unsupported
if LOGGER.getEffectiveLevel() == logging.DEBUG:
# Write pp_od_clk_voltage details to debug LOGGER
if os.path.isfile(pp_od_clk_voltage_file):
with open(pp_od_clk_voltage_file, 'r') as file_ptr:
pp_od_file_details = file_ptr.read()
else:
pp_od_file_details = 'The file {} does not exist'.format(pp_od_clk_voltage_file)
LOGGER.debug('%s contents:\n%s', pp_od_clk_voltage_file, pp_od_file_details)
# Set GPU parameters
self[gpu_uuid].populate_prm_from_dict({'pcie_id': pcie_id, 'model': gpu_name,
'vendor': vendor,
'driver': driver_module, 'card_path': card_path,
'sys_card_path': sys_card_path, 'gpu_type': gpu_type,
'hwmon_path': hwmon_path, 'readable': readable,
'writable': writable, 'compute': compute,
'compute_platform': opencl_device_version})
LOGGER.debug('Card flags: readable: %s, writable: %s, type: %s',
readable, writable, self[gpu_uuid].prm.gpu_type)
# Read GPU ID
rdata = self[gpu_uuid].read_gpu_sensor('id', vendor=GpuItem.GPU_Vendor.PCIE, sensor_type='DEVICE')
if rdata:
self[gpu_uuid].set_params_value('id', rdata)
if clinfo_flag:
if pcie_id in self.opencl_map.keys():
self[gpu_uuid].populate_ocl(self.opencl_map[pcie_id])
return True
def read_gpu_opencl_data(self) -> bool:
"""
Use clinfo system call to get openCL details for relevant GPUs.
:return: Returns True if successful
.. todo:: Read of Intel pcie_id is not working.
"""
# Check access to clinfo command
if not env.GUT_CONST.cmd_clinfo:
print('OS Command [clinfo] not found. Use sudo apt-get install clinfo to install', file=sys.stderr)
return False
# Run the clinfo command
cmd = subprocess.Popen(shlex.split('{} --raw'.format(env.GUT_CONST.cmd_clinfo)), shell=False,
stdout=subprocess.PIPE)
# Clinfo Keywords and related opencl_map key.
ocl_keywords = {'CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE': 'prf_wg_multiple',
'CL_DEVICE_MAX_WORK_GROUP_SIZE': 'max_wg_size',
'CL_DEVICE_PREFERRED_WORK_GROUP_SIZE': 'prf_wg_size',
'CL_DEVICE_MAX_WORK_ITEM_SIZES': 'max_wi_sizes',
'CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS': 'max_wi_dim',
'CL_DEVICE_MAX_MEM_ALLOC_SIZE': 'max_mem_allocation',
'CL_DEVICE_SIMD_INSTRUCTION_WIDTH': 'simd_ins_width',
'CL_DEVICE_SIMD_WIDTH': 'simd_width',
'CL_DEVICE_SIMD_PER_COMPUTE_UNIT': 'simd_per_cu',
'CL_DEVICE_MAX_COMPUTE_UNITS': 'max_cu',
'CL_DEVICE_NAME': 'device_name',
'CL_DEVICE_OPENCL_C_VERSION': 'opencl_version',
'CL_DRIVER_VERSION': 'driver_version',
'CL_DEVICE_VERSION': 'device_version'}
def init_temp_map() -> dict:
"""
Return an initialized clinfo dict.
:return: Initialized clinfo dict
"""
t_dict = {}
for temp_keys in ocl_keywords.values():
t_dict[temp_keys] = None
return t_dict
# Initialize dict variables
ocl_vendor = ocl_index = ocl_pcie_id = ocl_pcie_bus_id = ocl_pcie_slot_id = None
temp_map = init_temp_map()
# Read each line from clinfo --raw
for line in cmd.stdout:
linestr = line.decode('utf-8').strip()
if len(linestr) < 1:
continue
if linestr[0] != '[':
continue
line_items = linestr.split(maxsplit=2)
if len(line_items) != 3:
continue
cl_vendor, cl_index = tuple(re.sub(r'[\[\]]', '', line_items[0]).split('/'))
if cl_index == '*':
continue
if not ocl_index:
ocl_index = cl_index
ocl_vendor = cl_vendor
ocl_pcie_slot_id = ocl_pcie_bus_id = None
# If new cl_index, then update opencl_map
if cl_vendor != ocl_vendor or cl_index != ocl_index:
# Update opencl_map with dict variables when new index is encountered.
self.opencl_map.update({ocl_pcie_id: temp_map})
LOGGER.debug('cl_vendor: %s, cl_index: %s, pcie_id: %s',
ocl_vendor, ocl_index, self.opencl_map[ocl_pcie_id])
# Initialize dict variables
ocl_index = cl_index
ocl_vendor = cl_vendor
ocl_pcie_id = ocl_pcie_bus_id = ocl_pcie_slot_id = None
temp_map = init_temp_map()
param_str = line_items[1]
# Check item in clinfo_keywords
for clinfo_keyword, opencl_map_keyword in ocl_keywords.items():
if clinfo_keyword in param_str:
temp_map[opencl_map_keyword] = line_items[2].strip()
LOGGER.debug('openCL map %s: [%s]', clinfo_keyword, temp_map[opencl_map_keyword])
continue
# PCIe ID related clinfo_keywords
# Check for AMD pcie_id details
if 'CL_DEVICE_TOPOLOGY' in param_str:
ocl_pcie_id = (line_items[2].split()[1]).strip()
LOGGER.debug('AMD ocl_pcie_id [%s]', ocl_pcie_id)
continue
# Check for NV pcie_id details
if 'CL_DEVICE_PCI_BUS_ID_NV' in param_str:
ocl_pcie_bus_id = hex(int(line_items[2].strip()))
if ocl_pcie_slot_id is not None:
ocl_pcie_id = '{}:{}.0'.format(ocl_pcie_bus_id[2:].zfill(2), ocl_pcie_slot_id[2:].zfill(2))
ocl_pcie_slot_id = ocl_pcie_bus_id = None
LOGGER.debug('NV ocl_pcie_id [%s]', ocl_pcie_id)
continue
if 'CL_DEVICE_PCI_SLOT_ID_NV' in param_str:
ocl_pcie_slot_id = hex(int(line_items[2].strip()))
if ocl_pcie_bus_id is not None:
ocl_pcie_id = '{}:{}.0'.format(ocl_pcie_bus_id[2:].zfill(2), ocl_pcie_slot_id[2:].zfill(2))
ocl_pcie_slot_id = ocl_pcie_bus_id = None
LOGGER.debug('NV ocl_pcie_id [%s]', ocl_pcie_id)
continue
# Check for INTEL pcie_id details
# TODO don't know how to do this yet.
self.opencl_map.update({ocl_pcie_id: temp_map})
return True
def num_vendor_gpus(self, compatibility: Enum = GpuItem.GPU_Comp.ALL) -> Dict[str, int]:
"""
Return the count of GPUs by vendor. Counts total by default, but can also by rw, ronly, or wonly.
:param compatibility: Only count vendor GPUs if True.
:return: Dictionary of GPU counts
"""
try:
_ = compatibility.name
except AttributeError:
raise AttributeError('Error: {} not a valid compatibility name: [{}]'.format(
compatibility, GpuItem.GPU_Comp))
results_dict = {}
for gpu in self.gpus():
if compatibility == GpuItem.GPU_Comp.ReadWrite:
if not gpu.prm.readable or not gpu.prm.writable:
continue
if compatibility == GpuItem.GPU_Comp.ReadOnly:
if not gpu.prm.readable:
continue
if compatibility == GpuItem.GPU_Comp.WriteOnly:
if not gpu.prm.writable:
continue
if gpu.prm.vendor.name not in results_dict.keys():
results_dict.update({gpu.prm.vendor.name: 1})
else:
results_dict[gpu.prm.vendor.name] += 1
return results_dict
def num_gpus(self, vendor: Enum = GpuItem.GPU_Vendor.ALL) -> Dict[str, int]:
"""
Return the count of GPUs by total, rw, r-only or w-only.
:param vendor: Only count vendor GPUs of specific vendor or all vendors by default.
:return: Dictionary of GPU counts
"""
try:
vendor_name = vendor.name
except AttributeError:
raise AttributeError('Error: {} not a valid vendor name: [{}]'.format(vendor, GpuItem.GPU_Vendor))
results_dict = {'vendor': vendor_name, 'total': 0, 'rw': 0, 'r-only': 0, 'w-only': 0}
for gpu in self.gpus():
if vendor != GpuItem.GPU_Vendor.ALL:
if vendor != gpu.prm.vendor:
continue
if gpu.prm.readable and gpu.prm.writable:
results_dict['rw'] += 1
elif gpu.prm.readable:
results_dict['r-only'] += 1
elif gpu.prm.writable:
results_dict['w-only'] += 1
results_dict['total'] += 1
return results_dict
def list_gpus(self, vendor: Enum = GpuItem.GPU_Vendor.ALL,
compatibility: Enum = GpuItem.GPU_Comp.ALL) -> 'class GpuList':
"""
Return GPU_Item of GPUs. Contains all by default, but can be a subset with vendor and compatibility args.
Only one flag should be set.
:param vendor: Only count vendor GPUs or ALL by default.
:param compatibility: Only count GPUs with specified compatibility (all, readable, writable)
:return: GpuList of compatible GPUs
"""
try:
_ = compatibility.name
except AttributeError:
raise AttributeError('Error: {} not a valid compatibility name: [{}]'.format(
compatibility, GpuItem.GPU_Comp))
try:
_ = vendor.name
except AttributeError:
raise AttributeError('Error: {} not a valid vendor name: [{}]'.format(vendor, GpuItem.GPU_Vendor))
result_list = GpuList()
for uuid, gpu in self.items():
if vendor != GpuItem.GPU_Vendor.ALL:
if vendor != gpu.prm.vendor:
continue
if compatibility == GpuItem.GPU_Comp.Readable:
# Skip Legacy GPU type, since most parameters can not be read.
if gpu.prm.gpu_type != GpuItem.GPU_Type.Legacy:
if gpu.prm.readable:
result_list[uuid] = gpu
elif compatibility == GpuItem.GPU_Comp.Writable:
if gpu.prm.writable:
result_list[uuid] = gpu
else:
result_list[uuid] = gpu
return result_list
def read_gpu_ppm_table(self) -> None:
"""
Read GPU ppm data and populate GpuItem.
"""
for gpu in self.gpus():
if gpu.prm.readable:
gpu.read_gpu_ppm_table()
def print_ppm_table(self) -> None:
"""
Print the GpuItem ppm data.
"""
for gpu in self.gpus():
gpu.print_ppm_table()
def read_gpu_pstates(self) -> None:
"""
Read GPU p-state data and populate GpuItem.
"""
for gpu in self.gpus():
if gpu.prm.readable:
gpu.read_gpu_pstates()
def print_pstates(self) -> None:
"""
Print the GpuItem p-state data.
"""
for gpu in self.gpus():
gpu.print_pstates()
def read_gpu_sensor_set(self, data_type: Enum = GpuItem.SensorSet.All) -> None:
"""
Read sensor data from all GPUs in self.list.
:param data_type: Specifies the sensor set to use in the read.
"""
for gpu in self.gpus():
if gpu.prm.readable:
gpu.read_gpu_sensor_set(data_type)
# Printing Methods follow.
def print(self, short: bool = False, clflag: bool = False) -> None:
"""
Print all GpuItem.
:param short: If true, print short report
:param clflag: If true, print clinfo
"""
for gpu in self.gpus():
gpu.print(short=short, clflag=clflag)
def print_table(self, title: Union[str, None] = None) -> bool:
"""
Print table of parameters.
:return: True if success
"""
table_width: int = 20
if self.num_gpus()['total'] < 1:
return False
if title:
print('\x1b[1;36m{}\x1b[0m'.format(title))
print('┌', '─'.ljust(13, '─'), sep='', end='')
for _ in self.gpus():
print('┬', '─'.ljust(table_width, '─'), sep='', end='')
print('┐')
print('│\x1b[1;36m' + 'Card #'.ljust(13, ' ') + '\x1b[0m', sep='', end='')
for gpu in self.gpus():
print('│\x1b[1;36mcard{:<16}\x1b[0m'.format(gpu.prm.card_num), end='')
print('│')
print('├', '─'.ljust(13, '─'), sep='', end='')
for _ in self.gpus():
print('┼', '─'.ljust(table_width, '─'), sep='', end='')
print('┤')
for table_item in self.table_parameters():
print('│\x1b[1;36m{:<13}\x1b[0m'.format(str(self.table_param_labels()[table_item])[:13]), end='')
for gpu in self.gpus():
data_value_raw = gpu.get_params_value(table_item)
if isinstance(data_value_raw, float):
data_value_raw = round(data_value_raw, 3)
print('│{:<20}'.format(str(data_value_raw)[:table_width]), end='')
print('│')
print('└', '─'.ljust(13, '─'), sep='', end='')
for _ in self.gpus():
print('┴', '─'.ljust(table_width, '─'), sep='', end='')
print('┘')
return True
def print_log_header(self, log_file_ptr: TextIO) -> bool:
"""
Print the log header.
:param log_file_ptr: File pointer for target output.
:return: True if success
"""
if self.num_gpus()['total'] < 1:
return False
# Print Header
print('Time|Card#', end='', file=log_file_ptr)
for table_item in self.table_parameters():
print('|{}'.format(table_item), end='', file=log_file_ptr)
print('', file=log_file_ptr)
return True
def print_log(self, log_file_ptr: TextIO) -> bool:
"""
Print the log data.
:param log_file_ptr: File pointer for target output.
:return: True if success
"""
if self.num_gpus()['total'] < 1:
return False
# Print Data
for gpu in self.gpus():
print('{}|{}'.format(gpu.energy['tn'].strftime(env.GUT_CONST.TIME_FORMAT), gpu.prm.card_num),
sep='', end='', file=log_file_ptr)
for table_item in self.table_parameters():
print('|{}'.format(re.sub(PATTERNS['MHz'], '', str(gpu.get_params_value(table_item)).strip())),
sep='', end='', file=log_file_ptr)
print('', file=log_file_ptr)
return True
def print_plot_header(self, log_file_ptr: IO[Union[str, bytes]]) -> bool:
"""
Print the plot header.
:param log_file_ptr: File pointer for target output.
:return: True if success
"""
if self.num_gpus()['total'] < 1:
return False
# Print Header
line_str_item = ['Time|Card#']
for table_item in self.table_parameters():
line_str_item.append('|' + table_item)
line_str_item.append('\n')
line_str = ''.join(line_str_item)
log_file_ptr.write(line_str.encode('utf-8'))
log_file_ptr.flush()
return True
def print_plot(self, log_file_ptr: IO[Union[str, bytes]]) -> bool:
"""
Print the plot data.
:param log_file_ptr: File pointer for target output.
:return: True on success
"""
if self.num_gpus()['total'] < 1:
return False
# Print Data
for gpu in self.gpus():
line_str_item = ['{}|{}'.format(str(gpu.energy['tn'].strftime(env.GUT_CONST.TIME_FORMAT)),
gpu.prm.card_num)]
for table_item in self.table_parameters():
line_str_item.append('|' + re.sub(PATTERNS['MHz'], '', str(gpu.get_params_value(table_item))).strip())
line_str_item.append('\n')
line_str = ''.join(line_str_item)
log_file_ptr.write(line_str.encode('utf-8'))
log_file_ptr.flush()
return True
def about() -> None:
"""
Print details about this module.
"""
print(__doc__)
print('Author: ', __author__)
print('Copyright: ', __copyright__)
print('Credits: ', *['\n {}'.format(item) for item in __credits__])
print('License: ', __license__)
print('Version: ', __version__)
print('Maintainer: ', __maintainer__)
print('Status: ', __status__)
sys.exit(0)
if __name__ == '__main__':
about()
gpu-utils-3.6.0/GPUmodules/__init__.py 0000664 0000000 0000000 00000000200 14027501566 0017604 0 ustar 00root root 0000000 0000000 __version__ = '3.6.0'
__status__ = 'Development Status :: 5 - Production/Stable'
#__status__ = 'Development Status :: 4 - Beta'
gpu-utils-3.6.0/GPUmodules/env.py 0000775 0000000 0000000 00000046724 14027501566 0016665 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
"""env.py - sets environment for rickslab-gpu-utils and establishes global variables
Copyright (C) 2019 RicksLab
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
"""
__author__ = 'RueiKe'
__copyright__ = 'Copyright (C) 2019 RicksLab'
__credits__ = ['Craig Echt - Testing, Debug, and Verification']
__license__ = 'GNU General Public License'
__program_name__ = 'gpu-utils'
__maintainer__ = 'RueiKe'
__docformat__ = 'reStructuredText'
# pylint: disable=multiple-statements
# pylint: disable=line-too-long
# pylint: disable=bad-continuation
import argparse
import re
import subprocess
import platform
import sys
from os import path as os_path
import logging
from pathlib import Path
import inspect
import shlex
import shutil
from time import mktime as time_mktime
from datetime import datetime
from typing import Dict, Union, List, TextIO
from GPUmodules import __version__, __status__
LOGGER = logging.getLogger('gpu-utils')
class GutConst:
"""
GPU Utils constants used throughout the project.
"""
_verified_distros: List[str] = ['Debian', 'Ubuntu', 'Neon', 'Gentoo', 'Arch']
_dpkg_tool: Dict[str, str] = {'Debian': 'dpkg', 'Ubuntu': 'dpkg', 'Neon': 'dpkg',
'Arch': 'pacman',
'Gentoo': 'equery'}
_all_args: List[str] = ['execute_pac', 'debug', 'pdebug', 'sleep', 'no_fan', 'ltz', 'simlog', 'log', 'force_write']
PATTERNS = {'HEXRGB': re.compile(r'^#[0-9a-fA-F]{6}'),
'PCIIID_L0': re.compile(r'^[0-9a-fA-F]{4}.*'),
'PCIIID_L1': re.compile(r'^\t[0-9a-fA-F]{4}.*'),
'PCIIID_L2': re.compile(r'^\t\t[0-9a-fA-F]{4}.*'),
'END_IN_ALPHA': re.compile(r'[a-zA-Z]+$'),
'ALPHA': re.compile(r'[a-zA-Z]+'),
'AMD_GPU': re.compile(r'(AMD|amd|ATI|ati)'),
'NV_GPU': re.compile(r'(NVIDIA|nvidia|nVidia)'),
'INTC_GPU': re.compile(r'(INTEL|intel|Intel)'),
'ASPD_GPU': re.compile(r'(ASPEED|aspeed|Aspeed)'),
'MTRX_GPU': re.compile(r'(MATROX|matrox|Matrox)'),
'MHz': re.compile(r'M[Hh]z'),
'PPM_CHK': re.compile(r'[*].*'),
'PCI_GPU': re.compile(r'(VGA|3D|Display)'),
'PCI_ADD': re.compile(r'^([0-9a-fA-F]{2}:[0-9a-fA-F]{2}.[0-9a-fA-F])'),
'PPM_NOTCHK': re.compile(r'[ ]+'),
'VALID_PS_STR': re.compile(r'[0-9]+(\s[0-9])*'),
'IS_FLOAT': re.compile(r'[-+]?\d*\.?\d+|[-+]?\d+'),
'DIGITS': re.compile(r'^[0-9]+[0-9]*$'),
'VAL_ITEM': re.compile(r'.*_val$'),
'GPU_GENERIC': re.compile(r'(^\s|intel|amd|nvidia|amd/ati|ati|radeon|\[|\])', re.IGNORECASE),
'GPUMEMTYPE': re.compile(r'^mem_(gtt|vram)_.*')}
_sys_pciid_list: List[str] = ['/usr/share/misc/pci.ids', '/usr/share/hwdata/pci.ids']
_module_path: str = os_path.dirname(str(Path(__file__).resolve()))
_repository_path: str = os_path.join(_module_path, '..')
_local_config_list: Dict[str, str] = {
'repository': _repository_path,
'debian': '/usr/share/rickslab-gpu-utils/config',
'pypi-linux': os_path.join(str(Path.home()), '.local', 'share', 'rickslab-gpu-utils', 'config')}
_local_icon_list: Dict[str, str] = {
'repository': os_path.join(_repository_path, 'icons'),
'debian': '/usr/share/rickslab-gpu-utils/icons',
'pypi-linux': '{}/.local/share/rickslab-gpu-utils/icons'.format(str(Path.home()))}
featuremask: str = '/sys/module/amdgpu/parameters/ppfeaturemask'
card_root: str = '/sys/class/drm/'
hwmon_sub: str = 'hwmon/hwmon'
gui_window_title: str = 'Ricks-Lab GPU Utilities'
mon_field_width = 20
def __init__(self):
self.args: Union[argparse.Namespace, None] = None
self.repository_path: str = self._repository_path
self.install_type: Union[str, None] = None
self.package_path: str = inspect.getfile(inspect.currentframe())
if 'dist-packages' in self.package_path:
self.install_type = 'debian'
elif '.local' in self.package_path:
self.install_type = 'pypi-linux'
else:
self.install_type = 'repository'
self.icon_path = self._local_icon_list[self.install_type]
if not os_path.isfile(os_path.join(self.icon_path, 'gpu-mon.icon.png')):
print('Error: Invalid icon path')
self.icon_path = None
# Set pciid Path
for try_pciid_path in GutConst._sys_pciid_list:
if os_path.isfile(try_pciid_path):
self.sys_pciid = try_pciid_path
break
else:
self.sys_pciid = None
self.distro: Dict[str, Union[str, None]] = {'Distributor': None, 'Description': None}
self.amdfeaturemask: Union[int, None] = None
self.log_file_ptr: Union[TextIO, None] = None
# From args
self.execute_pac: bool = False
self.DEBUG: bool = False
self.PDEBUG: bool = False
self.SIMLOG: bool = False
self.LOG: bool = False
self.PLOT: bool = False
self.show_fans: bool = True
self.write_delta_only: bool = False
self.SLEEP: int = 2
self.USELTZ: bool = False
# Time
self.TIME_FORMAT: str = '%d-%b-%Y %H:%M:%S'
self.LTZ: datetime.tzinfo = datetime.utcnow().astimezone().tzinfo
# Command access
self.cmd_lsb_release: Union[str, None] = None
self.cmd_lspci: Union[str, None] = None
self.cmd_clinfo: Union[str, None] = None
self.cmd_dpkg: Union[str, None] = None
self.cmd_nvidia_smi: Union[str, None] = None
def set_args(self, args: argparse.Namespace) -> None:
"""
Set arguments for the give args object.
:param args: The object return by args parser.
"""
self.args = args
for target_arg in self._all_args:
if target_arg in self.args:
if target_arg == 'debug': self.DEBUG = self.args.debug
elif target_arg == 'execute_pac': self.execute_pac = self.args.execute_pac
elif target_arg == 'pdebug': self.PDEBUG = self.args.pdebug
elif target_arg == 'sleep': self.SLEEP = self.args.sleep
elif target_arg == 'no_fan': self.show_fans = not self.args.no_fan
elif target_arg == 'ltz': self.USELTZ = self.args.ltz
elif target_arg == 'simlog': self.SIMLOG = self.args.simlog
elif target_arg == 'log': self.LOG = self.args.log
elif target_arg == 'force_write': self.write_delta_only = not self.args.force_write
else: print('Invalid arg: {}'.format(target_arg))
LOGGER.propagate = False
formatter = logging.Formatter("%(levelname)s:%(name)s:%(module)s.%(funcName)s:%(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
stream_handler.setLevel(logging.WARNING)
LOGGER.addHandler(stream_handler)
LOGGER.setLevel(logging.WARNING)
if self.DEBUG:
LOGGER.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(
'debug_gpu-utils_{}.log'.format(datetime.now().strftime("%Y%m%d-%H%M%S")), 'w')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
LOGGER.addHandler(file_handler)
LOGGER.debug('Install type: %s', self.install_type)
LOGGER.debug('Command line arguments:\n %s', args)
LOGGER.debug('Local TZ: %s', self.LTZ)
LOGGER.debug('pciid path set to: %s', self.sys_pciid)
LOGGER.debug('Icon path set to: %s', self.icon_path)
@staticmethod
def now(ltz: bool = False) -> datetime:
"""
Get the current datetime object.
:param ltz: Flag to get local time instead of UTC
:return: datetime obj of current time
"""
return datetime.now() if ltz else datetime.utcnow()
@staticmethod
def utc2local(utc: datetime) -> datetime:
"""
Return local time for given UTC time.
:param utc: Time for UTC
:return: Time for local time zone
.. note:: from https://stackoverflow.com/questions/4770297/convert-utc-datetime-string-to-local-datetime
"""
epoch = time_mktime(utc.timetuple())
offset = datetime.fromtimestamp(epoch) - datetime.utcfromtimestamp(epoch)
return utc + offset
def read_amdfeaturemask(self) -> int:
"""
Read and return the amdfeaturemask as an int.
:return: AMD Feature Mask
"""
try:
with open(self.featuremask) as fm_file:
fm_str = fm_file.readline().rstrip()
LOGGER.debug('Raw Featuremask string: [%s]', fm_str)
self.amdfeaturemask = int(fm_str, 0)
except TypeError as err:
LOGGER.debug('Invalid AMD Featuremask str [%s], %s', fm_str, err)
self.amdfeaturemask = 0
except OSError as err:
LOGGER.debug('Could not read AMD Featuremask, %s', err)
self.amdfeaturemask = 0
return self.amdfeaturemask
def check_env(self) -> int:
"""
Check the compatibility of the user environment.
:return: Return status: ok=0, python issue= -1, kernel issue= -2, command issue= -3
"""
# Check python version
required_pversion = (3, 6)
(python_major, python_minor, python_patch) = platform.python_version_tuple()
LOGGER.debug('Using python: %s.%s.%s', python_major, python_minor, python_patch)
if int(python_major) < required_pversion[0]:
print('Using python {}, but {} requires python {}.{} or higher.'.format(python_major, __program_name__,
required_pversion[0],
required_pversion[1]),
file=sys.stderr)
return -1
if int(python_major) == required_pversion[0] and int(python_minor) < required_pversion[1]:
print('Using python {}.{}.{}, but {} requires python {}.{} or higher.'.format(python_major, python_minor,
python_patch,
__program_name__,
required_pversion[0],
required_pversion[1]),
file=sys.stderr)
return -1
# Check Linux Kernel version
required_kversion = (4, 8)
linux_version = platform.release()
LOGGER.debug('Using Linux Kernel: %s', linux_version)
if int(linux_version.split('.')[0]) < required_kversion[0]:
print('Using Linux Kernel {}, but {} requires > {}.{}.'.format(linux_version, __program_name__,
required_kversion[0], required_kversion[1]), file=sys.stderr)
return -2
if int(linux_version.split('.')[0]) == required_kversion[0] and \
int(linux_version.split('.')[1]) < required_kversion[1]:
print('Using Linux Kernel {}, but {} requires > {}.{}.'.format(linux_version, __program_name__,
required_kversion[0], required_kversion[1]), file=sys.stderr)
return -2
# Check Linux Distro
self.cmd_lsb_release = shutil.which('lsb_release')
if self.cmd_lsb_release:
lsbr_out = subprocess.check_output(shlex.split('{} -a'.format(self.cmd_lsb_release)),
shell=False, stderr=subprocess.DEVNULL).decode().split('\n')
for lsbr_line in lsbr_out:
if 'Distributor ID' in lsbr_line:
lsbr_item = re.sub(r'Distributor ID:[\s]*', '', lsbr_line)
LOGGER.debug('Using Linux Distro: %s', lsbr_item)
self.distro['Distributor'] = lsbr_item.strip()
if 'Description' in lsbr_line:
lsbr_item = re.sub(r'Description:[\s]*', '', lsbr_line)
LOGGER.debug('Linux Distro Description: %s', lsbr_item)
self.distro['Description'] = lsbr_item.strip()
if self.distro['Distributor'] and self.DEBUG:
print('{}: '.format(self.distro['Distributor']), end='')
if self.distro['Distributor'] in GutConst._verified_distros: print('Validated')
else: print('Unverified')
else:
print('OS command [lsb_release] executable not found.')
LOGGER.debug('Distro: %s, %s', self.distro['Distributor'], self.distro['Description'])
# Check access/paths to system commands
command_access_fail = False
self.cmd_lspci = shutil.which('lspci')
if not self.cmd_lspci:
print('Error: OS command [lspci] executable not found.')
command_access_fail = True
LOGGER.debug('lspci path: %s', self.cmd_lspci)
self.cmd_clinfo = shutil.which('clinfo')
if not self.cmd_clinfo:
print('Package addon [clinfo] executable not found. Use sudo apt-get install clinfo to install')
LOGGER.debug('clinfo path: %s', self.cmd_clinfo)
# Package Reader
if self.distro['Distributor'] in GutConst._dpkg_tool:
pkg_tool = GutConst._dpkg_tool[self.distro['Distributor']]
self.cmd_dpkg = shutil.which(pkg_tool)
if not self.cmd_dpkg:
print('OS command [{}] executable not found.'.format(pkg_tool))
else:
for test_dpkg in GutConst._dpkg_tool.values():
self.cmd_dpkg = shutil.which(test_dpkg)
if self.cmd_dpkg:
break
else:
self.cmd_dpkg = None
LOGGER.debug('%s package query tool: %s', self.distro["Distributor"], self.cmd_dpkg)
self.cmd_nvidia_smi = shutil.which('nvidia-smi')
if self.cmd_nvidia_smi:
print('OS command [nvidia-smi] executable found: [{}]'.format(self.cmd_nvidia_smi))
if command_access_fail:
return -3
return 0
def read_amd_driver_version(self) -> bool:
"""
Read the AMD driver version and store in GutConst object.
:return: True on success.
"""
if not self.cmd_dpkg:
print('Can not access package read utility to verify AMD driver.')
return False
if re.search(r'([uU]buntu|[dD]ebian)', self.distro['Distributor']):
return self.read_amd_driver_version_debian()
if re.search(r'([gG]entoo)', self.distro['Distributor']):
return self.read_amd_driver_version_gentoo()
if re.search(r'([aA]rch)', self.distro['Distributor']):
return self.read_amd_driver_version_arch()
return False
def read_amd_driver_version_gentoo(self) -> bool:
"""
Read the AMD driver version and store in GutConst object.
:return: True if successful
"""
for pkgname in ['dev-libs/amdgpu', 'dev-libs/amdgpu-pro-opencl', 'dev-libs/rocm', 'dev-libs/rocm-utils']:
try:
dpkg_out = subprocess.check_output(shlex.split('{} list {}'.format(self.cmd_dpkg, pkgname)),
shell=False, stderr=subprocess.DEVNULL).decode().split('\n')
except (subprocess.CalledProcessError, OSError):
continue
for dpkg_line in dpkg_out:
if '!!!' in dpkg_line:
continue
for driverpkg in ['amdgpu', 'rocm']:
if re.search('Searching', dpkg_line):
continue
if re.search(driverpkg, dpkg_line):
LOGGER.debug(dpkg_line)
dpkg_line = re.sub(r'.*\][\s]*', '', dpkg_line)
print('AMD: {} version: {}'.format(driverpkg, dpkg_line))
return True
print('amdgpu/rocm version: UNKNOWN')
return False
def read_amd_driver_version_arch(self) -> bool:
"""
Read the AMD driver version and store in GutConst object.
:return: True if successful
"""
for pkgname in ['amdgpu', 'rocm', 'rocm-utils']:
try:
dpkg_out = subprocess.check_output(shlex.split('{} -Qs {}'.format(self.cmd_dpkg, pkgname)),
shell=False, stderr=subprocess.DEVNULL).decode().split('\n')
except (subprocess.CalledProcessError, OSError):
continue
for dpkg_line in dpkg_out:
for driverpkg in ['amdgpu', 'rocm']:
if re.search(driverpkg, dpkg_line):
LOGGER.debug(dpkg_line)
dpkg_items = dpkg_line.split()
if len(dpkg_items) >= 2:
print('AMD: {} version: {}'.format(driverpkg, dpkg_items[1]))
return True
print('amdgpu/rocm version: UNKNOWN')
return False
def read_amd_driver_version_debian(self) -> bool:
"""
Read the AMD driver version and store in GutConst object.
:return: True if successful
"""
for pkgname in ['amdgpu', 'amdgpu-core', 'amdgpu-pro', 'rocm-utils']:
try:
dpkg_out = subprocess.check_output(shlex.split('{} -l {}'.format(self.cmd_dpkg, pkgname)),
shell=False, stderr=subprocess.DEVNULL).decode().split('\n')
except (subprocess.CalledProcessError, OSError):
continue
for dpkg_line in dpkg_out:
for driverpkg in ['amdgpu', 'rocm']:
if re.search(driverpkg, dpkg_line):
LOGGER.debug(dpkg_line)
dpkg_items = dpkg_line.split()
if len(dpkg_items) > 2:
if re.fullmatch(r'.*none.*', dpkg_items[2]): continue
print('AMD: {} version: {}'.format(driverpkg, dpkg_items[2]))
return True
print('amdgpu/rocm version: UNKNOWN')
return False
GUT_CONST = GutConst()
def about() -> None:
"""
Display details of this module.
"""
print(__doc__)
print('Author: ', __author__)
print('Copyright: ', __copyright__)
print('Credits: ', *['\n {}'.format(item) for item in __credits__])
print('License: ', __license__)
print('Version: ', __version__)
print('Install Type: ', GUT_CONST.install_type)
print('Maintainer: ', __maintainer__)
print('Status: ', __status__)
sys.exit(0)
if __name__ == '__main__':
about()
gpu-utils-3.6.0/LICENSE 0000664 0000000 0000000 00000104515 14027501566 0014472 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
gpu-utils-3.6.0/MANIFEST.in 0000664 0000000 0000000 00000000042 14027501566 0015211 0 ustar 00root root 0000000 0000000 include README.md
include LICENSE
gpu-utils-3.6.0/README.md 0000664 0000000 0000000 00000047412 14027501566 0014746 0 ustar 00root root 0000000 0000000 # Ricks-Lab GPU Utilities

[](https://badge.fury.io/py/rickslab-gpu-utils)
[](https://pepy.tech/project/rickslab-gpu-utils)



## rickslab-gpu-utils
A set of utilities for monitoring GPU performance and modifying control settings.
In order to get maximum capability of these utilities, you should be running with a kernel that
provides support of the GPUs you have installed. If using AMD GPUs, installing the latest **amdgpu**
driver or **ROCm** package, may provide additional capabilities. If you have Nvidia GPUs installed,
you should have **nvidia-smi** installed in order for the utility reading of the cards to be
possible. Writing to GPUs is currently only possible for compatible AMD GPUs on systems with
appropriate kernel version with the AMD ppfeaturemask set to enable this capability as described
[here](https://github.com/Ricks-Lab/gpu-utils/blob/master/docs/USER_GUIDE.md#getting-started).
## Installation
There are 4 methods of installation available and summarized here:
* [Repository](https://github.com/Ricks-Lab/gpu-utils/blob/master/docs/USER_GUIDE.md#repository-installation) - This approach is recommended for those interested in contributing to the project or helping to troubleshoot an issue in realtime with the developer. This type of installation can exist alongside any of the other installation types.
* [PyPI](https://github.com/Ricks-Lab/gpu-utils/blob/master/docs/USER_GUIDE.md#pypi-installation) - Meant for users wanting to run the very latest version. All **PATCH** level versions are released here first. This installation method is also meant for users not on a Debian distribution.
* [Rickslab.com Debian](https://github.com/Ricks-Lab/gpu-utils/blob/master/docs/USER_GUIDE.md#rickslabcom-debian-installation) - Lags the PyPI release in order to assure robustness. May not include every **PATCH** version.
* **Official Debian** - Only **MAJOR/MINOR** releases. This is currently broken by the name change of the project from **ricks-amdgpu-utils** to **rickslab-gpu-utils**. I will update this guide once the Debian package is back in sync with the repository.
## User Guide
For a detailed introduction, a community sourced
[User Guide](https://github.com/Ricks-Lab/gpu-utils/blob/master/docs/USER_GUIDE.md)
is available. All tools are demonstrated and use cases are presented. Additions
to the guide are welcome. Please submit a pull request with your suggested additions!
## Commands
A summary of command line tools available in **rickslab-gpu-utils** follows. Additional
details are available in man pages and the
[User Guide](https://github.com/Ricks-Lab/gpu-utils/blob/master/docs/USER_GUIDE.md).
### gpu-chk
This utility verifies if the user's environment is compatible with **rickslab-gpu-utils**.
### gpu-ls
This utility displays most relevant parameters for installed and compatible GPUs. The
default behavior is to list relevant parameters by GPU. OpenCL platform information is
added when the *--clinfo* option is used. A brief listing of key parameters is available
with the *--short* command line option. A simplified table of current GPU state is
displayed with the *--table* option. The *--no_fan* can be used to ignore fan settings.
The *--pstate* option can be used to output the p-state table for each GPU instead of
the list of basic parameters. The *--ppm* option is used to output the table of available
power/performance modes instead of basic parameters.
### gpu-mon
A utility to give the current state of all compatible GPUs. The default behavior
is to continuously update a text based table in the current window until Ctrl-C is
pressed. With the *--gui* option, a table of relevant parameters will be updated
in a Gtk window. You can specify the delay between updates with the *--sleep N*
option where N is an integer > zero that specifies the number of seconds to sleep
between updates. The *--no_fan* option can be used to disable the reading and display
of fan information. The *--log* option is used to write all monitor data to a psv log
file. When writing to a log file, the utility will indicate this in red at the top of
the window with a message that includes the log file name. The *--plot* will display a
plot of critical GPU parameters which updates at the specified *--sleep N* interval. If
you need both the plot and monitor displays, then using the --plot option is preferred
over running both tools as a single read of the GPUs is used to update both displays.
The *--ltz* option results in the use of local time instead of UTC.
### gpu-plot
A utility to continuously plot the trend of critical GPU parameters for all compatible
GPUs. The *--sleep N* can be used to specify the update interval. The *gpu-plot*
utility has 2 modes of operation. The default mode is to read the GPU driver
details directly, which is useful as a standalone utility. The *--stdin* option
causes *gpu-plot* to read GPU data from stdin. This is how *gpu-mon* produces the
plot and can also be used to pipe your own data into the process. The *--simlog*
option can be used with the *--stdin* when a monitor log file is piped as stdin.
This is useful for troubleshooting and can be used to display saved log results.
The *--ltz* option results in the use of local time instead of UTC. If you plan
to run both *gpu-plot* and *gpu-mon*, then the *--plot* option of the *gpu-mon*
utility should be used instead of both utilities in order reduce data reads by
a factor of 2.
### gpu-pac
Program and Control compatible GPUs with this utility. By default, the commands to
be written to a GPU are written to a bash file for the user to inspect and run. If you
have confidence, the *--execute_pac* option can be used to execute and then delete the
saved bash file. Since the GPU device files are writable only by root, sudo is used to
execute commands in the bash file, as a result, you will be prompted for credentials in the
terminal where you executed *gpu-pac*. The *--no_fan* option can be used to eliminate
fan details from the utility. The *--force_write* option can be used to force all configuration
parameters to be written to the GPU. The default behavior is to only write changes.
## New in this Version - v3.6.0
* Rewrite of the installation guide and simplification of the readme.
* Roll-up all v3.5.x patches into a new minor revision release.
## Development Plans
* Implement timeout to handle cases where drivers become unreadable.
* Optimize plot utilities for performance.
* Add status read capabilities for Intel GPUs.
* Add pac capabilities for Nvidia GPUs.
## Known Issues
* Some windows do not support scrolling or resize, making it unusable for lower resolution installations.
* I/O error when selecting CUSTOM ppm. Maybe it requires arguments to specify the custom configuration.
* Doesn't work well with Fiji ProDuo cards.
* P-state mask gets intermittently reset for GPU used as display output.
* Utility *gpu-pac* doesn't show what the current P-state mask is. Not sure if that can be read back.
* Utility *gpu-pac* fan speed setting results in actual fan speeds a bit different from setting and pac interface shows actual values instead of set values.
## References
* Original inspiration for this project: [Reddit](https://www.reddit.com/r/Amd/comments/agwroj/how_to_overclock_your_amd_gpu_on_linux/?st=JSL25OVP&sh=306c2d15)
* Phoronix articles including these: [PowerCap](https://www.phoronix.com/scan.php?page=news_item&px=AMDGPU-Quick-WattMan-Cap-Test), [HWMon](https://www.phoronix.com/scan.php?page=news_item&px=AMDGPU-Linux-4.17-Round-1)
* Repositories: [amdgpu-clocks](https://github.com/sibradzic/amdgpu-clocks), [WattmanGTK](https://github.com/BoukeHaarsma23/WattmanGTK), [ROC-smi](https://github.com/RadeonOpenCompute/ROC-smi)
* Relevant Kernel Details: [Kernel Details](https://www.kernel.org/doc/html/latest/gpu/amdgpu.html)
* PCI ID Decode Table: [PCI IDs](https://pci-ids.ucw.cz/v2.2/pci.ids)
* Radeon VII discussion on Reddit: [Radeon VII OC](https://www.reddit.com/r/linux_gaming/duplicates/au7m3x/radeon_vii_on_linux_overclocking_undervolting/)
* Example use cases: [wiki.archlinux.org](https://wiki.archlinux.org/index.php/AMDGPU)
## History
### New in Previous Release - v3.5.10
* Set **Neon** as a validated distribution.
* Check all possible package readers for undefined distribution.
### New in Previous Release - v3.5.9
* Optimize *gpu-mon* table size.
* Toggle button color to match enable/disable status of plot line.
* When install type is repository, force use of repository *gpu-plot* from *gpu-mon*.
### New in Previous Release - v3.5.8
* Fixed bug in determining AMD GPU card type. Now it properly identifies APU and Legacy types.
### New in Previous Release - v3.5.7
* More robust determination of install type and display this with *--about* and in logger.
* Implementation of scroll within PAC window.
* Fixed plot crash for invalid ticker increment.
* Code robustness improvements with more typing for class variables.
### New in Previous Release - v3.5.6
* Fixed issue in reading AMD FeatureMask for Kernel 5.11
### New in Previous Release - v3.5.5
* Include debian release package.
* Check gtk initialization for errors and handle nicely.
* Use logger to output plot exceptions.
* Check number of compatible and readable GPUs at utility start.
* Minor User Guide and man page improvements.
* Use minimal python packages in requirements.
### New in Previous Release - [v3.5.0](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v3.5.0)
* Utilities now include reading of NV GPUs with full gpu-ls, gpu-mon, and gpu-plot support!
* Update name from **amdgpu-utils** to **rickslab-gpu-utils**.
* Improved PyPI packaging.
* Updated User Guide to cover latest features and capabilities.
* Improved robustness of NV read by validating sensor support for each query item the first time read. This will assure functionality on older model GPUs.
* Fixed issue in setting display model name for NV GPUs.
* Improved how lack of voltage readings for NV is handled in the utilities.
* Fixed an issue in assessing compute capability when GPUs of multiple vendors are installed.
### New in Previous Release - [v3.3.14](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v3.3.14)
* Display card path details in logger whenever card path exists.
* Implemented read capabilities for Nvidia. Now supported by all utilities except pac.
* Added APU type and tuned parameters read/displayed for AMD APU integrated GPU.
* Read generic pcie sensors for all types of GPUs.
* Improved lspci search by using a no-shell call and using compiled regex.
* Implement PyPI package for easy installation.
* More robust handling of missing Icon and PCIID files.
#### New in Previous Release - [v3.2.0](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v3.2.0)
* Fixed CRITICAL issue where Zero fan speed could be written when invalid fan speed was read from the GPU.
* Fixed issue in reading pciid file in Gentoo (@CH3CN).
* Modified setup to indicate minimum instead of absolute package versions (@smoe).
* Modified requirements to include min/max package versions for major packages.
* Fixed crash for missing pci-ids file and add location for Arch Linux (@berturion).
* Fixed a crash in *amdgpu-pac* when no fan details could be read (laptop GPU).
* Fixed deprecation warnings for several property setting functions. Consolidated all property setting to a single function in a new module, and ignore warnings for those that are deprecated. All deprecated actions are marked with FIXME in GPUgui.py.
* Replaced deprecated set properties statement for colors with css formatting.
* Implemented a more robust string format of datetime to address datetime conversion for pandas in some installations.
* Implemented dubug logging across the project. Activated with --debug option and output saved to a .log file.
* Updated color scheme of Gtk applications to work in Ubuntu 20.04. Unified color scheme across all utilities.
* Additional memory parameters added to utilities.
* Read ID information for all GPUs and attempt to decode GPU name. For cards with no card path entry, determine system device path and use for reading ID. Report system device path in *amdgpu-ls*. Add *amdgpu-ls --short* report to give brief description of all installed GPUs.
#### New in Previous Release - [v3.0.0](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v3.0.0)
* Style and code robustness improvements
* Deprecated *amdgpu-pciid* and removed all related code.
* Complete rewrite based on benchMT learning. Simplified code with ObjDict for GpuItem parameters and use of class variables for generic behavior parameters.
* Use lspci as the starting point for developing GPU list and classify by vendor, readability, writability, and compute capability. Build in potential to be generic GPU util, instead of AMD focused.
* Test for readability and writability of all GPUs and apply utilities as appropriate.
* Add assessment of compute capability.
* Eliminated the use of lshw to determine driver compatibility and display of driver details is now informational with no impact on the utilities.
* Add p-state masking capability for Type 2 GPUs.
* Optimized pac writing to GPUs.
#### New in Previous Release - [v2.7.0](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v2.7.0)
* Initial release of man pages
* Modifications to work with distribution installation
* Use system pci.ids file and make *amdgpu-pciid* obsolete
* Update setup.py file for successful installation.
#### New in Previous Release - [v2.6.0](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v2.6.0)
* PEP8 style modifications
* Fixed a bug in monitor display.
* Implement requirements file for with and without a venv.
* Found and fixed a few minor bugs.
* Fixed issue with *amdgpu-plot* becoming corrupt over time.
* Implemented clean shutdown of monitor and better buffering to plot. This could have caused in problems in systems with many GPUs.
#### New in Previous Release - [v2.5.2](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v2.5.2)
* Some preparation work for [Debian package](https://tracker.debian.org/pkg/ricks-amdgpu-utils) (@smoe).
* Added *--ltz* option to use local times instead of UTC for logging and plot data.
* Added 0xfffd7fff to valid amdgpu.ppfeaturemask values (@pastaq).
* Updates to User Guide to include instructions to apply PAC conditions on startup (@csecht).
#### New in Previous Release - [v2.5.1](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v2.5.1)
* Fixed a compatibility issue with matplotlib 3.x. Converted time string to a datetime object.
* Display version information for pandas, matplotlib, and numpy with the *--about* option for *amdgpu-plot*
#### New in Previous Release - [v2.5.0](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v2.5.0)
* Implemented the *--plot* option for amdgpu-monitor. This will display plots of critical GPU parameters that update at an interval defined by the *--sleep N* option.
* Errors in reading non-critical parameters will now show a warning the first time and are disabled for future reads.
* Fixed a bug in implementation of compatibility checks and improved usage of try/except.
#### New in Previous Release - [v2.4.0](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v2.4.0)
* Implemented *amdgpu-pac* feature for type 2 Freq/Voltage controlled GPUs, which includes the Radeon VII.
* Implemented the *amdgpu-pac --force_write* option, which writes all configuration parameters to the GPU, even if unchanged. The default behavior is changed to now only write changed configuration parameters.
* Indicate number of changes to be written by PAC, and if no changes, don't execute bash file. Display execute complete message in terminal, and update messages in PAC message box.
* Implemented a new GPU type 0, which represent some older cards whose p-states can not be changed.
* Tuned *amdgpu-pac* window format.
#### New in Previous Release - [v2.3.1](https://github.com/Ricks-Lab/amdgpu-utils/releases/tag/v2.3.1)
* Fixed and improved Python/Kernel compatibility checks.
* Added Python2 compatible utility to check *amdgpu-utils* compatibility.
* Fixed confusing mode/level fileptr names.
* Removed CUSTOM PPM mode until I figure out syntax.
* Implemented classification of card type based on how it implements frequency/voltage control. This is reported by *amdgpu-ls* and alters the behavior of both *amdgpu-pac* and *amdgpu-monitor*.
* Changed dpkg error to a warning to handle custom driver installs.
* Initial [User Guide](docs/USER_GUIDE.md) - [Need contributors!](https://github.com/Ricks-Lab/amdgpu-utils/issues/13)
#### New in Previous Release - v2.3.0
* Implemented a message box in amdgpu-pac to indicate details of PAC execution and indicate if sudo is pending credential entry.
* Implement more robust classification of card compatibility and only use compatible GPUs in the utilities.
* Official release of amdgpu-pciid which updates a local list of GPU names from the official pci.ids website.
* Optimized refresh of data by moving static items to a different function and only read those that are dynamic.
* Power Cap and Fan parameters can be reset by setting to -1 in the *amdgpu-pac* interface.
* Initial basic functionality for Radeon VII GPU!
#### New in Previous Release - v2.2.0
* Major bug fix in the way HWMON directory was determined. This fixes an issue in not seeing sensor files correctly when a some other card is resident in a PCIe slot.
* Implemented logging option *--log* for amdgpu-monitor. A red indicator will indicate active logging and the target filename.
* Implemented energy meter in amdgpu-monitor.
* Implemented the ability to check the GPU extracted ID in a pci.ids file for correct model name. Implemented a function to extract only AMD information for the pci.ids file and store in the file amd_pci_id.txt which is included in this distribution.
* Optimized long, short, and decoded GPU model names.
* Alpha release of a utility to update device decode data from the pci.ids website.
#### New in Previous Release - v2.1.0
* Significant bug fixes and error proofing. Added messages to stderr for missing driver related files.
* Added fan monitor and control features.
* Implemented --no_fan option across all tools. This eliminates the reading and display of fan parameters and useful for those who have installed GPU waterblocks.
* Implemented P-state masking, which limits available P-states to those specified. Useful for power management.
* Fixed implementation of global variables that broke with implementation of modules in library.
* Added more validation checks before writing parameters to cards.
#### New in Previous Release - v2.0.0
* Many bug fixes!
* First release of amdgpu-pac.
* Add check of amdgpu driver in the check of environment for all utilities. Add display of amdgpu driver version.
* Split list functions of the original amdgpu-monitor into amdgpu-ls.
* Added --clinfo option to amdgpu-ls which will list openCL platform details for each GPU.
* Added --ppm option to amdgpu-ls which will display the table of available power/performance modes available for each GPU.
* Error messages are now output to stderr instead stdout.
* Added power cap and power/performance mode to the monitor utilities. I have also included them in the amdgpu-ls display in addtion to the power cap limits.
#### New in Previous Release - v1.1.0
* Added --pstates feature to display table of p-states instead of GPU details.
* Added more error checking and exit if no compatible AMD GPUs are found.
#### New in Previous Release - v1.0.0
* Completed implementation of the GPU Monitor tool.
gpu-utils-3.6.0/docs/ 0000775 0000000 0000000 00000000000 14027501566 0014407 5 ustar 00root root 0000000 0000000 gpu-utils-3.6.0/docs/Type1vsType2.png 0000664 0000000 0000000 00000046064 14027501566 0017426 0 ustar 00root root 0000000 0000000 PNG
IHDR e eIy sRGB gAMA a pHYs od KIDATx^ŕg