Gradient fits of function-heavy models spend almost all their time re-running bngsim's SymPy analyses on every evaluation

未关闭
#976 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
58/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
python
领域
performance

调研方向

Start with pybnf/bngsim_model/net_model.py, _simulator.py around line 3265, and _result.py around line 1017, then trace the bngsim Simulator and Model initialization paths named in the profile. Run repro_function_heavy.py with the provided lbfgs.conf and compare evaluation times and objective values before and after the change; the repeated SymPy analysis should no longer dominate each evaluation.

由索引模型根据 Issue 内容生成。

描述

Summary

Some BNGL models produce many algebraic functions as output, for example one function per variant in a high-throughput screen scored with BPSL constraints. For such models, each gradient-fit evaluation (job_type = lbfgs) is dominated by SymPy work inside bngsim. That work depends only on the model's structure, yet it is redone for every evaluation. The simulation itself takes milliseconds.

Environment: PyBNF 1.8.1 (5ecb1f69), bngsim 0.15.0, Python 3.12, macOS arm64 (16 cores).

Reproduce

Save the script below as repro_function_heavy.py, then run:

python repro_function_heavy.py repro 300 30
cd repro && BNGPATH=/path/to/BioNetGen pybnf -c lbfgs.conf -o

The model has 1 species, 300 functions, and 33 free parameters. The data are 300 BPSL probit constraints plus 20 quantitative replicates, with the noise scale shared through qualitative_scale = fit s.

repro_function_heavy.py
"""Standalone reproduction for three PyBNF issues: a model whose outputs are many algebraic functions, fitted to BPSL
probit constraints (one per function) plus a few quantitative replicates.

    python repro_function_heavy.py OUTDIR [N_FUNCTIONS] [N_PARAMS]

Writes OUTDIR/model.bngl, calls.prop, reps/r*.exp and three configs:
  lbfgs.conf        constraints + replicates, job_type = lbfgs (issue: per-evaluation cost dominated by SymPy work)
  prop_only.conf    constraints only, job_type = lbfgs, parallel_count = 2 (issue: routing error)
  check.conf        job_type = check with an estimated noise scale (issue: KeyError)
"""
import sys
from pathlib import Path

import numpy as np


def main(out, n_fun=300, n_par=30, seed=0):
    out = Path(out)
    (out / "reps").mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(seed)
    pars = [f"p{j}" for j in range(n_par)]
    lines = ["begin model", "begin parameters", "  m 4.0", "  K 0.1"]
    lines += [f"  {p} {rng.normal(0, 0.5):.4f}" for p in pars]
    lines += ["end parameters", "begin molecule types", "  counter()", "end molecule types",
              "begin seed species", "  counter() 0", "end seed species",
              "begin observables", "  Molecules x counter()", "end observables", "begin functions",
              "  logF() = m"]
    for i in range(n_fun):
        a, b = rng.choice(n_par, 2, replace=False)
        e = f"({pars[a]}+{pars[b]})"
        lines.append(f"  f{i}() = ln((1+K*exp(2-{e}))/(1+K*exp(-{e}))) - ln((1+K*exp(2))/(1+K))")
    lines += ["end functions", "begin reaction rules", "  0 -> counter() 1", "end reaction rules", "end model"]
    (out / "model.bngl").write_text("\n".join(lines) + "\n")
    (out / "calls.prop").write_text("".join(
        f"f{i} {'>' if rng.random() < 0.5 else '<'} 0 at time=1 confidence 0.98\n" for i in range(n_fun)))
    for j in range(1, 21):
        (out / "reps" / f"r{j}.exp").write_text(f"# time logF\n{1 if j <= 10 else 2} {4 + rng.normal(0, 0.2):.4f}\n")
    reps = ", ".join(f"reps/r{j}.exp" for j in range(1, 21))
    free = ["uniform_var = m 3 5", "loguniform_var = K 1e-3 10", "loguniform_var = s 0.01 2"] + \
           [f"uniform_var = {p} -3 3" for p in pars]
    base = ["edition = 2", "model: model.bngl", "bngl_backend = bngsim", "verbosity = 2"]
    (out / "lbfgs.conf").write_text("\n".join(base + [
        "output_dir = output/lbfgs", "job_type = lbfgs", f"experiment: e1, data: {reps}, calls.prop",
        "noise_model = normal, sigma = fit s", "qualitative_scale = fit s", *free,
        "population_size = 1", "max_iterations = 2", "parallel_count = 2"]) + "\n")
    (out / "prop_only.conf").write_text("\n".join(base + [
        "output_dir = output/prop_only", "job_type = lbfgs", "experiment: e1, data: calls.prop, t_end: 1, n_steps: 1",
        "objective = sos", "qualitative_scale = fit s", *free, "population_size = 1", "max_iterations = 2",
        "parallel_count = 2"]) + "\n")
    (out / "check.conf").write_text("\n".join(base + [
        "output_dir = output/check", "job_type = check", f"experiment: e1, data: {reps}, calls.prop",
        "noise_model = normal, sigma = fit s", "qualitative_scale = fit s", "loguniform_var = s 0.2 0.20002"]) + "\n")
    print(f"wrote {out}: {n_fun} functions over {n_par} parameters")


if __name__ == "__main__":
    main(sys.argv[1], *(int(a) for a in sys.argv[2:]))

Observed

  • Repro (300 functions, 33 parameters): 2 L-BFGS-B iterations take 30 s, about 2.5 s per evaluation inside the worker's simulate step. bngsim itself logs Simulation complete: 8 steps, 19 RHS evals.
  • Larger case (500 functions of about 300 characters, 62 parameters): about 22 s per evaluation; 3 iterations took 3 min 58 s.
  • Diagnostic patch: replacing bngsim._simulator.Simulator._expression_sens_support with lambda self: {} (which affects only error messages) cut these to 8 s and 34 s. The objective values were identical at every iteration (repro: 178.166345; larger case: 133.093164 → 132.115912 → 131.718905).

Where the time goes

From a sampling profile of a Dask worker:

  1. About 90% of worker compute. The call path is Simulator.run → _expression_sens_support → bngsim._codegen.output_sens_support → _analyze_output_sens → _jacobian.differentiate_expression_output_partials, i.e. SymPy derivatives of every function with respect to every sensitivity parameter.
    • It runs on every sensitivity run (_simulator.py, around line 3265).
    • Its result is used only to build an error message when a selector requests an unsupported function's sensitivity (_result.py, around line 1017).
    • It is memoized per Simulator, but pybnf/bngsim_model/net_model.py constructs a new Simulator for each evaluation, so it is recomputed every time.
  2. Most of the rest. The call path is net_model.copy_with_param_set → bngsim Model.clone → Model.__init__ → _guard_function_expressions → guard_rate_law_text → _exprtk_to_sympy → SymPy parse_expr on every function, once per evaluation.

Suggested fixes (either side)

  • bngsim:
    • Compute the support map lazily, only when a Result actually needs a reason.
    • Or cache it module-wide, keyed by the model's structural/codegen key (already computed for the .so cache).
    • Cache the clone-time function guard by expression text.
  • PyBNF: reuse a Simulator, or carry its analysis memo, across evaluations within a worker.

Why it matters

The cost scales with (number of functions) × (number of sensitivity parameters) × (expression size). For data sets with one BPSL constraint per variant, this is the difference between minutes and days of fitting.

主要语言
Python
星标
25
派生
25
平均合并
4 小时 5 分钟
30 天内合并 PR
10

环境准备

  • 提供 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

lanl/PyBNF 的其他 Issue

查看 lanl/PyBNF 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。