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

如何指定TensorFlow SavedModel在C++中运行的设备?

强制TensorFlow 1.x C++模型在CPU运行(支持多模型分设备)

你完全可以通过**配置SessionOptions的ConfigProto**来指定模型的运行设备,不用依赖全局环境变量,这样就能实现一个模型跑CPU、另一个跑GPU的需求。具体做法如下:

核心思路

TensorFlow的SessionOptions允许你为每个会话单独配置设备使用策略。要强制模型在CPU运行,我们只需要在配置中告诉TensorFlow不要分配GPU设备,同时开启软放置(防止部分操作没有CPU实现时报错)。

修改后的代码示例

#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/core/protobuf/config.pb.h"

// 1. 创建并配置SessionOptions,强制使用CPU
tensorflow::SessionOptions session_options;
tensorflow::ConfigProto config;

// 开启软放置:如果某个操作没有CPU实现,自动 fallback 到可用设备(可选但建议)
config.set_allow_soft_placement(true);
// 告诉TensorFlow不使用GPU设备(设置GPU数量为0)
*config.mutable_device_count()->insert({"GPU", 0}).first->second = 0;

session_options.config = config;

// 2. 加载模型时传入配置好的session_options
std::unique_ptr<tensorflow::SavedModelBundle> bundle(new tensorflow::SavedModelBundle());
tensorflow::Status status = tensorflow::LoadSavedModel(
    session_options, tensorflow::RunOptions(), modelPath,
    {tensorflow::kSavedModelTagServe}, bundle.get());

// 检查加载状态
if (!status.ok()) {
    // 处理加载失败逻辑
    std::cerr << "Model load failed: " << status.ToString() << std::endl;
}

多模型分设备的实现方式

如果要同时运行两个模型(一个CPU、一个GPU),只需要为每个模型创建独立的SessionOptions:

  • 给CPU模型的SessionOptions设置device_count{"GPU": 0}
  • 给GPU模型的SessionOptions使用默认配置(或者根据需要设置GPU相关参数,比如显存分配比例)

这样两个模型的会话会各自使用指定的设备,互不干扰。

补充说明

  • allow_soft_placement设为true是为了兼容一些仅GPU实现的操作(不过大部分常用操作都有CPU版本),如果你的模型所有操作都有CPU实现,也可以设为false。
  • 这种方式是会话级别的配置,比全局环境变量CUDA_VISIBLE_DEVICES更灵活,能精准控制每个模型的设备使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:18:26