Mingyu's Library主页
深度学习文档 · 2026-08-17 Deep Dive · 2026-08-17

当服务器看不见你的数据也能推理:同态加密与 Google HEIR

Inference When the Server Never Sees Your Data: Homomorphic Encryption and Google HEIR

2026 年 8 月 14 日,Google 开源了 HEIR —— 一个能把普通模型自动改写成「在密文上跑」的编译器。这份文档讲清楚:它到底做了什么、怎么上手、什么场景值得用、以及为什么它仍然很慢。

On August 14, 2026, Google open-sourced HEIR — a compiler that rewrites ordinary models so they run directly on ciphertexts. This document covers what it actually does, how to get started, where it's worth using, and why it is still slow.

调研时间:2026-08-17覆盖:是什么 / 怎么用 / 什么场景 / 和谁比 / 有什么坑全部事实标注来源
Researched: 2026-08-17Covers: what / how / where / vs. alternatives / pitfallsEvery claim sourced

30 秒速览

The 30-second version

今天几乎所有云端 AI 都有一个默认前提:你得先把明文数据交给服务器。同态加密(Homomorphic Encryption,简称 HE)推翻了这个前提——它让服务器能在加密后的数据上直接做计算,算完返回一个加密结果,只有你手上的密钥能解开。整个过程中服务器从没见过明文。

Nearly all cloud AI today assumes one thing: you hand the server your plaintext data first. Homomorphic encryption (HE) removes that assumption — the server computes directly on encrypted data, returns an encrypted result, and only your key can open it. The server never sees plaintext at any point.

这不是新想法,但一直卡在两件事上:太慢,以及太难写。Google 的 HEIR 攻的是第二件。Google 官方博客(2026-08-14)的说法是:「手工把一个现有程序高效改造成同态加密版本,需要一支密码学团队」;HEIR 的目标是让你「用 Python 写程序,标注哪些类型是 secret,剩下的交给 HEIR 编译」。

This isn't a new idea, but it has been stuck on two problems: it's too slow, and it's too hard to write. Google's HEIR attacks the second. As Google's blog put it (2026-08-14): "manually converting an existing program to use homomorphic encryption efficiently requires a team of cryptographers." HEIR's pitch is that you "write a program in Python, annotate the types to mark which are secret, and HEIR will compile the rest."

同一个需求,三条路线 ① 明文上云(今天的默认) 明文数据 云端模型 能力最强,但服务器完整看到你的数据 · 泄露 / 合规风险 👁️ ② 纯本地推理 明文数据 本机模型 数据不出门,但受限于本机算力;把模型发到端上又会泄露模型 IP 📵 ③ 密文推理(HE / HEIR) 🔒 密文 云端密文计算 🔑 本地解密 服务器算得出结果,但全程看不见明文 —— 代价是慢 10³–10⁵ 倍 🙈
图 1:同一个「云端推理」需求的三条路线。密文推理把「能力 vs 隐私」的取舍,换成了「隐私 vs 成本」的取舍。
One need, three routes 1. Plaintext to cloud (today's default) plaintext cloud model Most capable, but the server sees everything · breach and compliance risk 👁️ 2. On-device only plaintext local model Data stays home, but device compute limits you; shipping the model leaks its IP 📵 3. Encrypted inference (HE / HEIR) 🔒 ciphertext compute on ciphertext 🔑 decrypt locally The server produces a result without ever seeing plaintext — at 10³–10⁵× the cost 🙈
Fig. 1 — Three routes to the same "cloud inference" need. Encrypted inference swaps a capability-vs-privacy trade-off for a privacy-vs-cost one.
一句话 In one line HEIR 是一个基于 MLIR 的开源 FHE 编译器工具链,由 Google 维护,目标是成为「FHE 领域的行业标准编译器」。它不是让 FHE 变快的魔法,而是把「写 FHE 程序」这件事从密码学工程降级成编译器配置。 HEIR is an MLIR-based open-source FHE compiler toolchain maintained by Google, aiming to be "the industry-standard compiler for FHE." It is not magic that makes FHE fast; it demotes "writing an FHE program" from cryptography engineering to compiler configuration.

1. 为什么需要它:端到端加密留下的那个洞

1. Why it exists: the hole left by end-to-end encryption

先讲痛点,再讲定义。

Motivation first, definitions later.

Google 的博客把问题说得很直接:标准的端到端加密其实是一笔交易——用户数据能防住数据泄露,但服务提供方也因此没法再提供任何依赖这份数据的功能,比如垃圾邮件检测、病毒检测。

Google's post states the problem plainly: standard end-to-end encryption is a trade-off — user data is protected from breaches, but the service provider then cannot provide any feature that depends on that data, such as spam or virus detection.

那把计算搬到本地呢?博客也否掉了:本地处理「受限于本地设备的能力,以及服务方 IP 的敏感度」——把专有模型发到设备上,就有模型被窃取的风险。所以这是一个三方为难的局面:数据敏感、算力在云上、模型也是资产。

What about moving compute to the device? The post rules that out too: local processing is "limited by the capabilities of the local device and the sensitivity of the service provider's IP" — shipping a proprietary model to a device risks leaking the model. So it is a three-way bind: the data is sensitive, the compute is in the cloud, and the model is itself an asset.

类比:委托冲印底片 Analogy: developing a film negative

你要把一卷底片送去冲印店。传统做法是把底片交出去——店员看得到每一张照片。同态加密相当于:你把底片装进一个特制暗盒,店员的机器能隔着盒子完成冲印的每一道工序,取出来的成品还在盒子里,只有你手上的钥匙能打开。店员全程知道自己在「冲印」,但从没看过任何一张画面。

You send a roll of film to a lab. Normally you hand over the negatives — the technician sees every frame. Homomorphic encryption is like sealing the roll in a special light-tight box: the lab's machine performs every step of development through the box, and the finished prints come out still inside it, openable only with your key. The technician knows they were developing film, but never saw a single frame.

这件事对哪些行业最要紧?博客点名了医疗和金融——这些领域「对风险更加厌恶,而且严格的法规限制了机构之间的数据共享」。这正是密文推理的价值所在:它不是让现有产品更快,而是让某些本来根本不可能上云的工作负载变得可能。

Which industries care most? The post names healthcare and finance — sectors that are "even more averse to these risks," where "strict regulations limit data sharing across institutions." That is where the value sits: encrypted inference doesn't make existing products faster, it makes certain workloads that could never have gone to the cloud at all possible.

关键转换The key reframing 博客里最值得记住的一句:同态加密「有不小的成本开销,但它把『能力 / 隐私』的取舍,转换成了一个成本问题。而同态加密的成本正在快速下降。」——这是判断这条路线是否值得押注的核心论点。 The most quotable line: homomorphic encryption "has a nontrivial cost overhead, [but] it shifts the capability/privacy trade-off to a question of cost. And the cost of homomorphic encryption is rapidly decreasing." That single reframing is the whole bet.

2. 核心概念:噪声、bootstrapping,和为什么非线性这么贵

2. Core concepts: noise, bootstrapping, and why nonlinearity is expensive

理解这三件事,就能理解 FHE 的全部成本结构。

Understand these three things and you understand FHE's entire cost structure.

同态加密(Homomorphic Encryption, HE)
Homomorphic Encryption (HE)
一种加密方式,它的特别之处是:对密文做运算,等价于对明文做同样的运算。你加密 3 和 5 得到两坨乱码,把这两坨乱码相加得到第三坨乱码,解密出来正好是 8。服务器全程只碰乱码。
An encryption scheme with one special property: computing on ciphertexts is equivalent to computing on the underlying plaintexts. Encrypt 3 and 5, get two blobs; add the blobs, get a third blob; decrypt it and you get exactly 8. The server only ever touched blobs.
「Fully(全)同态加密」FHE 指的是加法和乘法都支持、且可以任意次组合——因为任何计算原则上都能拆成加法和乘法,所以理论上什么都能算。
"Fully" homomorphic encryption (FHE) means both addition and multiplication are supported and can be composed arbitrarily — since any computation can in principle be decomposed into additions and multiplications, anything is computable in theory.

2.1 噪声:每做一次运算,密文就「脏」一点

2.1 Noise: every operation makes the ciphertext a bit dirtier

这是 FHE 最反直觉、也最决定成本的一点。为了保证安全性,加密时会往密文里掺入随机噪声。问题是:每做一次同态运算,噪声都会变大——而且乘法比加法涨得凶得多。研究文献的描述是:噪声在若干次运算后会指数级增长,一旦超过阈值,解密出来的就是垃圾。

This is FHE's most counter-intuitive property and the one that sets its cost. For security, encryption mixes random noise into the ciphertext. The catch: every homomorphic operation grows that noise — and multiplication grows it far faster than addition. The literature describes noise as increasing exponentially after several operations; past a threshold, decryption returns garbage.

Bootstrapping(自举)
Bootstrapping
给一个「脏了」的密文做清洗,把噪声降回低水平,让它还能继续参与运算。文献里的说法是:bootstrapping 用来降低密文中因多次运算而指数增长的噪声,刷新密文,使解密不会因失控的噪声而出错。
A refresh operation that scrubs a "dirty" ciphertext back to a low noise level so it can keep being computed on. As the literature puts it: bootstrapping reduces the noise that grows exponentially after several operations, refreshing ciphertexts so decryption is not corrupted by uncontrolled noise.
代价:bootstrapping 是 FHE 里最昂贵的单个操作。整个 FHE 编译优化领域,很大一部分工作就是在算「什么时候必须 bootstrap、能不能少 bootstrap 几次」。
The cost: bootstrapping is the single most expensive operation in FHE. A large slice of the entire FHE compiler-optimization field is about computing when a bootstrap is unavoidable and how to need fewer of them.
噪声预算:FHE 程序真正的「油箱」 噪声 运算次数 → 解密失败阈值 ♻️ ♻️ ♻️ bootstrap 加法:涨得慢 乘法:涨得快 每次 bootstrap 把噪声压回低位,但它是 FHE 里最贵的单个操作 —— 编译器的核心任务之一就是让这些 ♻️ 尽可能少。
图 2:噪声预算模型。曲线爬向红线代表密文即将不可解密;♻️ 是 bootstrapping 把噪声重置回去。
Noise budget: the real fuel tank of an FHE program noise operations → decryption failure threshold ♻️ ♻️ ♻️ bootstrap addition: slow growth multiplication: fast growth Each bootstrap resets noise, but it is the costliest single FHE operation — minimising those ♻️ marks is a core compiler job.
Fig. 2 — The noise budget model. The curve climbing toward the red line means the ciphertext is about to become undecryptable; ♻️ marks a bootstrap that resets it.

2.2 为什么神经网络在 FHE 下特别难

2.2 Why neural networks are especially hard under FHE

FHE 天生擅长加法和乘法,而神经网络里的矩阵乘法恰好就是这两样——这部分其实还好。真正的麻烦是非线性激活:ReLU、Softmax、GELU 这些函数没法用有限次加乘直接表达。

FHE is natively good at addition and multiplication, and a neural network's matrix multiplications are exactly that — so that part is manageable. The real trouble is nonlinear activations: ReLU, Softmax, GELU cannot be expressed directly with a finite number of adds and multiplies.

通行做法是用高次多项式去逼近它们。但多项式次数越高,乘法链就越深,噪声涨得越猛,越早需要 bootstrapping。研究文献总结得很精炼:FHE 与 Transformer 架构相冲突——「僵硬的密文打包要求昂贵的旋转操作,而非线性所需的深层多项式电路又迫使昂贵的 bootstrapping」。

The standard workaround is to approximate them with high-degree polynomials. But higher degree means a deeper multiplication chain, faster noise growth, and an earlier bootstrap. The literature puts it crisply: FHE clashes with transformer architectures, where "rigid ciphertext packing demands expensive rotations, and deep polynomial circuits for nonlinearities necessitate costly bootstrapping."

换个说法:为什么 ReLU 这么麻烦? Put differently: why is ReLU such a headache?

ReLU 的定义是「大于 0 就保留,小于 0 就归零」——它需要比较。而密文里的数你根本看不见,没法比较。于是只能画一条尽量像 ReLU 的光滑曲线去替代它,而画得越像,曲线的多项式次数就越高,计算就越贵。在 HEIR 的 MLIR 输入里,这个取舍是明写出来的一个参数:degree = 6,配合 lower / upper 指定逼近的取值范围。

ReLU says "keep it if positive, zero it if negative" — that requires a comparison. Inside a ciphertext you cannot see the value, so you cannot compare. The fix is to draw a smooth curve that resembles ReLU, and the closer the resemblance, the higher the polynomial degree and the higher the cost. In HEIR's MLIR input this trade-off is an explicit parameter: degree = 6, alongside lower / upper bounds for the approximation range.

2.3 打包(packing):一次算一批,把成本摊薄

2.3 Packing: batch many values into one ciphertext to amortise cost

既然单次密文运算这么贵,自然的优化是:一个密文里塞很多个数,一次运算同时算完——这就是 SIMD 打包。CKKS 方案「在近似实数上计算,配合大量 SIMD 打包,使它成为机器学习和统计场景的首选方案」。

Since a single ciphertext operation is so costly, the natural optimisation is to pack many values into one ciphertext and process them in a single operation — SIMD packing. CKKS "computes on approximate real numbers with heavy SIMD packing, making it the scheme of choice for machine learning and statistics."

代价是:数据在密文的哪个「槽位」(slot)上,就变成了一个需要优化的问题。要把两个不在同一槽位的数加起来,得先做旋转(rotation)把它们对齐,而旋转本身也不便宜。HEIR 把这件事抽象成了「布局(layout)」,并用整数集合库(ISL)做多面体优化来选最优布局——这是它区别于手写 FHE 代码的核心价值之一。

The cost: which "slot" a value sits in becomes an optimisation problem of its own. Adding two values in different slots requires a rotation to align them first, and rotations are not cheap either. HEIR abstracts this as a "layout" and uses the Integer Set Library for polyhedral optimisation over layouts — one of its core advantages over hand-written FHE code.

3. 怎么用 HEIR:三条入口,从最轻的开始

3. How to use HEIR: three entry points, lightest first

以下命令与代码全部来自 HEIR 官方 Getting Started 文档(该页最后更新:2026-08-11)。

All commands and code below come from HEIR's official Getting Started page (last updated 2026-08-11).

先看清项目当前状态Know the project's current state first 官方文档明确写着:HEIR 团队仍在开发某些工作流(比如把预编译的 torch 模型转到指定后端)的端到端二进制;目前的用法是通过 heir-opt(跑编译 pass)和 heir-translate(后端代码生成)这两个「大杂烩」二进制。另外,预构建的 nightly 二进制官方说明是「用于测试编译器 pass,不用于生产」。 The docs say plainly that the HEIR team is still working on an end-to-end binary for certain workflows (such as converting pre-compiled torch models to a specific backend); in the meantime you use the "kitchen sink" binaries heir-opt (compiler passes) and heir-translate (backend codegen). The prebuilt nightly binary is also explicitly "intended for testing compiler passes and not for production use."

入口 A:pip 装,用 Python 装饰器(最快上手)

Entry A: pip install and use the Python decorator (fastest)

官方发布了 Python 包 heir_py,里面带 heir-optheir-translate 二进制,还可选带前后端:

There is an official Python package, heir_py, which bundles the heir-opt and heir-translate binaries and optionally front- and backends:

python -m venv venv
source venv/bin/activate

pip install "heir_py[python,openfhe]"

heir-opt --help
heir-translate --help
来源:HEIR Getting Started · Via pip
Source: HEIR Getting Started · Via pip

装好支持的后端(如 OpenFHE)后,就能用装饰器写「密文函数」。注意 Secret[I64] —— 这就是官方说的「标注哪些类型是 secret」:

With a supported backend installed (e.g. OpenFHE), you can write an encrypted function with a decorator. Note Secret[I64] — this is the "annotate the types to mark which are secret" part:

from heir import compile
from heir.mlir import I64, Secret

@compile()  # defaults to scheme="bgv", OpenFHE backend, and debug=False
def func(x: Secret[I64], y: Secret[I64]):
    sum = x + y
    diff = x - y
    mul = x * y
    expression = sum * diff + mul
    deadcode = expression * mul
    return expression

func.setup()
enc_x = func.encrypt_x(7)
enc_y = func.encrypt_y(8)
result_enc = func.eval(enc_x, enc_y)
result = func.decrypt_result(result_enc)
来源:HEIR Getting Started · Via pip。默认使用 BGV 方案 + OpenFHE 后端。
Source: HEIR Getting Started · Via pip. Defaults to the BGV scheme with the OpenFHE backend.
两个官方注意事项Two official caveats ① 必须自己装 OpenFHE——因为 Python 前端会调用 C++ 编译器编译 HEIR 生成的代码并链接 OpenFHE,而 OpenFHE 的安装是随系统而异的(比如 OpenMP 配置)。② 文档写明:除 OpenFHE 外的后端支持仍在推进中 (1) You must install OpenFHE yourself — the Python frontend invokes a C++ compiler on HEIR-generated code and links against OpenFHE, and that installation is system-specific (e.g. OpenMP configuration). (2) The docs state that support for backends besides OpenFHE is in progress.

入口 B:直接跑编译管线(看清中间发生了什么)

Entry B: run the compiler pipeline directly (see what actually happens)

官方的 dot-product 例子最能说明 HEIR 在做什么。输入是一段 MLIR,注意参数上的 {secret.secret} 标注——这就是全部的「加密声明」:

The official dot-product example is the clearest illustration. The input is MLIR; note the {secret.secret} annotation on the arguments — that is the entire "encryption declaration":

func.func @dot_product(%arg0: tensor<8xi16> {secret.secret},
                       %arg1: tensor<8xi16> {secret.secret}) -> i16 {
  %c0 = arith.constant 0 : index
  %c0_si16 = arith.constant 0 : i16
  %0 = affine.for %arg2 = 0 to 8 iter_args(%iter = %c0_si16) -> (i16) {
    %1 = tensor.extract %arg0[%arg2] : tensor<8xi16>
    %2 = tensor.extract %arg1[%arg2] : tensor<8xi16>
    %3 = arith.muli %1, %2 : i16
    %4 = arith.addi %iter, %3 : i16
    affine.yield %4 : i16
  }
  return %0 : i16
}
来源:HEIR 仓库 tests/Examples/common/dot_product_8.mlir
Source: HEIR repo, tests/Examples/common/dot_product_8.mlir
  1. 编译成 scheme 层 IR把普通程序降级成 BGV 方案的密文操作,再转成 OpenFHE 出口方言。
    heir-opt \
      --mlir-to-bgv='min-slot-count=8' \
      --scheme-to-openfhe='entry-function=dot_product' \
      dot_product_8.mlir > output.mlir
  2. 生成后端代码heir-translate 产出 OpenFHE 的 C++ 头文件和实现。
    heir-translate --emit-openfhe-pke-header \
      --openfhe-include-type=source-relative output.mlir > heir_output.h
    heir-translate --emit-openfhe-pke \
      --openfhe-include-type=source-relative output.mlir > heir_output.cpp
  3. 像普通 OpenFHE 程序一样编译运行生成的文件里除了主函数,还自动带了 __encrypt__argN / __decrypt__result0 / __generate_crypto_context / __configure_crypto_context 这几个客户端辅助函数。官方示例的运行结果是 Expected: 240 / Actual: 240
  1. Compile to scheme-level IR.Lower the ordinary program to BGV ciphertext operations, then to the OpenFHE exit dialect.
    heir-opt \
      --mlir-to-bgv='min-slot-count=8' \
      --scheme-to-openfhe='entry-function=dot_product' \
      dot_product_8.mlir > output.mlir
  2. Emit backend code.Use heir-translate to produce the OpenFHE C++ header and implementation.
    heir-translate --emit-openfhe-pke-header \
      --openfhe-include-type=source-relative output.mlir > heir_output.h
    heir-translate --emit-openfhe-pke \
      --openfhe-include-type=source-relative output.mlir > heir_output.cpp
  3. Build and run it like any OpenFHE program.Besides the main function, the generated files include client helpers: __encrypt__argN, __decrypt__result0, __generate_crypto_context and __configure_crypto_context. The official example prints Expected: 240 / Actual: 240.

最能说明「编译器在替你想事情」的是生成出来的 C++:一个朴素的循环点积,被编译成了旋转-归约(rotate-and-reduce)模式——先做一次密文乘法和 relinearize,然后按 4、2、1 三次旋转累加,而不是老老实实循环 8 次。这正是手写 FHE 代码时需要密码学经验才能想到的优化。

The clearest sign that the compiler is thinking for you is the generated C++: a naive loop-based dot product compiles into a rotate-and-reduce pattern — one ciphertext multiply plus relinearize, then rotations by 4, 2 and 1 with accumulation, rather than eight literal loop iterations. That is exactly the optimisation that hand-written FHE code needs cryptography experience to find.

const auto& v4  = v0->EvalMultNoRelin(v1, v2);
const auto& v5  = v0->Relinearize(v4);
const auto& v6  = v0->EvalRotate(v5, 4);
const auto& v7  = v0->EvalAdd(v5, v6);
const auto& v8  = v0->EvalRotate(v7, 2);
const auto& v9  = v0->EvalAdd(v7, v8);
const auto& v10 = v0->EvalRotate(v9, 1);
const auto& v11 = v0->EvalAdd(v9, v10);
来源:HEIR Getting Started 生成的 heir_output.cpp 节选(rotate-and-reduce 模式)
Source: excerpt from the generated heir_output.cpp in HEIR's Getting Started (rotate-and-reduce pattern)

入口 C:bazel + rules_heir(工程化集成)

Entry C: bazel + rules_heir (engineering integration)

如果项目用 bazel,官方推荐 rules_heir,它把连接 HEIR 与应用的大量细节藏了起来。核心是一个 heir_lattigo_lib 宏,把 heir-opt / heir-translate 的 flag 写在 BUILD 文件里:

If your project uses bazel, the docs recommend rules_heir, which hides most of the wiring between HEIR and your application. The core is a heir_lattigo_lib macro that puts the heir-opt / heir-translate flags in your BUILD file:

heir_lattigo_lib(
    name = "hello_world",
    go_library_name = "helloworld",
    heir_opt_flags = [
        "--annotate-module=backend=lattigo scheme=ckks",
        "--mlir-to-ckks=min-slot-count=2048 first-mod-bits=0",
        "--scheme-to-lattigo",
    ],
    mlir_src = "hello_world.mlir",
    split_preprocessing = False,
)
来源:HEIR Getting Started · Using bazel and rules_heir(此例走 CKKS 方案 + Lattigo 后端)
Source: HEIR Getting Started · Using bazel and rules_heir (this example uses the CKKS scheme with the Lattigo backend)
从源码构建 / 用 nightly 二进制 Building from source / using the nightly binary

从源码构建只需 Git 和 bazelisk,其余依赖(C++/Go/Rust 编译器、Python 解释器)全由 bazel 管理:git clone git@github.com:google/heir.git && cd heir,然后 bazel build -c opt @heir//tools:heir-opt。注意 Linux 上不能用 root 身份跑 bazel。想省事就下 nightly 二进制(记住:仅供测试,不用于生产):wget -O heir-opt https://github.com/google/heir/releases/download/nightly/heir-opt-manylinux_2_28_x86_64

Building from source needs only Git and bazelisk; bazel manages everything else (C++/Go/Rust compilers, Python interpreter): git clone git@github.com:google/heir.git && cd heir, then bazel build -c opt @heir//tools:heir-opt. Note that on Linux your user must not be root. For a shortcut, grab the nightly binary (testing only, not production): wget -O heir-opt https://github.com/google/heir/releases/download/nightly/heir-opt-manylinux_2_28_x86_64.

4. 编译管线拆解:一个 PyTorch 模型是怎么变成密文程序的

4. Inside the pipeline: how a PyTorch model becomes an encrypted program

这一节的内容来自 HEIR 官方设计文档「ML with HEIR」及其对应论文 arXiv:2508.11095。

This section draws on HEIR's official design page "ML with HEIR" and its companion paper, arXiv:2508.11095.

HEIR 的 ML 前端把 PyTorch、TensorFlow、ONNX 三条路,分别经由 torch-mlironnx-mlirStableHLO 汇聚到一个统一的入口层:MLIR 的 linalg 方言。文档解释了为什么选 linalg——这个抽象层级刚好能匹配 ML 的 kernel 操作做优化。

HEIR's ML frontend funnels PyTorch, TensorFlow and ONNX — via torch-mlir, onnx-mlir and StableHLO respectively — into a single entry level: MLIR's linalg dialect. The docs explain the choice: that abstraction level is the one at which ML kernel operations can be matched for optimisation.

HEIR 的分层结构:每一层解决一类问题 前端 PyTorch · TensorFlow · ONNX → torch-mlir / onnx-mlir / StableHLO 标准 MLIR(入口层) func · linalg · tensor · arith · affine —— 在这里做规范化与非线性简化 密文算术层 secret · tensor_ext · mgmt · polynomial · comb —— 布局、kernel、噪声管理都在这层决定 方案 API 层 lwe · bgv · ckks · cggi —— 选定加密方案与参数 出口 ①:库方言 lattigo · openfhe · tfhe_rust · jaxite 快速原型、易集成;难做跨操作融合 出口 ②:低层 IR polynomial · rns · mod_arith → llvm / scifr 适合长期、稳健的硬件集成 后端覆盖 CPU / GPU / FPGA / ASIC / 光子计算 —— 合作方包括 Belfort、Niobium、Cornami、Optalysys
图 3:HEIR 的分层编译结构。关键设计是「一个中间表示、多个出口」——同一份程序可以落到库 API,也可以落到硬件加速器。
HEIR's layers: each solves one class of problem Frontend PyTorch · TensorFlow · ONNX → torch-mlir / onnx-mlir / StableHLO Standard MLIR (entry level) func · linalg · tensor · arith · affine — canonicalisation and nonlinearity reduction happen here Secret arithmetic secret · tensor_ext · mgmt · polynomial · comb — layouts, kernels and noise are decided here Scheme APIs lwe · bgv · ckks · cggi — scheme and parameter selection Exit 1: library dialects lattigo · openfhe · tfhe_rust · jaxite Fast prototyping, easy integration; limits cross-op fusion Exit 2: low-level IRs polynomial · rns · mod_arith → llvm / scifr Suited to longer-term, robust hardware integration Backends span CPU / GPU / FPGA / ASIC / photonics — partners include Belfort, Niobium, Cornami, Optalysys
Fig. 3 — HEIR's layered compilation structure. The key design is "one IR, multiple exits": the same program can land on a library API or on a hardware accelerator.

编译时你需要配置什么

What you configure at compile time

官方文档列出的「编译配置」项恰好是一份很好的心智清单——它们就是 FHE 部署里真正要做的决策:

The "compilation configuration" list in the docs doubles as a good mental checklist — these are the decisions an FHE deployment actually involves:

module attributes {backend.openfhe, scheme.ckks} {
  func.func @mnist(%input: tensor<784> {secret.secret}) -> tensor<10> {
    %matrix1 = arith.constant dense<...> : tensor<512x784>
    %0 = linalg.matvec ins(%matrix1, %input) {kernel = "diagonal"}
    %1 = arith.addf %0, %bias1
    %2 = arith.maximumf %1, %cst {degree = 6, lower = -15.0, upper = 12}
    ...
  }
}
来源:HEIR「ML with HEIR」设计文档中的 MNIST 示例(节选)。degree = 6 就是 ReLU 的多项式逼近次数。
Source: the MNIST example (excerpt) in HEIR's "ML with HEIR" design page. degree = 6 is the polynomial approximation degree for ReLU.

布局优化:HEIR 最有技术含量的一层

Layout optimisation: HEIR's most technically distinctive layer

前面提到「数据在哪个槽位」是个优化问题。HEIR 的做法是把布局形式化为一个部分函数:从明文张量的索引集合,映射到一串密文槽位的索引集合,用 Presburger 关系和拟仿射公式表达。然后用整数集合库(ISL)做多面体分析,来计算 kernel 简化或批处理的槽位利用率。

Recall that "which slot holds which value" is an optimisation problem. HEIR formalises a layout as a partial function from the index set of a cleartext tensor to the index set of a list of ciphertext slots, expressed with Presburger relations and quasi-affine formulas. It then runs polyhedral analysis via the Integer Set Library to compute kernel simplifications and slot utilisation for batching.

优化流程分三步:Propagate(前向分析,给 IR 传播默认布局与 kernel)→ Optimize(用成本模型选最优 kernel,最小化布局转换)→ Simplify(反向遍历,把布局转换提升到编码阶段)。

The flow has three stages: Propagate (forward analysis seeds the IR with default layouts and kernels) → Optimize (cost models pick kernels that minimise cost and layout conversions) → Simplify (a backwards traversal hoists layout conversions into encodings).

和 Transformer 有关的一条One line that matters for transformers 文档提到 HEIR 已经集成了 bicyclic 与 tricyclic 布局,用于「以最优乘法深度计算并行多头自注意力的批量矩阵乘法」。也就是说:密文 Transformer 推理在 HEIR 里是正在推进的研究方向,而不是已经可用的生产能力。 The docs note that HEIR has integrated bicyclic and tricyclic layouts for "batched matrix multiplication for parallelized multi-head self-attention with optimal multiplicative depth." Read that as: encrypted transformer inference is an active research direction inside HEIR, not a shipping production capability.

5. 落地场景:Google 放出的四个 demo

5. Real applications: the four demos Google shipped

这四个例子都用 HEIR 编译,官方给出的延迟数据基于单线程 CPU

All four were compiled with HEIR; the official latency figures are for a single-threaded CPU.

场景解决什么问题合作方
深度学习推荐模型(DLRM)提供私密内容推荐——云服务能推荐,却看不到用户特征Belfort Labs、LG、纽约大学
信用卡欺诈检测在不暴露交易明文的前提下判断是否欺诈Niobium、hardshell.ai
入侵检测(Kitsune 系统)对加密网络流量做异常检测,服务方看不到数据包内容Niobium
唤醒词检测让音频触发的 AI Agent 识别唤醒词,同时保护录音隐私Belfort Labs
ApplicationWhat it solvesPartners
Deep Learning Recommendation Model (DLRM)Private content recommendations — the service recommends without seeing user featuresBelfort Labs, LG, New York University
Credit card fraud detectionJudge whether a transaction is fraudulent without exposing it in the clearNiobium, hardshell.ai
Threat intrusion (Kitsune)Anomaly detection over encrypted network traffic without revealing packet contentsNiobium
Hotword detectionLet an audio-triggered AI agent recognise hotwords while protecting the recordingsBelfort Labs

注意这四个的共同点:模型都不大,输出都很小——一个推荐分数、一个欺诈标签、一个异常判定、一个「是/否唤醒」。这不是巧合,而是 FHE 当前成本结构决定的选型逻辑:输入敏感、模型不深、输出是个标量或短向量的任务,是这条路线的甜点区。

Note what these four share: the models are small and the outputs are tiny — a recommendation score, a fraud flag, an anomaly verdict, a yes/no wake decision. That is not coincidence but the selection logic FHE's current cost structure imposes: tasks with sensitive inputs, shallow models, and a scalar or short-vector output are the sweet spot.

对 Agent 开发者的直接含义Direct implication for agent developers 四个 demo 里的唤醒词检测,官方措辞是「可以让一个音频触发的 AI Agent 识别唤醒词,同时保护音频录音的隐私」。这是一个具体信号:密文推理最先能进入 Agent 栈的位置,是常驻监听、隐私最敏感、但模型最小的那一环,而不是主推理链路。 Google frames the hotword demo as something that "could allow an audio-triggered AI agent to recognize hotwords while protecting the privacy of the audio recordings." That's a concrete signal: the first place encrypted inference enters an agent stack is the always-listening, most privacy-sensitive, smallest-model link — not the main reasoning path.

生态状况:它已经是一个研究平台

Ecosystem: it is already a research platform

官方博客提到:自 2023 年宣布意向以来,HEIR 已与开发 FHE 硬件加速器的公司合作,包括 Belfort、Niobium、Cornami、Optalysys;学术侧的合作包括佐治亚理工、卡内基梅隆、UC 圣塔芭芭拉、伊利诺伊理工、普渡、爱丁堡大学、清华大学等。截至发文,已有四篇同行评审论文基于 HEIR 完成,更多在准备中。

Google's post notes that since announcing its intentions in 2023, HEIR has partnered with FHE hardware-accelerator companies including Belfort, Niobium, Cornami and Optalysys, and with academic groups at Georgia Tech, Carnegie Mellon, UC Santa Barbara, Illinois Institute of Technology, Purdue, the University of Edinburgh and Tsinghua University. As of publication, four peer-reviewed publications were built on HEIR, with more in preparation.

6. 和谁比:FHE、TEE、MPC、ZK 各自的位置

6. How it compares: FHE vs. TEE vs. MPC vs. ZK

这一节的判断来自第三方分析文章,属于社区观点而非官方结论,请据此权衡。

This section reflects third-party analysis — community opinion rather than official conclusions. Weigh accordingly.

技术信任谁性能量级适合什么
FHE(本文主角)只信数学。安全性是纯密码学的,不依赖硬件厂商据分析文章,面临 10⁶× 量级的减速挑战;另有测算称即使精心设计电路,FHE 运算仍比明文慢 10³–10⁵ 倍硬件信任不可接受的场景;跨机构、强监管行业
TEE(可信执行环境)信芯片厂商(Intel / AMD / NVIDIA)据分析,开销在个位数百分比;NVIDIA 2023 年把 TEE 扩展到 GPU被称为大规模机密工作负载的「务实默认选项」
MPC(安全多方计算)信「参与方不合谋」主要瓶颈是通信开销多方各持一部分输入、要联合计算的场景
ZK(零知识证明)信数学据称已可用于生产选择性披露、可验证计算——注意它解决的是「证明」不是「保密计算」
TechnologyWho you trustPerformance orderBest for
FHE (this article)Only mathematics. Guarantees are purely cryptographic, not hardware-dependentAnalyses cite a ~10⁶× slowdown challenge; other estimates put carefully engineered FHE at 10³–10⁵× slower than cleartextCases where hardware trust is unacceptable; cross-institution, heavily regulated sectors
TEE (trusted execution environment)Chip vendors (Intel / AMD / NVIDIA)Reported single-digit-percent overhead; NVIDIA extended TEE to GPUs in 2023Described as the "pragmatic default" for large confidential workloads
MPC (secure multiparty computation)That the parties do not colludeMain bottleneck is communication overheadSeveral parties each hold part of the input and must compute jointly
ZK (zero-knowledge proofs)MathematicsReported production-readySelective disclosure and verifiable compute — note it solves proving, not confidential computation
为什么「纯密码学保证」不只是学术洁癖Why "purely cryptographic" is not just academic purity TEE 的安全性依赖硬件不被攻破。据报道,2025 年 10 月研究者公布了 TEE.failWireTap 两种物理攻击,用廉价电子元件在 CPU 与内存之间插入 interposer 就能提取加密密钥。⚠️ 此条来自第三方分析文章,建议查阅原始研究再下结论。但它说明了 FHE 与 TEE 的根本差异:FHE 的安全性不会因为攻击者能物理接触服务器而失效 A TEE's security depends on the hardware not being broken. Reportedly, in October 2025 researchers disclosed TEE.fail and WireTap, physical attacks that place a cheap interposer between CPU and memory to extract encryption keys. ⚠️ This comes from third-party analysis; consult the original research before drawing conclusions. Still, it illustrates the fundamental difference: FHE's guarantees do not collapse just because an attacker gains physical access to the server.

一篇分析文章给出的选型框架很实用,归结为四个问题:谁绝对不能看到这份数据?需要的是「验证」还是「计算」?被隐藏的工作负载有多大?有几方持有输入?把这四个问题回答清楚,技术选型基本就定了。

One analysis offers a practical selection framework built on four questions: who must not see the data; is the need verification or computation; how big is the hidden workload; and how many parties hold inputs? Answer those four and the technology choice largely falls out.

10³–10⁵×
精心设计电路后,FHE 相对明文计算的典型慢速倍数(据第三方测算)
2–10 秒
优化 CKKS + 批处理下,1 万条记录的加密逻辑回归推理耗时(据第三方基准)
>75%
Gartner 预测:到 2029 年,不可信基础设施上超此比例的操作将使用机密计算
10³–10⁵×
Typical FHE slowdown vs. cleartext even with carefully engineered circuits (third-party estimate)
2–10 s
Encrypted logistic-regression inference over 10,000 records with optimised CKKS and batching (third-party benchmark)
>75%
Gartner's forecast: share of operations on untrusted infrastructure using confidential computing by 2029

7. 坑与限制:上手前必须知道的

7. Pitfalls and limits: know these before you start

① 别指望跑 LLM1. Don't expect to run an LLM 这是最需要泼冷水的一条。研究文献明确指出:FHE 与 Transformer 架构相冲突;非线性函数在推理中「本质上就比线性函数计算昂贵、内存需求大」,需要用高次多项式逼近。密文 Transformer/LLM 推理目前仍集中在学术论文层面(如 ELLMo、Cachemir、Tricycle 等),不是可以直接部署的能力。 This is the one that most needs cold water. The literature is explicit: FHE clashes with transformer architectures, and nonlinear functions are "by nature computationally expensive and memory demanding compared to linear functions," requiring high-degree polynomial approximation. Encrypted transformer/LLM inference remains largely at the research-paper stage (ELLMo, Cachemir, Tricycle and others), not a deployable capability.
② 官方工具链尚未「一键化」2. The toolchain is not yet one-click HEIR 官方的愿景是「一键方案,让非专家把加密推理放进生产应用」——注意这是愿景。当下的现实是:端到端二进制仍在开发中,你需要手动串 heir-optheir-translate;OpenFHE 之外的后端支持仍在推进;nightly 二进制明确标注不用于生产。 HEIR's stated vision is "a one-click solution to enable non-experts to incorporate encrypted inference into production applications" — note that this is a vision. Today: the end-to-end binary is still being built, you wire heir-opt and heir-translate by hand, backends beyond OpenFHE are in progress, and the nightly binary is explicitly not for production.
③ CKKS 是「近似」计算3. CKKS is approximate arithmetic CKKS 方案的定位是「在近似实数上计算」。这意味着结果本身带有可控的数值误差——官方 dot-product 示例的 Go 测试就设了 errorThreshold = 0.0001 来做断言。做决策系统时,这个误差必须纳入设计,不能假设精确相等。 CKKS is defined as computing "on approximate real numbers." Results carry a controlled numerical error — HEIR's own Go test for the dot-product example asserts with errorThreshold = 0.0001. If you build a decision system on it, that error must be part of the design; do not assume exact equality.
④ 性能高度依赖「电路形状」4. Performance depends heavily on circuit shape 据第三方分析:FHE 在「工作负载被设计成最大化并行度、最小化电路深度」时表现最好;满足这些条件时,安全计算的开销才接近实际可用的企业 SLA。反过来说——把一个没为 FHE 设计过的模型直接丢进去,拿到的性能数字大概率毫无参考价值。 Per third-party analysis, FHE performs best when workloads are structured to maximise parallelism and minimise circuit depth; only under those conditions does the overhead approach practical enterprise SLAs. The corollary: throwing a model that was never designed for FHE at the compiler will produce performance numbers that tell you nothing useful.
⑤ 别忘了它保护的是「输入」,不是全部5. It protects the input, not everything 密文推理保护的是用户输入数据不被服务器看到。它本身不解决模型侧的问题——比如模型权重的保密(权重在服务端仍是明文)、结果被反推(通过多次查询推断模型或数据),以及元数据泄露(请求时间、频率、密文大小)。做威胁建模时要把这几项分开考虑。 Encrypted inference protects the user's input from the server. It does not by itself address model-side concerns — weight confidentiality (weights remain in the clear server-side), inference attacks that reconstruct the model or data through repeated queries, or metadata leakage (request timing, frequency, ciphertext size). Keep these separate in your threat model.

8. 术语表

8. Glossary

FHE(Fully Homomorphic Encryption)
全同态加密。支持在密文上做任意次加法和乘法组合的加密方案。
CKKS
一种 FHE 方案,在近似实数上计算,配合大量 SIMD 打包,是机器学习和统计场景的首选。HEIR 中对应 ckks 方言。
BGV
另一种 FHE 方案,面向整数运算。HEIR 的 Python 装饰器默认就用它。
CGGI
面向布尔电路 / 小整数的 FHE 方案家族,HEIR 中对应 cggi 方言,常见于 FPGA 加速器集成。
Bootstrapping
刷新密文、把累积噪声降回低水平的操作,是 FHE 中最昂贵的单个操作。
Slot / Packing
一个密文里可以装多个明文值,每个位置叫一个 slot;把数据摆进 slot 的过程叫 packing,能让一次运算同时处理一批数据。
Rotation(旋转)
把密文里各 slot 的值整体循环移位的操作,用来对齐不同 slot 上的数据。不便宜。
Relinearization
密文乘法会让密文「变大」(维度上升),relinearize 把它压回标准形态。
MLIR
LLVM 生态里的多层中间表示框架。HEIR 整个建立在 MLIR 上,「方言(dialect)」就是 MLIR 里定义一组操作的单位。
OpenFHE / Lattigo
两个主流开源 FHE 库,HEIR 可以把程序编译成调用它们的代码(分别是 C++ 和 Go)。
FHE (Fully Homomorphic Encryption)
An encryption scheme supporting arbitrary compositions of addition and multiplication on ciphertexts.
CKKS
An FHE scheme that computes on approximate real numbers with heavy SIMD packing — the scheme of choice for ML and statistics. HEIR exposes it as the ckks dialect.
BGV
Another FHE scheme, oriented to integer arithmetic. It is the default for HEIR's Python decorator.
CGGI
A family of FHE schemes for boolean circuits and small integers; HEIR's cggi dialect, common in FPGA accelerator integrations.
Bootstrapping
Refreshing a ciphertext to push accumulated noise back down — the single most expensive FHE operation.
Slot / packing
A ciphertext can hold many plaintext values; each position is a slot. Packing arranges data into slots so one operation processes a whole batch.
Rotation
Cyclically shifting the values across a ciphertext's slots, used to align data sitting in different slots. Not cheap.
Relinearization
Ciphertext multiplication inflates the ciphertext (its dimension grows); relinearization compresses it back to standard form.
MLIR
The multi-level intermediate representation framework in the LLVM ecosystem. HEIR is built entirely on MLIR; a "dialect" is MLIR's unit for defining a set of operations.
OpenFHE / Lattigo
Two mainstream open-source FHE libraries; HEIR can compile programs into code calling them (C++ and Go respectively).

9. 学习资源

9. Resources

来源清单

Sources

可信度说明:本文关于 HEIR 功能、用法、demo、合作方的所有陈述,均来自 Google 官方博客(2026-08-14)与 HEIR 官方文档。关于 FHE 性能倍数、FHE/TEE/MPC/ZK 对比、TEE 物理攻击、Gartner 预测的陈述,来自第三方分析文章,已在正文中标注为「据分析 / 据报道」,未经官方一手来源交叉确认,请以原始研究为准。关于 Transformer 下 FHE 困难的陈述来自学术论文摘要。
Confidence note: Every statement about HEIR's capabilities, usage, demos and partners comes from Google's official blog (2026-08-14) and HEIR's official documentation. Statements about FHE slowdown factors, the FHE/TEE/MPC/ZK comparison, TEE physical attacks and the Gartner forecast come from third-party analyses, are marked "reportedly / per analysis" in the text, and have not been cross-confirmed against primary sources — consult the original research. Claims about FHE's difficulty under transformers come from academic paper abstracts.
  1. Jeremy Kun,「How Google is Making Private AI Practical with Homomorphic Encryption」,Google Blog,2026-08-14 —— blog.google(官方一手)
  2. HEIR 官方站点首页(What is HEIR / Why HEIR / Project Goals)—— heir.dev(官方一手)
  3. HEIR 官方文档「Getting Started」,最后更新 2026-08-11 —— heir.dev/docs/getting_started(官方一手,本文所有命令与代码来源)
  4. HEIR 官方设计文档「ML with HEIR」,最后更新 2026-03-10 —— heir.dev/docs/design/ml_with_heir(官方一手)
  5. 「HEIR: A Universal Compiler for Homomorphic Encryption」,arXiv:2508.11095 —— arxiv.org
  6. google/heir 代码仓库 —— github.com/google/heir
  7. 「ZK vs FHE vs MPC vs TEE: How to Choose in 2026」,Wavect —— wavect.io(第三方分析)
  8. 「Is FHE Still Too Slow? Homomorphic Encryption Benchmarks 2026」,Duality —— dualitytech.com(第三方基准)
  9. 「Confidential computing decoded: TEEs vs FHE」,Optalysys —— optalysys.com(第三方,注意 Optalysys 是 HEIR 合作方,立场非中立)
  10. 「ELLMo: Packing- and Depth-Aware Encrypted Transformer Inference」,IACR ePrint 2026/198 —— eprint.iacr.org
  11. 「FHE-Agent: Automating CKKS Configuration for Practical Encrypted Inference via an LLM-Guided Agentic Framework」—— arxiv.org
  12. 「Google releases open-source tool to run AI on encrypted data」,Northeast Times,2026-08-15 —— northeasttimes.com(媒体报道)
  1. Jeremy Kun, "How Google is Making Private AI Practical with Homomorphic Encryption," Google Blog, 2026-08-14 — blog.google (primary, official)
  2. HEIR official homepage (What is HEIR / Why HEIR / Project Goals) — heir.dev (primary, official)
  3. HEIR docs, "Getting Started," last updated 2026-08-11 — heir.dev/docs/getting_started (primary; source of every command and code snippet here)
  4. HEIR design docs, "ML with HEIR," last updated 2026-03-10 — heir.dev/docs/design/ml_with_heir (primary, official)
  5. "HEIR: A Universal Compiler for Homomorphic Encryption," arXiv:2508.11095 — arxiv.org
  6. google/heir source repository — github.com/google/heir
  7. "ZK vs FHE vs MPC vs TEE: How to Choose in 2026," Wavect — wavect.io (third-party analysis)
  8. "Is FHE Still Too Slow? Homomorphic Encryption Benchmarks 2026," Duality — dualitytech.com (third-party benchmark)
  9. "Confidential computing decoded: TEEs vs FHE," Optalysys — optalysys.com (third-party; note Optalysys is a HEIR partner and not a neutral source)
  10. "ELLMo: Packing- and Depth-Aware Encrypted Transformer Inference," IACR ePrint 2026/198 — eprint.iacr.org
  11. "FHE-Agent: Automating CKKS Configuration for Practical Encrypted Inference via an LLM-Guided Agentic Framework" — arxiv.org
  12. "Google releases open-source tool to run AI on encrypted data," Northeast Times, 2026-08-15 — northeasttimes.com (press coverage)