1 错误现象

  使用torch调用GPU时时出现以下错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 3: invalid start byte

2 原始代码

import torch

def test():
    x = torch.arange(2, 4, device='cuda')#直接创建
    print("直接创建:", x)
    y = torch.arange(2, 4)
    y = y.to('cuda', dtype=torch.double)#可以更改数据类型,使用y = y.cuda()亦可
    print("间接转换:", y)
    z = x + y
    print("转换回CPU:", z.to('cpu', dtype=torch.int))

if __name__ == '__main__':
    test()

3 问题解决

  出现该类错误的原因在于cuda未初始化,添加以下语句即可:

torch.cuda._initialized = True

  最终代码:

import torch

def test():
    torch.cuda._initialized = True#初始化
    x = torch.arange(2, 4, device='cuda')#直接创建
    print("直接创建:", x)
    y = torch.arange(2, 4)
    y = y.to('cuda', dtype=torch.double)#可以更改数据类型,使用y = y.cuda()亦可
    print("间接转换:", y)
    z = x + y
    print("转换回CPU:", z.to('cpu', dtype=torch.int))

if __name__ == '__main__':
    test()
Logo

电影级数字人,免显卡端渲染SDK,十行代码即可调用,工业级demo免费开源下载!

更多推荐