选择数值后端
FlyRuler 的编译流程将声明期的模型结构(ModelDeclaration)降层为特定数值后端的可执行函数,并通过统一的缓存与产物机制管理编译结果。
准备、编译与绑定
compiler.prepare:执行结构校验、积分器解析与资源数学准备,生成后端无关的ModelProgram。准备一次后,可反复编译到不同目标,无需重新声明。compiler.compile:根据target将模型降层为目标代码(TargetProgram),省略target时默认使用 CasADi。runtime.bind:绑定目标运行环境,返回可调用的RuntimeInstance。
python
from pathlib import Path
from fly_ruler_core import (
CompileOptions,
ModelSettings,
OperationContext,
compiler,
runtime,
targets,
)
context = OperationContext(store=Path("build/flyruler"), cache="reuse")
program = compiler.prepare(
System.build("Root"),
settings=ModelSettings(integrator="euler", dt=0.1),
context=context,
)
target = compiler.compile(
program,
target=targets.numpy,
options=CompileOptions(prune_unused=True),
context=context,
)
model = runtime.bind(target)| 设置类 | 常用字段与默认值 | 职责 |
|---|---|---|
ModelSettings | integrator="euler"、dt=0.01、so3_integrator="rkmk" | 数值积分与步长语义,随 ModelProgram 持久化 |
CompileOptions | prune_unused=True、casadi=CasadiOptions() | 代码生成策略与依赖裁切(详见设置编译选项) |
OperationContext | store=None、cache="reuse"、verbosity="quiet"、color=True | 本次编译的存储路径、缓存策略与日志详细度 |
三个后端
| 编译目标 | 返回模型类型 | 运行期数组类型 | 适用场景与安装要求 |
|---|---|---|---|
targets.numpy | RuntimeInstance | numpy.ndarray | 快速原型验证、轻量仿真(随 fly-ruler 自带) |
targets.casadi | CasadiModel | CasADi DM | 符号自动微分、配平与线性化、C++/PX4 导出(随 fly-ruler 自带) |
targets.jax | RuntimeInstance | JAX 设备数组 | JIT 加速、GPU 批量仿真(需 uv add "fly-ruler[jax]") |
不同后端返回的原生数组可用 model.to_numpy(value) 统一转换为宿主 NumPy 数组进行跨后端比对。
JAX 的进程级精度配置
JAX 默认使用 float32,且在首次导入 jax 时就会锁定设备与精度策略。需要 float64 精度时,请在首次导入 jax 之前显式调用:
python
from fly_ruler_core.runtime.jax_config import JaxRuntimePolicy, configure_jax_runtime
configure_jax_runtime(
JaxRuntimePolicy(platforms=("cpu",), preallocate=False, enable_x64=True)
)| 字段 | 对应环境变量 | 说明 |
|---|---|---|
platforms | JAX_PLATFORMS | 如 ("cpu",) |
preallocate / memory_fraction | XLA_PYTHON_CLIENT_PREALLOCATE / MEM_FRACTION | 显存预分配与比例 (0, 1] |
allocator | XLA_PYTHON_CLIENT_ALLOCATOR | 自定义分配器(与前两项互斥) |
enable_x64 | JAX_ENABLE_X64 | 显式启用双精度 float64 |
缓存策略与产物
当 OperationContext 指定了持久目录 store 时,cache 控制缓存行为:
cache 取值 | 行为 |
|---|---|
"reuse" | 内容身份(IR、数值设置、资源、目标选项)一致时直接复用,否则重新生成 |
"refresh" | 忽略已有缓存,强制重新编译 |
"readonly" | 仅允许命中已有缓存,缺失时直接报错 |
要将模型保存为独立可分发的产物目录,调用 artifacts.save(program_or_target, output_dir=...);接收方无需原声明脚本即可用 artifacts.open(path).describe() 查看摘要,或用 runtime.bind(path) 直接恢复运行实例。