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

使用Ray Serve部署模型时无法调用GPU的问题求助

解决Ray Serve部署中模型未使用GPU的问题
  • 核心问题:模型未显式绑定到GPU设备,且初始化方法存在语法错误
    你的代码里Translator类的初始化方法写成了init(缺少双下划线),导致该方法不会被正确调用;同时get_model仅加载模型,未将其移动到GPU,即使Ray分配了GPU资源,PyTorch默认仍会使用CPU。

  • 修复步骤:

    1. 修正类初始化方法
      将def init(self):改为def __init__(self):,确保实例化时能执行模型加载逻辑:

      @serve.deployment(num_replicas=2, ray_actor_options={"num_cpus": 0, "num_gpus": 1})
      class Translator:
          def __init__(self):  # 修正为双下划线的__init__
              self.model = get_model()
      
    2. 修改模型加载代码,绑定到GPU
      更新get_model函数,自动检测GPU并将模型移动到对应设备:

      import torch
      
      def get_model():
          model = LayoutLMv2ForQuestionAnswering.from_pretrained(model_checkpoint_finetuned)
          # 自动选择GPU,无GPU则 fallback 到CPU
          device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
          model = model.to(device)
          print(f'model loaded in device: {device}')
          return model
      
    3. 确保预测函数使用对应设备
      检查predict函数,需将输入数据移动到模型所在的GPU设备:

      def predict(model, count):
          # 将输入数据移至模型所在设备
          input_data = count.to(model.device)
          model_output = model(input_data)
          # 处理输出逻辑
          return model_output
      
    4. 验证GPU绑定状态
      可以在__init__中添加日志,确认模型设备:

      def __init__(self):
          self.model = get_model()
          # 打印模型所在设备,验证是否绑定GPU
          print(f"Model running on device: {next(self.model.parameters()).device}")
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:27:36