如何在 Presto UDF 中调用 CUDA Kernel 并管理 GPU 内存?
解读
国内金融、运营商、头部互联网公司的 Presto 集群普遍运行在 x86+GPU 的混合节点上,既要满足秒级 OLAP,又要复用已有的 CUDA 加速库(如 cuDF、cuBLAS)。面试官问“UDF 里怎么调 CUDA”,并不是让你写一段 JNI 那么简单,而是考察四点:
- 能否把 GPU 算子无缝嵌入 Presto 的向量化执行管线;
- 能否在 MPP 并发场景下保证 GPU 内存不 OOM、不泄漏;
- 能否让 Coordinator 在做 Cost-Based Optimizer 时感知 GPU 资源,决定要不要下推;
- 能否兼容 K8s 弹性节点,做到 GPU 的调度、隔离、监控一体化。
一句话:不是“能跑”,而是“能稳、能快、能管、能扩”。
知识点
- Presto UDF 生命周期:parse → analyze → plan → split → task → operator → pageProcessor → callSiteDescriptor。
- Presto 内存域:user、system、revocable、pool;GPU 显存不在其内,需自定义 MemoryContext。
- JNI 与 JCuda/JNI CUDA 0 拷贝:Pinned Memory + CUDA Host Register 可避免一次额外拷贝。
- Presto 的 Plugin SPI:FunctionProvider、FunctionNamespaceManager、Type、BlockEncoding。
- GPU 资源管理:CUDA Stream Pool、显存池化、RAII 包装、OOM 重试、spill-to-RDMA。
- 调度层面:K8s device-plugin 上报 GPU 核数/显存,Presto ResourceGroup 配置 gpu_weight,CBO 通过 ExternalCostProvider 把 GPU 代价换算成 CPU 等价核时。
- 容错:CUDA Kernel 异常时如何抛给 Presto 的 StandardErrorCode,触发 query retry 还是 worker restart。
- 安全:NVML 权限、容器 /dev/nvidia0 隔离、UDF SecurityManager 白名单。
答案
给出一个可直接落地的“GPU 加速 JSON 字符串解析 UDF”示例,演示调用路径与显存管理。
步骤 1:定义函数元数据
@SqlInvokedScalarFunction(value = "gpu_json_extract",
alias = "gpu_json_extract",
deterministic = true,
calledOnNullInput = false)
@Description("GPU accelerated json_extract, only support int64 path")
public final class GpuJsonExtractFunction {
public static final String GPU_JSON_EXTRACT = "gpu_json_extract";
}
步骤 2:Plugin 里注册 FunctionNamespaceManager
public class GpuPlugin implements Plugin {
@Override
public Iterable<FunctionNamespaceManagerFactory> getFunctionNamespaceManagerFactories() {
return ImmutableList.of(new GpuFunctionNamespaceManagerFactory());
}
}
步骤 3:在 GpuFunctionNamespaceManager 中生成 CallSiteDescriptor,把注解函数绑定到 JNI 实现
public class GpuFunctionNamespaceManager
extends SqlInvokedFunctionNamespaceManager {
static {
System.loadLibrary("presto_gpu");
}
// native 方法签名
private native long extractBatch(int rows, long[] offsets, long[] lengths,
byte[] data, long gpuMemPtr);
}
步骤 4:C++ 侧 JNI 实现(libpresto_gpu.so)
JNIEXPORT jlong JNICALL
Java_com_facebook_presto_gpu_GpuFunctionNamespaceManager_extractBatch(
JNIEnv *env, jobject, jint rows,
jlongArray jOffsets, jlongArray jLengths,
jbyteArray jData, jlong gpuMemPtr) {
// 1. 把 JVM heap 数据拷到 Pinned Host Memory(0 拷贝)
void* h_data = env->GetPrimitiveArrayCritical(jData, 0);
jlong *offsets = env->GetLongArrayElements(jOffsets, 0);
jlong *lengths = env->GetLongArrayElements(jLengths, 0);
// 2. 显存池化:gpuMemPtr 是预分配好的显存块,大小由 Presto MemoryContext 控制
char *d_data;
cudaSetDevice(0);
cudaMalloc((void**)&d_data, totalBytes);
cudaMemcpyAsync(d_data, h_data, totalBytes, cudaMemcpyHostToDevice, stream);
// 3. 启动 CUDA Kernel(每个线程处理一行 JSON)
int threads = 256;
int blocks = (rows + threads - 1) / threads;
json_extract_kernel<<<blocks, threads, 0, stream>>>(
d_data, d_offsets, d_lengths, d_result, rows);
// 4. 结果拷回 Host Pinned Memory
cudaMemcpyAsync(h_result, d_result, rows * sizeof(long), cudaMemcpyDeviceToHost, stream);
cudaStreamSynchronize(stream);
// 5. 释放 JVM critical 区
env->ReleasePrimitiveArrayCritical(jData, h_data, 0);
env->ReleaseLongArrayElements(jOffsets, offsets, 0);
env->ReleaseLongArrayElements(jLengths, lengths, 0);
// 6. 返回结果地址给 Presto,后续封装成 Block
return (jlong)h_result;
}
步骤 5:在 PageProcessor 里把 Block 转成 off-heap 地址,调 JNI,再把结果封装成 LongArrayBlock
public Block extractJson(Block jsonBlock, Block pathBlock) {
int positionCount = jsonBlock.getPositionCount();
long gpuMem = gpuMemoryPool.reserve(positionCount * 64); // 预估算
long resultAddr = extractBatch(positionCount, offsets, lengths, data, gpuMem);
long[] result = UnsafeUtil.copyMemoryToLongArray(resultAddr, positionCount);
gpuMemoryPool.release(gpuMem);
return new LongArrayBlock(positionCount, Optional.of(nulls), result);
}
步骤 6:内存池化与 OOM 重试
- 实现 GpuMemoryContext implements MemoryContext,内部维护一个 CUDA malloc 池,支持 reserve/tryReserve/release。
- 当 cudaMalloc 返回 out of memory 时,抛 PrestoException(GPU_OUT_OF_MEMORY),让 Coordinator 根据 retry policy 重试或调度到别的 GPU worker。
- 在 K8s 环境,通过 device-plugin 上报显存,ResourceGroup 配置 max_gpu_memory_per_query=8Gi,防止大查询挤爆卡。
步骤 7:CBO 代价注入
- 自定义 ExternalCostProvider,把 GPU 版本 json_extract 的 CPU 等价代价设为 0.2 核·秒,而 CPU 版本为 2 核·秒,优化器自动选择 GPU 路径。
- 若当前 worker 无空闲 GPU,则代价模型返回 +∞,强制走 CPU fallback。
步骤 8:监控与运维
- 通过 NVML 采集显存利用率,暴露 /metrics,接入 Prometheus;
- Grafana 面板同时展示 presto_query_gpu_time_ms 与 nvidia_gpu_memory_used_bytes;
- 当 GPU 利用率 <20% 且显存碎片率 >60% 时,触发 cudaDeviceReset() 并重启 worker,防止显存碎片。
拓展思考
- 多卡并发:Presto Worker 启动时扫描 NVML,把 8 张 A100 拆成 8 个 CUDA context,Task 粒度绑定 stream,如何避免 context switch 开销?
- 动态代码生成:把 GPU Kernel 也用 NVRTC 在线编译,与 Presto 的 Janino 字节码生成统一入口,实现“同一套表达式,CPU/GPU 双后端”。
- 数据格式零拷贝:Presto 的 ORC/DWRF reader 已经把数据拷到 off-heap,能否直接通过 CUDA Host Register 把 off-heap 地址映射给 GPU,从而省掉一次 cudaMemcpy?
- 安全沙箱:国内银行要求 UDF 必须跑在 Seccomp 沙箱,JNI 调 libcuda.so 会被拦截,如何用 userspace CUDA driver(如 Gdev)绕过?
- 云原生弹性:当 GPU 节点被 K8s Cluster Autoscaler 缩容时,Presto 的 Remote Task 如何优雅迁移,保证 GPU 显存里的中间结果不丢?是否要把 spill 做到 RDMA 共享显存?
把这些问题想透,面试就从“能写 JNI”升级到“能设计金融级 GPU 加速数仓”,基本稳过。