← 论文海报合集← Paper Notes|
cs.RO · ICRA 2023

Code as Policies

Language Model Programs for Embodied Control
Jacky Liang, Wenlong Huang, Fei Xia, Peng Xu, Karol Hausman, Brian Ichter, Pete Florence, Andy Zeng  ·  Robotics at Google

将在代码上训练的大语言模型(LLM)重新用于机器人控制:给定自然语言指令,通过少样本提示(few-shot prompting)让 LLM 自动组合 API 调用,生成可在真实机器人上执行的 Python 策略代码。无需额外训练,即可完成空间推理、泛化新指令、根据上下文精确赋值等复杂任务。Repurposing large language models (LLMs) trained on code for robot control: given a natural-language instruction, few-shot prompting lets the LLM compose API calls on its own and produce Python policy code that runs on a real robot. With no additional training, it handles complex tasks such as spatial reasoning, generalizing to new instructions, and assigning precise values from context.

arXiv 2022 · ICRA 2023 cs.RO Robotics at Google 📄 arXiv:2209.07753 Project Page
code generation language model robot policy few-shot prompting embodied control hierarchical code generation 机器人操控robot manipulation 自然语言指令natural-language instruction Python policy LLM for robotics

01 动机Motivation

机器人需要理解自然语言指令并转化为具体行为。已有方法(如 SayCan、语义解析器)要么仅输出离散动作序列,要么需要大量标注数据训练,难以泛化到新指令。能否利用 LLM 直接生成结构化的机器人控制程序,从而利用代码的逻辑表达能力实现更强的空间推理与泛化?Robots need to understand natural-language instructions and turn them into concrete behavior. Existing approaches (e.g. SayCan, semantic parsers) either emit only discrete action sequences or require training on large amounts of annotated data, and generalize poorly to new instructions. Can an LLM directly generate structured robot control programs, so that the logical expressiveness of code yields stronger spatial reasoning and generalization?

"We find that language models trained on code-completion can be repurposed to write robot policy code, given natural language commands (formatted as comments) and few-shot examples of language instructions followed by corresponding code."
CaP teaser: natural language instruction converted to robot policy code
图1:Code as Policies(CaP)系统概览。用户输入自然语言指令(如"Stack the blocks on the empty bowl"),LLM 直接生成对应的 Python 策略代码,调用感知 API(如 detect_objects)和控制 API(如 pick_place)来完成任务。代码包含逻辑结构(循环、条件判断)和第三方库调用(NumPy、Shapely),可表达复杂的空间推理。Figure 1: Overview of the Code as Policies (CaP) system. The user gives a natural-language instruction (e.g. "Stack the blocks on the empty bowl") and the LLM directly generates the corresponding Python policy code, calling perception APIs (e.g. detect_objects) and control APIs (e.g. pick_place) to accomplish the task. The code contains logical structure (loops, conditionals) and third-party library calls (NumPy, Shapely), letting it express complex spatial reasoning.
4机器人平台(tabletop、whiteboard、mobile nav、mobile manipulation)robot platforms (tabletop, whiteboard, mobile nav, mobile manipulation)
37RoboCodeGen 评测任务数量tasks in the RoboCodeGen benchmark
39.8%层次化 code-gen 在 HumanEval 上的 pass@1 提升pass@1 gain from hierarchical code-gen on HumanEval
0额外训练样本(zero-shot 场景下)additional training examples (in the zero-shot setting)

现有方法的不足Shortcomings of existing approaches

CaP 的核心洞察是:LLM 在代码补全任务上的训练赋予了它理解和生成 Python 程序的能力,而代码天然具备表达复杂逻辑的能力——这正是自然语言所缺失的。The core insight of CaP is that training an LLM on code completion gives it the ability to understand and generate Python programs, while code natively expresses complex logic — exactly what natural language lacks.

02 方法Method

Code as Policies(CaP)是一种以 LLM 为核心的机器人控制框架。在 Hints 中告知可用 API,在 Examples 中提供少量语言-代码对示范,然后让 LLM 为新的自然语言指令生成对应的策略代码,并直接在机器人上执行。Code as Policies (CaP) is a robot control framework built around an LLM. Hints declare the available APIs, Examples supply a handful of language-code demonstration pairs, and the LLM then generates the corresponding policy code for a new natural-language instruction, which is executed directly on the robot.

CaP prompt structure and method overview
图2:CaP 的提示结构示意。一个 LMP(Language Model Program)提示由两部分组成:(1) Hints——告知 LLM 当前可用的 Python 库和 API 类型提示(type hints);(2) Examples——若干条"自然语言注释 + 对应代码"示例对,以 few-shot 方式引导 LLM 学习任务的代码风格。推理时,LLM 根据新指令生成新代码(高亮部分),代码可递归调用未定义函数,触发层次化 code-gen。Figure 2: The structure of a CaP prompt. An LMP (Language Model Program) prompt has two parts: (1) Hints — telling the LLM which Python libraries are available together with API type hints; (2) Examples — several "natural-language comment + corresponding code" demonstration pairs that guide the LLM few-shot toward the code style of the task. At inference time the LLM generates new code from a new instruction (highlighted), and that code may recursively call undefined functions, triggering hierarchical code-gen.

语言模型程序(Language Model Programs, LMP)Language Model Programs (LMPs)

每个 LMP 是一段由 LLM 生成的 Python 函数。LMP 的输入提示格式如下:Each LMP is a Python function generated by the LLM. The format of an LMP's input prompt is as follows:

# Place the first blue block to the left of the red block.
import numpy as np
target_pos = get_pos('red block')
place_pos  = target_pos + np.array([-0.1, 0, 0])
put_first_on_second('blue block', place_pos)

LMP 可以调用感知 API(如 detect_objects()get_pos())获取环境状态,调用控制 API(如 pick_place()put_first_on_second())执行动作。变量命名和代码结构遵循自然语言描述,使代码本身具有可读性。An LMP can call perception APIs (e.g. detect_objects(), get_pos()) to read the state of the environment, and control APIs (e.g. pick_place(), put_first_on_second()) to execute actions. Variable names and code structure follow the natural-language description, which makes the code itself readable.

层次化代码生成(Hierarchical Code Generation)Hierarchical Code Generation

当生成的代码引用了尚未定义的函数时,系统会递归地为该函数生成新的 LMP,直至所有函数均有实现。这一机制使 CaP 能处理更复杂的指令,同时保持每层提示的简洁性。When the generated code references a function that has not yet been defined, the system recursively generates a new LMP for that function until every function has an implementation. This mechanism lets CaP handle more complex instructions while keeping the prompt at each level concise.

"LMPs can be hierarchically prompted: the prompt for a high-level function e.g. parse_obj ... generates code that calls lower-level functions e.g. get_obj_bbox_area_xy, and automatically generates implementations of those lower-level functions."

层次化结构的优点:各层 LMP 专注于自身抽象层次,提示长度可控(在模型的 context window 内),同时组合产生高层行为能力。Advantages of the hierarchical structure: each LMP focuses on its own level of abstraction, prompt length stays bounded (within the model's context window), and composition yields high-level behavioral capability.

第三方库与空间推理Third-party libraries and spatial reasoning

CaP 允许代码导入并使用 NumPy(数值计算)、Shapely(几何计算)等标准 Python 库,从而无需专门训练即可完成精确的空间推理,例如"在四个对象的凸包内随机游走"等复杂几何任务。CaP lets the generated code import and use standard Python libraries such as NumPy (numerical computation) and Shapely (geometric computation), so it can perform precise spatial reasoning without dedicated training — for example complex geometric tasks such as "walk randomly inside the convex hull of the four objects".

支持的策略类型Supported policy types

CaP robot demonstrations across four domains
图3:CaP 在四类机器人平台上的演示。(a) 桌面操作(UR5e + D435 相机):码垛、颜色/形状分组、场景描述;(b) 白板绘画:绘制几何形状、变换(旋转、缩放);(c) 移动机器人导航:路径规划、凸包路径、绕障行走;(d) 移动机器人操作:对象分类、条件检索、场景问答。所有任务均由同一 few-shot 提示框架驱动,无需任何额外训练。Figure 3: CaP demonstrations on four classes of robot platform. (a) Tabletop manipulation (UR5e + D435 camera): stacking, grouping by color/shape, scene description; (b) whiteboard drawing: drawing geometric shapes and transformations (rotation, scaling); (c) mobile robot navigation: path planning, convex-hull paths, walking around obstacles; (d) mobile robot manipulation: object sorting, conditional retrieval, scene question answering. Every task is driven by the same few-shot prompting framework, with no additional training whatsoever.

03 实验Experiments

作者在三个维度上评估 CaP:(i) 新提出的 RoboCodeGen benchmark(代码生成质量);(ii) TabletopManipulation 仿真任务(与 CLIPort 等基线比较成功率);(iii) 真实机器人上的定性演示。同时分析层次化 code-gen 对代码质量的提升效果。The authors evaluate CaP along three axes: (i) the newly proposed RoboCodeGen benchmark (code generation quality); (ii) TabletopManipulation simulation tasks (success rate against baselines such as CLIPort); (iii) qualitative demonstrations on real robots. They also analyze how much hierarchical code-gen improves code quality.

RoboCodeGen 基准(代码生成)The RoboCodeGen benchmark (code generation)

作者提出 RoboCodeGen——一个包含 37 道机器人代码生成题目的评测集(对标 HumanEval 风格),涵盖 table-top manipulation 典型任务。指标为 pass@N(N 次采样中至少一次通过单元测试的比例)。The authors introduce RoboCodeGen, a benchmark of 37 robot code-generation problems (in the style of HumanEval) covering typical table-top manipulation tasks. The metric is pass@N (the fraction of problems for which at least one of N samples passes the unit tests).

RoboCodeGen and TabletopManipulation results tables
表I(左上):RoboCodeGen 上的代码生成 pass 率(%),GPT-{112} 与 Codex-{11} 在 flat 与 hierarchical 两种 code-gen 策略下的对比。层次化策略始终优于 flat。表II(右上):TabletopManipulation 仿真任务成功率(%),CaP 与 CLIPort 基线在 Seen/Unseen 属性及 task family 上的比较。Table I (top left): code-generation pass rates (%) on RoboCodeGen, comparing GPT-{112} and Codex-{11} under the flat and hierarchical code-gen strategies. The hierarchical strategy is consistently better than flat. Table II (top right): success rates (%) on the TabletopManipulation simulation tasks, comparing CaP with the CLIPort baseline on Seen/Unseen attributes and across task families.
模型ModelCode-gen 策略Code-gen strategypass@6pass@11
GPT-{112}Flat8490
GPT-{112}Hierarchical8495
Codex-{11}Flat8084
Codex-{11}Hierarchical8487

Table I 节选(来自论文原文):层次化代码生成在 pass@6 和 pass@11 指标上均优于或持平于 flat 策略,表明递归函数定义有效提升了代码质量。Excerpt from Table I (verbatim from the paper): hierarchical code generation matches or beats the flat strategy on both pass@6 and pass@11, indicating that recursive function definition effectively improves code quality.

TabletopManipulation 仿真任务TabletopManipulation simulation tasks

方法MethodSeen 属性 (%)Seen attributes (%)Unseen 属性 (%)Unseen attributes (%)P@10 (%)
CLIPort [36]53.0N/AN/A
VILD [1]0.00N/AN/A
CaP (flat)53.039.390.9
CaP (hierarchical)53.039.495

Table II 节选(来自论文原文):CaP 在 Seen 属性上与 CLIPort 持平(53.0%),但 CLIPort 无法泛化到 Unseen 属性(需要重新训练),而 CaP 无需额外训练即可处理新属性(39.3%/39.4%)。Excerpt from Table II (verbatim from the paper): CaP matches CLIPort on Seen attributes (53.0%), but CLIPort cannot generalize to Unseen attributes (it would need retraining), whereas CaP handles new attributes with no additional training (39.3%/39.4%).

成功率对比(Table III)Success rate comparison (Table III)

Task FamilyCLIPort [36]P@10P@100
Long-Horizon97.2877.93N/A
Spatial-Geometric0.00N/A75.33
Long-Horizon (UA)3.58N/AN/A
Spatial-Geometric (UA)0.00N/A75.93

Table III 节选:CLIPort 在 Spatial-Geometric 任务上得 0 分(无法处理空间推理),而 CaP 通过 NumPy/Shapely 代码达到 75.33%(P@100)。Long-Horizon 任务上 CLIPort 领先(97.28% vs 77.93%),说明对于已见简单序列任务,专门训练的模型更有优势。Excerpt from Table III: CLIPort scores 0 on the Spatial-Geometric tasks (it cannot handle spatial reasoning), while CaP reaches 75.33% (P@100) through NumPy/Shapely code. On Long-Horizon tasks CLIPort leads (97.28% vs 77.93%), showing that a specially trained model retains an edge on seen, simple sequential tasks.

消融实验(HumanEval)Ablation study (HumanEval)

作者在 HumanEval benchmark 上分析了层次化代码生成的效果:将未定义函数递归分解后,pass@1 从基线提升至 39.8%,优于同规模的 flat 策略。这一结果直接支持了层次化 code-gen 的有效性假设。The authors analyze the effect of hierarchical code generation on the HumanEval benchmark: after recursively decomposing undefined functions, pass@1 rises from the baseline to 39.8%, beating the flat strategy at the same scale. This result directly supports the hypothesis that hierarchical code-gen is effective.

"Hierarchical code generation, which incrementally generates new instructions and responses to the prompt, allows later instructions to refer back to previous instructions, like 'undo the last action'."

04 局限性Limitations

注:以下局限性来自论文 Discussion and Limitations 小节(第 VI 节)的明确表述(标注为 stated),以及从系统设计可推断的约束(标注为 inferred)。Note: The limitations below are drawn from the explicit statements in the paper's Discussion and Limitations section (Section VI), marked stated, together with constraints that can be inferred from the system design, marked inferred.
感知 API 的局限性制约了整体能力(stated)The limits of the perception APIs cap overall capability (stated)

CaP 的上限受制于所提供的感知与控制 API 质量。论文指出:"the scope of actions a robot can perform is bounded by its available APIs and skills." 如果底层检测器无法识别某类物体,或控制 API 不支持某种操作,CaP 无法弥补这一差距。CaP's ceiling is set by the quality of the perception and control APIs it is given. The paper notes: "the scope of actions a robot can perform is bounded by its available APIs and skills." If the underlying detector cannot recognize a class of objects, or the control API does not support some operation, CaP cannot close that gap.

仅评估语言-策略接口,不解决感知和运动规划难题(stated)Only the language-to-policy interface is evaluated; perception and motion planning remain unsolved (stated)

"This work focuses on the language-to-policy interface and does not directly address the challenges of perception and motion planning." CaP 假设可靠的感知 API(如 open-vocabulary 目标检测 VILD [1])和低层控制器已就绪,而这些本身就是活跃的研究领域。"This work focuses on the language-to-policy interface and does not directly address the challenges of perception and motion planning." CaP assumes that reliable perception APIs (such as the open-vocabulary object detector VILD [1]) and low-level controllers are already in place, yet each of those is itself an active research area.

无法处理显著超出 few-shot 示例复杂度的指令(stated)Cannot handle instructions far beyond the complexity of the few-shot examples (stated)

论文在 Discussion 中指出,当指令的复杂度远超 Examples 中的示例时(例如需要构建完整的 3D 场景),CaP 难以生成正确代码。"it would be difficult for LMPs to 'build a house with the blocks,' since there are no Examples on building complex 3D structures."The paper notes in the Discussion that when an instruction is far more complex than the demonstrations in Examples (for instance requiring a complete 3D scene to be built), CaP struggles to generate correct code. "it would be difficult for LMPs to 'build a house with the blocks,' since there are no Examples on building complex 3D structures."

代码执行前无法预判响应是否可行(inferred)No way to judge in advance whether the response is feasible before the code runs (inferred)

生成的代码在执行前无安全验证机制——若 LLM 生成了错误的 API 调用序列或数值(如超出机器人工作空间的位置),只有在执行时才能发现错误。这对真实机器人部署是一个安全隐患。There is no safety verification of the generated code before execution: if the LLM produces a wrong sequence of API calls or wrong values (such as a position outside the robot workspace), the error can only be discovered at execution time. That is a safety hazard for deployment on real robots.

依赖大型闭源 LLM,推理成本高(inferred)Depends on a large closed-source LLM, with high inference cost (inferred)

论文实验主要使用 GPT-3 Codex(当时为 OpenAI API 付费服务),每次指令执行都需要调用大型模型进行 code-gen。在时延和成本上对实时机器人控制存在挑战,尤其是层次化递归生成时需要多次 API 调用。The experiments mainly use GPT-3 Codex (at the time a paid OpenAI API service), and every instruction execution requires a call to a large model for code-gen. This poses latency and cost challenges for real-time robot control, especially because hierarchical recursive generation needs multiple API calls.