pytorch使用——(十七)GPU运行

一、CPU与GPU

  • CPU(Central Processing Unit, 中央处理器):主要包括控制器和运算器
  • GPU(Graphics Processing Unit, 图形处理器):处理统一的,无依赖的大规模数据运算

二、转换数据类型/设备

  • tensor.to(*args, **kwargs),不执行inplace
  • module.to(*args, **kwargs),执行inplace
x = torch.ones((3, 3))
x = x.to(torch.float64)
x = torch.ones((3, 3))
x = x.to("cuda")
linear = nn.Linear(2, 2)
linear.to(torch.double)
gpu1 = torch.device("cuda")
linear.to(gpu1

三、 torch.cuda

  • torch.cuda.device_count():计算当前可见可用gpu数
  • torch.cuda.get_device_name():获取gpu名称
  • torch.cuda.manual_seed():为当前gpu设置随机种子
  • torch.cuda.manual_seed_all():为所有可见可用gpu设置随机种子
  • 5torch.cuda.set_device():设置主gpu为哪一个物理gpu(不推荐)

四、并行机制

1、功能:包装模型,实现分发并行机制

torch.nn.DataParallel(module, device_ids=None,output_device=None, dim=0

主要参数:
• module: 需要包装分发的模型
• device_ids: 可分发的gpu,默认分发到所有可见可用gpu
• output_device: 结果输出设备

2、查询当前gpu内存剩余

def get_gpu_memory():
import os
os.system('nvidia-smi -q -d Memory | grep -A4 GPU | grep Free > tmp.txt')
memory_gpu = [int(x.split()[2]) for x in open('tmp.txt', 'r').readlines()]
os.system('rm tmp.txt')
return memory_gpu

example:
gpu_memory = get_gpu_memory()
gpu_list = np.argsort(gpu_memory)[::-1]
gpu_list_str = ','.join(map(str, gpu_list))
os.environ.setdefault("CUDA_VISIBLE_DEVICES", gpu_list_str)
print("\ngpu free memory: {}".format(gpu_memory))
print("CUDA_VISIBLE_DEVICES :{}".format(os.environ["CUDA_VISIBLE_DEVICES"]))
>>> gpu free memory: [10362, 10058, 9990, 9990]
>>> CUDA_VISIBLE_DEVICES :0,1,3,2

 

 

### 如何检测 PyTorch 环境中 GPU 是否可用 为了确认 PyTorch 能够正确配置并使用 GPU,可以通过调用一系列函数来获取详细的设备信息。以下是完整的实现方式以及解释。 #### 方法一:通过 `torch.cuda` 检查 GPU 可用性 可以定义一个函数用于打印 GPU 的详细信息,包括是否可用、设备数量、名称和计算能力等[^1]: ```python import torch def check_gpu_availability(): print("\nGPU Details:") print(f"Is CUDA available? {torch.cuda.is_available()}") # 判断CUDA是否可用 if not torch.cuda.is_available(): print("No GPU detected or PyTorch is not built with CUDA support.") return device_count = torch.cuda.device_count() print(f"CUDA Device Count: {device_count}") # 获取GPU的数量 for i in range(device_count): print(f"Device Name (GPU-{i}): {torch.cuda.get_device_name(i)}") # 打印每张显卡的名字 print(f"Device Capability (GPU-{i}): {torch.cuda.get_device_capability(i)}") # 显卡的计算能力 check_gpu_availability() ``` 上述代码会输出当前环境中是否有支持 CUDA 的 GPU 设备及其具体属性。如果返回 `True` 并显示了具体的 GPU 名称,则说明环境已成功配置 GPU 支持。 --- #### 方法二:创建 Tensor 测试 GPU 加载 除了检查基本信息外,还可以尝试将数据加载到 GPU运行简单的操作以进一步验证其功能正常[^3]: ```python if torch.cuda.is_available(): tensor = torch.rand((3, 3)).cuda() # 创建随机矩阵并将它移动至GPU上 result = tensor @ tensor.T # 进行一次基本运算测试性能 print(result.cpu().numpy()) # 将结果转回CPU端并打印出来观察效果 else: print("Cannot perform operations on GPU because it's unavailable!") ``` 此段脚本不仅检验了硬件连接状态良好与否,还证明软件层面上能够顺利执行涉及深度学习框架内的核心任务——即利用 GPU 完成数值处理工作流的一部分。 --- #### 方法三:TensorFlow 对比验证(可选) 对于同时依赖多个 DL 库的情况来说,也可以采用 TensorFlow 来辅助判断是否存在兼容性的障碍或者潜在冲突问题[^2] : ```python import tensorflow as tf print("Number of GPUs Available:", len(tf.config.experimental.list_physical_devices('GPU'))) ``` 尽管这是针对另一个主流机器学习平台所设计的方法论之一,但它同样有助于排查某些特定场景下的异常现象比如驱动程序版本不匹配等问题。 综上所述,在实际开发过程中可以根据项目需求灵活选用以上任意一种或多种组合形式来进行全方位诊断分析从而保障最终部署方案稳定可靠高效运作!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值