Skip to content

控制编译开销 ​

当模型包含大量循环展开或复杂表达式时,声明阶段可能在进入 compiler.prepare() 之前就消耗大量内存。FlyRuler 按共享表达式 DAG(而非展开树)计量规模,并提供声明预算(BuildOptions)与编译阶段报告来提前拦截异常膨胀并定位耗时。

对应示例:packages/fly_ruler/examples/core/compilation_resources.py。

设置声明预算 ​

无需修改块或系统内部代码,只需在调用 System.build() 时包裹 build_options 上下文:

python
from fly_ruler_core import BuildOptions, ModelSettings, build_options, compiler, runtime, targets

with build_options(BuildOptions(max_expression_nodes=200_000)):
    source = Aircraft.build("Root", cfg)

program = compiler.prepare(source, settings=ModelSettings())
model = runtime.bind(compiler.compile(program, target=targets.numpy))

当声明规模超出预算时,系统会立即抛出 BuildBudgetError(附带 stage="declaration"、块路径、算子名称、实际规模与上限)。BuildOptions 共有三项预算设置(均为正整数):

设置项默认上限约束对象
max_expression_nodes1,000,000单个已登记表达式根可达的去重 DAG 节点数
max_expression_depth512表达式最大依赖深度
max_total_nodes20,000,000累计新建节点数及最终 IR 保留节点数上限

下面的示例演示故意触发预算上限并捕获错误,随后正常编译模型:

py
def demonstrate_budget() -> None:
    """构图超限时立即停止;退出上下文后恢复默认预算。"""
    with build_options(BuildOptions(max_expression_nodes=50)):
        try:
            Root.build("Root", 10)
        except BuildBudgetError as error:
            print(error)
        else:
            raise AssertionError("large recursive declaration must be rejected")
bash
python packages/fly_ruler/examples/core/compilation_resources.py --output results/compile_resources
声明计数与作用域规则
  • source.build_stats 提供 largest_expression_nodes、expression_depth、created_nodes 与 stored_expression_nodes;重复复用同一中间信号只计新建节点,不会按树展开重复收费。
  • build_options(...) 支持在顶层构建外嵌套,退出上下文时自动恢复外层配置;BuildOptions 同时管理 externalize_threshold 数组外置阈值。

查看各阶段耗时 ​

  • 声明规模:读取 source.build_stats。
  • 编译与代码生成耗时:读取 model.compilation_report(包含目标生成、产物发布、native 工具链耗时及生成源码字节数),或在编译时传入 OperationContext(verbosity="detailed") 在终端实时打印各阶段进度。

构建期循环 vs 运行期循环 ​

  • 构建期循环:在 @fr.block / @fr.system 中使用普通 Python for 循环用于展开重复结构或递推表达式,只要共享 DAG 规模与深度在预算内即可正常声明。
  • 运行期循环:若需要依赖运行期状态或动态终止条件的迭代算法,请通过 fr.math.call 接入自定义算子。
紧凑 DAG 序列化格式

source.ir.to_json() 与 Signal.to_expr_dict() 采用局部节点索引表(kind="dag"、version=1、nodes、root)保存共享子图,因此导出与加载时均不会将共享表达式还原为指数级展开树。

下一步 ​