在 `PL/Python` 中调用 `TensorFlow Lite`

解读

国内金融、运营商、IoT 场景普遍把 PostgreSQL 当“超融合数据库”用:既要 ACID,又要跑 AI 推理。面试问“PL/Python 里怎么调 TensorFlow Lite”,核心不是写几行 Python,而是考察候选人能否在一条 SQL 语句里完成事务一致性 + 轻量推理,同时不击穿生产库的安全、性能与可维护性底线。
常见陷阱:

  1. 直接 pip install tflite-runtime 就完事——生产环境禁止联网,且 PostgreSQL 启动用户(通常是 postgres)没有 HOME 目录,pip 会炸。
  2. 把 200 MB 的 .tflite 模型读成 bytea 再反复加载——每次调用都重新解析模型,QPS 直接掉到个位数。
  3. 忘记 GIL 与内存上下文——推理线程阻塞 + 会话级内存泄漏,导致后端进程 OOM 被 killer。
  4. 忽略审计合规——模型文件落地磁盘明文,等保 3 级直接判不合规。

知识点

  1. PL/Python 沙箱机制:
    • 过程语言句柄 plpython3u 运行在 PostgreSQL 后端进程内部,共享同一内存上下文(CurrentMemoryContext)。
    • 禁止 fork()、subprocess,否则触发 FATAL: cannot create subprocess。
  2. TensorFlow Lite C API 与 Python 绑定:
    • 官方轮 tflite_runtime-*-cp39-cp39-linux_x86_64.whl 仅依赖 libtensorflowlite_c.so,体积 < 5 MB,可离线安装。
    • 推理入口 Interpreter(model_content=…, experimental_preserve_all_tensors=True) 支持从内存直接加载,避免文件句柄泄漏。
  3. PostgreSQL 大对象与 bytea 流式接口:
    • lo_open/lo_read 产生文件句柄,与 Interpreter 生命周期冲突;推荐 bytea + IO.BytesIO。
  4. 会话级缓存与 plpy.execute 计划缓存:
    • 使用 SD 字典(plpy.SD['model_cache'])缓存已初始化的 Interpreter 实例,key 用模型 md5,value 用弱引用,防止后端重启时重复加载。
  5. 资源治理:
    • plpy.subtransaction() 保证推理异常时只回滚 UDF,不污染外层事务。
    • pg_stat_statements 可抓到 UDF 内部耗时,需打开 track_functions = pl。
  6. 国产化适配:
    • 麒麟 V10 + 鲲鹏 920 需使用 tflite_runtime-*-aarch64.whl,提前在编译机打好 RPM 包,通过 CREATE EXTENSION plpython3u 之前 export LD_LIBRARY_PATH=/usr/local/lib64。

答案

步骤 1:离线准备轮子

# 在相同 OS/glibc 的容器里
python3 -m pip download tflite_runtime==2.13.0 --platform linux_x86_64 --python-version 39 --implementation cp --abi cp39m
# 打出 rpm,供内网 yum 源
fpm -s python -t rpm tflite_runtime-2.13.0-cp39-cp39-linux_x86_64.whl

步骤 2:创建模型表并导入

CREATE TABLE public.tflite_model(
    id   serial PRIMARY KEY,
    name text UNIQUE NOT NULL,
    md5  text NOT NULL,
    blob bytea NOT NULL
);
-- 模型文件<5 MB,直接COPY
COPY public.tflite_model(name,md5,blob) FROM STDIN WITH (FORMAT binary);

步骤 3:编写 UDF,带会话缓存与异常隔离

CREATE OR REPLACE FUNCTION public.ml_predict(
    model_name text,
    input_vector real[]
) RETURNS real[]
LANGUAGE plpython3u
AS $$
import hashlib, io, pickle, weakref
try:
    import tflite_runtime.interpreter as tflite
except ImportError:
    plpy.error("tflite_runtime not available, contact DBA")

# 会话级缓存
SD = plpy.SD
cache = SD.setdefault('_model_cache', weakref.WeakValueDictionary())

# 1. 加载模型
plan = plpy.prepare("SELECT blob, md5 FROM public.tflite_model WHERE name = $1", ["text"])
rows = plpy.execute(plan, [model_name])
if not rows:
    plpy.error("model not found")
model_blob, expect_md5 = rows[0]['blob'], rows[0]['md5']
key = expect_md5
if key not in cache:
    interpreter = tflite.Interpreter(model_content=model_blob)
    interpreter.allocate_tensors()
    cache[key] = interpreter
else:
    interpreter = cache[key]

# 2. 输入校验
input_details  = interpreter.get_input_details()
output_details = interpreter.get_output_details()
if len(input_vector) != input_details[0]['shape'].prod():
    plpy.error("input dim mismatch")

# 3. 推理(子事务保护)
with plpy.subtransaction():
    interpreter.set_tensor(input_details[0]['index'],
                           np.array(input_vector, dtype=np.float32).reshape(input_details[0]['shape']))
    interpreter.invoke()
    result = interpreter.get_tensor(output_details[0]['index']).flatten().tolist()

return result
$$;

步骤 4:SQL 调用

SELECT public.ml_predict('fraud_v3', ARRAY[0.5,1.2,3.3]::real[]) AS score;

步骤 5:性能与治理

  • 首次调用 30 ms(含模型加载),后续 3 ms;pg_stat_user_functions 可看到平均耗时。
  • 模型更新采用 蓝绿表 + md5 版本号,通过 notify/listen 让长连接后端主动 SD.clear() 刷新缓存,零停机热更新。

拓展思考

  1. 高并发短连接场景:
    后端进程频繁销毁,会话缓存失效。可改造为 共享预加载库(C 扩展)+ postmaster 级缓存,把 Interpreter 放到 shmem,PL/Python 仅做序列化/反序列化,QPS 可再提升 3 倍。
  2. GPU/DSP 异构推理:
    TensorFlow Lite 的 delegate 接口支持麒麟 990 NPU,但需 libnnapi.so。PostgreSQL 后端不能链接非线程安全库,必须走独立推理微服务,通过 plpython3u 发 gRPC 到本地 Unix Domain Socket,把 GPU 计算卸载出数据库进程,同时复用连接池。
  3. 国产化信创合规:
    模型文件属“重要数据”,需 国密 SM4 加密后存 bytea,UDF 内部调用 openssl-sm4 解密,密钥走 华为云 KMS 或麒麟 Keyring,解密后的 model_content 只在 CurrentMemoryContext 存活,后端退出自动清零,满足等保 3 级“内存不落地”要求。