SYCL/DPC++运行程序时如何指定使用特定GPU设备?
SYCL/DPC++指定多GPU中目标设备的解决方案
默认的gpu_selector只会返回优先级最高的GPU设备,要指定非默认设备可以通过以下三种常用方案实现:
方案1:使用自定义索引选择器(代码内硬编码指定,稳定性高)
你可以通过继承device_selector类自定义选择逻辑,按设备序号选择第二块GPU(索引从0开始计数,第二块对应索引1):
class custom_gpu_selector : public device_selector { public: int operator()(const device &dev) const override { // 仅匹配GPU设备,返回数值越大优先级越高 if (dev.is_gpu()) { static int gpu_count = 0; // 选择索引为1的第二块GPU,要选第一块将1改为0即可 if (gpu_count++ == 1) { return 100; } } return -1; } };
使用时替换原来的gpu_selector{}为custom_gpu_selector{}即可。
方案2:使用环境变量指定(无需修改代码,灵活调试)
DPC++支持通过SYCL_DEVICE_FILTER环境变量全局指定使用的设备,不需要改动代码:
- Linux/macOS终端执行:
export SYCL_DEVICE_FILTER=gpu:1 - Windows Powershell执行:
$env:SYCL_DEVICE_FILTER = "gpu:1"
执行后再运行你的程序,就会自动选择序号为1的第二块GPU。如果需要指定后端,也可以写全格式:opencl:gpu:1、cuda:gpu:1、level_zero:gpu:1对应不同的 runtime 后端。
方案3:按设备名称匹配(设备型号不同时更准确)
如果两块GPU型号不同,你可以直接匹配目标设备的名称避免索引混乱:
class named_gpu_selector : public device_selector { public: int operator()(const device &dev) const override { if (dev.is_gpu()) { std::string dev_name = dev.get_info<info::device::name>(); // 替换成你目标GPU的实际名称,可以先运行下方的枚举代码查看 if (dev_name.find("NVIDIA A10") != std::string::npos) { return 100; } } return -1; } };
附1:枚举所有GPU设备信息的代码
你可以先运行以下代码打印所有GPU的序号、名称等信息,确认目标设备的标识:
#include <iostream> #include <CL/sycl.hpp> using namespace sycl; using namespace std; int main() { auto gpus = device::get_devices(info::device_type::gpu); cout << "系统共有" << gpus.size() << "块GPU:" << endl; for (int i = 0; i < gpus.size(); i++) { cout << "索引" << i << ":" << gpus[i].get_info<info::device::name>() << ",厂商:" << gpus[i].get_info<info::device::vendor>() << endl; } return 0; }
附2:修改后的完整测试代码
#include <iostream> #include <CL/sycl.hpp> using namespace sycl; using namespace std; class custom_gpu_selector : public device_selector { public: int operator()(const device &dev) const override { if (dev.is_gpu()) { static int gpu_count = 0; if (gpu_count++ == 1) return 100; } return -1; } }; int main() { queue my_gpu( custom_gpu_selector{} ); cout << "当前使用GPU设备:" << my_gpu.get_device().get_info<info::device::name>() << "\n"; return 0; }
内容的提问来源于stack exchange,提问作者sv6
相关产品推荐
相关产品推荐

