NLP工具——Stanza设置GPU device

NLP工具——Stanza设置GPU device

1. 简介

这篇博客介绍如何在stanza工具中修改设置device。由于stanza模型代码中只预留了设置cpu还是cuda,但是没有给出设置device的选项,这导致我们在多卡的情况下调用模型时不够灵活。所以本文对这一内容进行介绍。

原理很简单,把所有的.cuda()修改为.to(device)即可。此方法同样适用于其他开源项目。

2. 修改

pipeline/core.py中,修改:

class Pipeline的__init__中增加一个参数,device=None:

# self.use_gpu = torch.cuda.is_available() and use_gpu
# 修改为:
self.use_gpu = device

models/depparse/trainer.py中,修改:

# inputs = [b.cuda() if b is not None else None for b in batch[:11]]
# 修改为:
inputs = [b.to(torch.device(use_cuda)) if b is not None else None for b in batch[:11]]

models/lemma/trainer.py中,类似的修改:

# inputs = [b.cuda() if b is not None else None for b in batch[:6]]
# 修改为:
inputs = [b.to(torch.device(use_cuda)) if b is not None else None for b in batch[:6]]

# self.model.cuda()
# self.crit.cuda()
# 修改为:
self.model.to(torch.device(use_cuda))
self.crit.to(torch.device(use_cuda))

models/mwt/trainer.py中,也是类似的修改:

# inputs = [b.cuda() if b is not None else None for b in batch[:4]]
# 修改为
inputs = [b.to(torch.device(use_cuda)) if b is not None else None for b in batch[:4]]

# self.model.cuda()
# self.crit.cuda()
# 修改为:
self.model.to(torch.device(use_cuda))
self.crit.to(torch.device(use_cuda))

pipeline/sentiment_processor.py:

# self._model.cuda()
# 修改为:
self._model.to(torch.device(use_gpu))

models/tokenization/trainer.py同理:
所有.cuda()替换为.to(torch.device(self.use_cuda))

models/common/seq2seq_model.py:

# self.SOS_tensor = self.SOS_tensor.cuda() if self.use_cuda else self.SOS_tensor
# 修改为
if self.use_cuda.startswith('cuda'):
	self.SOS_tensor = self.SOS_tensor.to(torch.device(self.use_cuda))

# return h0.cuda(), c0.cuda()
# 修改为:
h0 = h0.to(torch.device(use_cuda))
c0 = c0.to(torch.device(use_cuda))

以上内容可能仍有遗漏,如果修改之后还是不行,则找到报错的py中,搜搜cuda,然后做出同样的修改即可。

如有疑问,欢迎留言。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值