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

Aperta
#976 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
58/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
python
Ambito
performance

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
Python
Stelle
25
Fork
25
Merge medio
4h 5m
PR unite (30g)
10

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di lanl/PyBNF

Tutte le issue di lanl/PyBNF

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.