AI Wiki中文/EN

程序合成:规格与反例

Program synthesis

枚举小型程序语法,用有限域验证器细化有歧义的例子。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

要解决的问题

两个输入输出例子规定:0变成1,1变成2。“加一”程序符合要求,“先平方再加一”也符合。例子表达了一部分意图,却不一定确定唯一程序。

程序合成在规定的语言中,搜索满足规格的程序。规格可以是逻辑性质、参照实现或例子。合成系统既需要搜索空间,也需要判断候选是否足够好的方式;两者是独立的设计选择。Program Synthesis

定义与保证

设H\mathcal H为有界程序集合,DD为声明的输入域,ff为参照行为。本例目标为:

∃p∈H  ∀x∈D: p(x)=f(x).\exists p\in\mathcal H\;\forall x\in D:\ p(x)=f(x).

学习器最初只看到样本E⊆DE\subseteq D。反例引导的归纳合成,交替执行两步:寻找与EE一致的候选,再按完整规格检查。失败输入被加入EE,然后重新搜索。SKETCH论文为有限程序提出合成—验证循环,合成综述进一步解释oracle引导的总体模式。Combinatorial Sketching for Finite Programs Program Synthesis

本例语法包含变量、常数零和一、加法与乘法:

p::=x∣0∣1∣(p+p)∣(p×p).p ::= x\mid0\mid1\mid(p+p)\mid(p\times p).

抽象语法树把每个变量、常数和运算符计为一个节点。程序按大小顺序,枚举节点上界内的全部树。它不执行生成的Python文本,只计算这些受控树构造器。

验证器检查有限域中的每个输入。每个反例都是新输入,因为候选已经符合积累的样本。在语法有限、验证器精确时,循环要么找到正确候选,要么确立声明输入域内、此语法中没有解。最多加入∣D∣|D|个新的失败输入;超时或不完整验证器则需要不同的结果状态。

最小实现

参照程序把整数平方后加一。搜索最初只得到两个例子,验证器则拥有全部五个声明输入。为了清楚展示这种分工,程序缓存了有限参照表。这是教学例子,不表示如此小的任务本身需要复杂合成器。

def expressions(max_nodes):
    if type(max_nodes) is not int or not 1 <= max_nodes <= 7:
        raise ValueError("teaching bound: 1..7 AST nodes")
    by_size = {1: [("x",), ("const", 0), ("const", 1)]}
    for size in range(2, max_nodes + 1):
        by_size[size] = []
        for op in ("+", "*"):
            for left_size in range(1, size - 1):
                right_size = size - 1 - left_size
                for left in by_size.get(left_size, []):
                    for right in by_size.get(right_size, []):
                        by_size[size].append((op, left, right))
    return [e for size in range(1, max_nodes + 1) for e in by_size[size]]

def run(expr, x):
    if expr[0] == "x":
        return x
    if expr[0] == "const":
        return expr[1]
    left, right = run(expr[1], x), run(expr[2], x)
    return left + right if expr[0] == "+" else left * right

def show(expr):
    if expr[0] == "x":
        return "x"
    if expr[0] == "const":
        return str(expr[1])
    return "(" + show(expr[1]) + " " + expr[0] + " " + show(expr[2]) + ")"

def first_counterexample(expr, reference, domain):
    # Verification sees the whole declared finite domain.
    for x in domain:
        if run(expr, x) != reference[x]:
            return x
    return None

def synthesise(target, domain, examples, max_nodes=5):
    domain = tuple(domain)
    if not 1 <= len(domain) <= 16 or any(type(x) is not int for x in domain):
        raise ValueError("domain must contain 1..16 integers")
    if len(set(domain)) != len(domain):
        raise ValueError("domain values must be distinct")
    reference = {x: target(x) for x in domain}
    if any(type(y) is not int for y in reference.values()):
        raise ValueError("reference outputs must be integers")
    examples = tuple(examples)
    samples = dict(examples)
    for x, y in examples:
        if type(x) is not int or type(y) is not int or x not in reference or y != reference[x]:
            raise ValueError("examples must agree with the reference on the domain")
    candidates = expressions(max_nodes)
    trace = []
    while True:
        # Search sees only the samples accumulated so far.
        candidate = next((e for e in candidates
                          if all(run(e, x) == y for x, y in samples.items())), None)
        if candidate is None:
            return None, trace
        counterexample = first_counterexample(candidate, reference, domain)
        trace.append((show(candidate), counterexample))
        if counterexample is None:
            return candidate, trace
        samples[counterexample] = reference[counterexample]

if __name__ == "__main__":
    domain = (-2, -1, 0, 1, 2)
    expression, trace = synthesise(lambda x: x*x + 1, domain, [(0, 1), (1, 2)])
    for candidate, counterexample in trace:
        print(candidate, "counterexample:", counterexample)
    print("verified on:", len(domain), "inputs")
    print("three-node bound:", synthesise(lambda x: x*x + 1, domain, [(0, 1)], 3)[0])
(x + 1) counterexample: -2
(1 + (x * x)) counterexample: None
verified on: 5 inputs
three-node bound: None

第一个候选在−2处失败:加一得到−1,参照却得到5。随后,一个五节点表达式通过整个五输入域。在三节点语法中,没有表达式满足同样规格;失败针对语法上界,不表示无法写出所需函数。

这个语法有3棵单节点树、18棵三节点树、216棵五节点树。若保留KK个至多NN节点的候选,输入域有dd个值,直接重复搜索的时间上界可写成O(KNd2)O(KNd^2),存储的保守上界为O(KN+d)O(KN+d)。小规模上界很重要,因为候选数增长很快。

求值器run用于expressions生成的树,不用于任意不可信AST。参照必须确定,初始例子必须与它一致。真实工具应报告:它检查了有限域、求解了符号条件,还是仅运行了一些测试。

局限与替代

有限验证不会自动证明所有整数上的正确性,更不会覆盖带异常、状态或并发的语言全部行为。对于返回的算术表达式,可以另用代数论证得到更强结论,但这不是有限验证器已经认证的内容。

不同语法能够表达不同解。限制语法有助于搜索,却可能排除预期程序;扩展语法则增加候选和歧义。最短的一致程序,是空间内的一种偏好,不保证符合用户真正想要的行为。

现代合成以不同方式组合枚举、约束、概率引导和学习式提议。生成的候选仍可以接受独立检查。提议机制的质量与验证器的保证强度,需要分别评估。

练习与答案

1. 为什么最初两个例子不能确定预期程序?

x+1和x*x+1在0与1处相同。

2. 反例−2揭示什么?

x+1得到−1,x*x+1得到5。

3. 1+(x*x)有多少节点?

五个:两个运算符与三个叶节点。

4. 三节点上界下失败,证明没有程序能解决任务吗?

不能。五节点程序能满足声明的规格。

研究与下一步

阅读合成综述的规格与oracle引导章节,再看原始有限程序SKETCH循环。关键契约是验证器量化了哪些输入,以及搜索能够表达哪些程序。

继续读自动定理证明、归纳逻辑编程与SAT求解。

先判断,再看解释

三节点失败确立什么?

选择一个答案

学习目标

  • 区分语法、观察例子与完整规格。
  • 解释有限域验证与相对于语法的失败。

先修与延伸

查看知识关联图 →

参考文献

  1. Program Synthesis
    Sumit Gulwani; Oleksandr Polozov; Rishabh Singh · 2017
  2. Combinatorial Sketching for Finite Programs
    Armando Solar-Lezama; Liviu Tancau; Rastislav Bodik; Vijay Saraswat; Sanjit Seshia · 2006

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit finite models, executed programs, independent mathematical/exhaustive references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.

  • 单个AI作者进行技术检查:可运行示例、精确或字面参照、明确假设及对应的双语公式与习题。实际执行和渲染结果另行记录。
  • 8项测试:语法数量3/18/216、0/1处歧义、反例−2、有限域外推失败、更紧语法无解与非法迭代器例子。校验前固定例子集合,避免迭代器耗尽绕过检查。
  • 逐项对照双语论点、定义、假设、公式、代码、结果及四组练习。均为原创有限教学程序,不声称复现已发表系统或研究基准。冻结前修正目录ID。
  • 完整双语正文与对应习题迁入,正式文章状态及SHA绑定。算法篇测试读取正式MDX;历史篇不虚列可执行程序或计算测试。
  • 出版导航将已发表主题指向完整文章并移除对应待写措辞,未发表目标保留目录入口;原理、公式、程序与习题未改,重新绑定最终正文SHA。

核对的来源位置:

  • Program Synthesis · Physical13–15/17 specification and challenge passages;49–52 oracle-guided/CEGIS loop and verifier assumptions.
  • Combinatorial Sketching for Finite Programs · Author MIT copy; abstract and physical2/7/9 counterexample synthesize-verify passages, finite program scope; no tool benchmark reproduction.

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。