Skip to content

设置编译选项 ​

compiler.prepare 与 compiler.compile 之间有一套细粒度的选项与自省机制,用于控制 CasADi Block 符号表示、缓存复用与编译报告、产物保存与恢复,以及未使用表达式的依赖裁切。

对应示例:packages/fly_ruler/examples/core/compile.py、packages/fly_ruler/examples/core/casadi_blocks.py。基础的三大后端选择与缓存策略见选择数值后端。

准备、编译与恢复示例 ​

py
# 数值设置属于模型;裁切属于生成;目录与日志只属于本次操作。
settings = fr.ModelSettings(dt=0.02, integrator="rk4", so3_integrator="rkmk")
options = fr.CompileOptions(prune_unused=True)
context = fr.OperationContext(
    store=output / "cache", verbosity="detailed", color=False
)
program = fr.compiler.prepare(
    FirstOrderSystem.build("Root"), settings=settings, context=context
)
py
# 三个内置目标各编译一份;JAX 目标的数组类型是 JaxArray,与 NumPy 不同。
numpy_target_program = fr.compiler.compile(
    program, target=fr.targets.numpy, options=options, context=context
)
numpy_model: fr.runtime.RuntimeInstance[fr.runtime.NumpyArray] = fr.runtime.bind(
    numpy_target_program
)
casadi_target_program = fr.compiler.compile(
    program, target=fr.targets.casadi, options=options, context=context
)
casadi_model = fr.runtime.bind(casadi_target_program)
jax_target_program = fr.compiler.compile(
    program, target=fr.targets.jax, options=options, context=context
)
jax_model: fr.runtime.RuntimeInstance[fr.runtime.JaxArray] = fr.runtime.bind(
    jax_target_program
)
  • ModelProgram(由 compiler.prepare 返回)已固定数值设置 ModelSettings 与准备好的资源(例如三次样条系数),保存后可在其他进程中通过 artifacts.read_program(path) 恢复并直接编译到新目标。
  • 自定义后端可通过 targets.PythonTarget(backend) 传入 compiler.compile。

CasADi 的 Block 表示 ​

默认情况下,CasadiOptions(block_mode="auto") 会为每个 Block 自动选择合适的 CasADi 符号表示:大型矩阵乘法、插值表、稀疏乘积与嵌套导数使用 MX,标量运算量不超过预算(1024)的小型块使用 SX。

需要针对特定块显式指定时,可通过 overrides 传入完整、大小写敏感的 Block 实例路径("mx" 或 "sx"):

py
# auto 是默认值:保留矩阵/资源结构,只把预算内的纯计算编成 SX。
default_policy = CasadiOptions()
overridden = CasadiOptions(overrides={"Root.matrix": "sx"})
for config in (default_policy, overridden):
    settings = fr.ModelSettings()
    options = fr.CompileOptions(casadi=config)
    context = fr.OperationContext(store=output / "cache")
    program = fr.compiler.prepare(source, settings=settings, context=context)
    target_program = fr.compiler.compile(
        program, target=fr.targets.casadi, options=options, context=context
    )
    model = fr.runtime.bind(target_program)
    for decision in target_program.description.block_decisions:
        print(decision)
    models.append(model)

内部表示与外部符号视图相互独立

CasadiOptions 仅控制生成的 CasADi 计算图内部各块的表示,调用方仍可自由使用 model.sx 与 model.mx 视图,变量视图的 build/read/default 用法保持不变。可通过 model.target_program.description.block_decisions 查看每个块的实际决策与开销估计。

编译报告与产物恢复 ​

每次调用 compiler.compile(...) 都会在 model.compilation_report 中记录分阶段事件(events)与总耗时(total_seconds),其中命中缓存的阶段状态为 cache_hit:

py
# 重复编译同一目标;第二次应从缓存恢复,事件里出现 cache_hit。
first_report = casadi_model.compilation_report
cached_target_program = fr.compiler.compile(
    program, target=fr.targets.casadi, options=options, context=context
)
cached_model = fr.runtime.bind(cached_target_program)
cached_report = cached_model.compilation_report
# 进度报告可能为空,缺失时跳过缓存统计而不是静默假定命中。
if first_report is not None and cached_report is not None:
    cache_events = tuple(
        event for event in cached_report.events if event.status == "cache_hit"
    )
    print(f"重复编译的缓存命中事件:{len(cache_events)}")

将模型程序或目标产物保存到磁盘,以便后续进程直接加载或部署:

py
# save 保存目标及模型依赖闭包;open 只读描述;runtime.bind 只绑定已有目标。
saved_path = output / "casadi-artifact"
artifact = fr.artifacts.save(casadi_model.target_program, output_dir=saved_path)
reader = fr.artifacts.open(artifact)
info = reader.describe()
assert info.target.target == "python"
restored = fr.runtime.bind(saved_path)
assert isinstance(restored, fr.runtime.CasadiModel)
# 恢复后的模型用同一组初值再走一步,y 应与原模型完全一致。
restored_result = restored.discrete_fn(
    0.0,
    restored.x.build({"Root.plant::state": [1.0]}),
    restored.xd.build(),
    restored.u.build({"Root::command": [0.5]}),
    restored.p.default(),
)
print(
    f"保存并恢复:{artifact}; kind={reader.kind}; "
    f"target={info.target.target}/{info.target.backend}; "
    f"dt={info.settings.dt} s; y={restored_result.y}"
)
  • 只读查看元数据:info = artifacts.open(path).describe() 可直接读取 info.settings.dt、info.initial_values["x"] 及各变量路径与单位,无需绑定运行环境。
  • 直接绑定运行:runtime.bind(path) 按产物内记录的目标直接绑定执行(从路径绑定时 compilation_report 为 None)。
  • 检查目标入口:target = artifacts.read_target(path) 可在执行前查看 target.description.entries["discrete"] 与 operator_requirements。
进阶:CasADi 与 Python 目标的恢复前提

CasADi 与完全降层的 native 目标保存共享计算图或二进制,恢复时无需重新注册历史算子提供者;NumPy 与 JAX 目标恢复生成模块时,需先按 requirements.runtime.operators 注册对应的运行期算子提供者。若从已保存的 CasADi 目标继续导出 C++/PX4,详见保存与导出产物。

部署时关闭所有诊断出口 ​

调试时可以用 fr.effect 记录中间值。部署时如果只需要正式输出和状态更新,在构建同一个顶层系统时关闭诊断即可,不用给每个块加条件分支:

python
import fly_ruler_core as fr

with fr.build_options(fr.BuildOptions(include_effects=False)):
    declaration = Aircraft.build("Root")

program = fr.compiler.prepare(declaration, settings=fr.ModelSettings(dt=0.01))

默认的 include_effects=True 保留所有诊断。设为 False 对整棵模型树生效;continuous_fn、discrete_fn 仍返回相同结构,但 effects 向量长度为零。保存后再恢复也不会出现这些路径;需要记录诊断时,用原声明重新构建开启版。

例如,控制器返回有界命令 u,另外用一次无约束线性求解和一次分配误差计算生成两项诊断。关闭诊断后,不会为了这两个结果在每拍求解或计算误差;有界命令本身需要的增益矩阵和输入残差仍会计算。Python 在声明时仍会执行构造表达式的代码。保持默认的 prune_unused=True,还能裁掉失去最后一个消费者的上游块输出;公开输出、状态更新和约束仍是保留计算的依据。

依赖裁切与优化报告 ​

CompileOptions.prune_unused(默认 True)会在代码生成前按 continuous、dynamics、transition、constraint 与 observation 等执行入口的可达闭包,移除未参与任何输出、状态更新或约束的死分支表达式根。

依赖裁切保持所有状态、端口路径、向量槽位与数值结果完全一致,只减少生成代码中的冗余计算。关闭或开启裁切后的差异可通过 model.optimization 对比:

py
# 同一份 IR 关掉依赖裁切再编一次,对照优化报告与生成源码的差别。
unpruned_options = fr.CompileOptions(prune_unused=False)
unpruned_context = fr.OperationContext(
    store=output / "cache-unpruned", cache="refresh", color=False
)
unpruned_target_program = fr.compiler.compile(
    program,
    target=fr.targets.casadi,
    options=unpruned_options,
    context=unpruned_context,
)
unpruned_model = fr.runtime.bind(unpruned_target_program)
pruned_report = casadi_model.optimization
unpruned_report = unpruned_model.optimization
print(
    f"裁切开关:enabled={pruned_report.enabled} -> {unpruned_report.enabled}; "
    f"removed_roots={len(pruned_report.removed_roots)} -> "
    f"{len(unpruned_report.removed_roots)}"
)
# 两个报告的入口顺序相同,可以逐项对照裁剪前后的表达式根数量。
for pruned_entry, unpruned_entry in zip(
    pruned_report.entries, unpruned_report.entries, strict=True
):
    print(
        f"入口 {pruned_entry.entry}: 保留根 {pruned_entry.retained}/"
        f"{pruned_entry.total} -> {unpruned_entry.retained}/{unpruned_entry.total}"
    )
for root in pruned_report.removed_roots:
    print(f"移除的根 {root.path} ({root.kind}):未被任何执行入口保留")
# 裁切减少实际计算;函数封装和策略报告也占源码空间,字节数不作为根数的代理。
pruned_source = casadi_model.artifact.file(ArtifactFile.BACKEND_SOURCE).read_text(
    encoding="utf-8"
)
unpruned_source = unpruned_model.artifact.file(
    ArtifactFile.BACKEND_SOURCE
).read_text(encoding="utf-8")
print(f"生成源码长度:pruned={len(pruned_source)},unpruned={len(unpruned_source)}")
assert pruned_report.removed_roots
assert sum(e.retained for e in pruned_report.entries) < sum(
    e.retained for e in unpruned_report.entries
)
# observe 始终只保留输出闭包;关闭可选裁切不扩大它的纯观测契约。
assert all(
    e.retained == e.total for e in unpruned_report.entries if e.entry != "observe"
)
OptimizationReport 的阅读要点
  • entries 按执行入口列出 strategy、total、retained 与 roots;removed_roots 列出全局被裁掉的表达式根。
  • 计数单位为表达式根(而非后端指令数)。启用裁切且移除了死分支时,新编译会发出一条 RuntimeWarning;缓存命中时不重复提示。
  • 被裁掉的死分支即使包含当前后端不支持的算子也不会报错,只有存活分支才会触发 BackendCapabilityError。

常见报错排查 ​

现象排查方向
cache="readonly" 下报错缺失该策略仅允许命中现有缓存;首次编译或修改后请改用 "reuse" 或 "refresh"
修改声明后编译结果未更新默认 "reuse" 按声明 IR 与选项内容作缓存键,确认改动已进入 System.build(),或临时使用 "refresh"
收到 FlyRuler pruned ... 警告模型中存在未连接到输出或状态的表达式根,可查看 model.optimization 核对具体被裁切的路径
compilation_report 为 None从已保存路径 runtime.bind(path) 恢复时无编译过程;块级表示决策可从 target_program.description.block_decisions 读取
产物目录体积持续增长开发期可传 OperationContext(store=None) 使用临时工作区,或定期清理 store 目录

下一步 ​