You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中通过nvidia-smi获取MIG的GI-ID参数?

获取MIG分区GI-ID的Python实现方法

方法1:调用nvidia-smi命令解析输出

直接通过subprocess调用nvidia-smi工具,解析其输出提取GI-ID,适合快速实现:

XML格式解析(更全面的信息)

import subprocess
import xml.etree.ElementTree as ET

# 执行nvidia-smi获取XML格式的详细信息
cmd_result = subprocess.run(['nvidia-smi', '-q', '-x'], capture_output=True, text=True)
root = ET.fromstring(cmd_result.stdout)

# 遍历每个GPU的MIG实例
for gpu in root.findall('gpu'):
    mig_instances = gpu.findall('mig_current_gpu_instances/mig_current_gpu_instance')
    for idx, instance in enumerate(mig_instances):
        gi_id = instance.find('id').text
        print(f"GPU {gpu.find('index').text} - MIG实例{idx+1} GI-ID: {gi_id}")

CSV格式解析(仅提取GI-ID)

如果只需要GI-ID,用CSV格式输出更高效:

import subprocess

# 执行命令获取GI-ID列表
cmd_result = subprocess.run(
    ['nvidia-smi', '--query-gpu=mig.current_gpu_instance.id', '--format=csv,noheader'],
    capture_output=True, text=True
)
# 处理输出,过滤空行
gi_ids = [line.strip() for line in cmd_result.stdout.strip().split('\n') if line.strip()]
print(f"当前所有MIG分区GI-ID: {gi_ids}")

方法2:使用官方pynvml库(推荐)

pynvml是NVIDIA官方提供的Python绑定库,直接调用底层API获取MIG信息,稳定性更好:

  1. 先安装库:
pip install pynvml
  1. 示例代码:
import pynvml

# 初始化NVML库
pynvml.nvmlInit()

# 遍历所有GPU设备
device_count = pynvml.nvmlDeviceGetCount()
for device_idx in range(device_count):
    device_handle = pynvml.nvmlDeviceGetHandleByIndex(device_idx)
    try:
        # 检查MIG是否启用
        mig_enabled, _ = pynvml.nvmlDeviceGetMigMode(device_handle)
        if mig_enabled:
            # 获取当前运行的MIG实例列表
            mig_instances = pynvml.nvmlDeviceGetMigCurrentInstances(device_handle)
            for instance in mig_instances:
                print(f"GPU {device_idx} - GI-ID: {instance.instanceId}")
    except pynvml.NVMLError as err:
        print(f"GPU {device_idx} 无法获取MIG信息: {err}")

# 关闭NVML库
pynvml.nvmlShutdown()

注意事项

  • 确保Python进程拥有访问NVIDIA设备的权限(如root或加入video用户组)
  • pynvml版本需与本地NVIDIA驱动版本匹配,版本不兼容可能导致API调用失败
  • 容器环境下需确保挂载了MIG相关的设备节点(如/dev/nvidia-mig*)

内容的提问来源于stack exchange,提问作者Gota_12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:55:01