Skip to content

Finding where the time goes

How to find which phase, which entry and which solve a model spends its time on. Read this before Making a solve faster: the phase that is slow decides which way to try.

The spec is examples/dispatch.yaml.

import polars as pl

import specsolve as sps

pl.Config.set_tbl_rows(30)

MODEL = 'examples/dispatch.yaml'
GENERATORS = ['wind', 'solar', 'gas']

sources = {
    'snapshot': range(4),
    'generator': GENERATORS,
    'p_max': pl.DataFrame({'generator': GENERATORS, 'value': [80.0, 0.0, 200.0]}),
    'cost': pl.DataFrame({'generator': GENERATORS, 'value': [10.0, 25.0, 50.0]}),
    'load': pl.DataFrame({'snapshot': range(4), 'value': [60.0, 120.0, 180.0, 90.0]}),
}

The phases of a solve

A model is clocked in nine phases, from the spec as you give it to the archive on disk. Each phase starts where the one before it ended, so the phases add up to the whole call:

flowchart TB
    SPEC["the spec<br/>a YAML file or a mapping"] -->|load| PROGRAM["the checked spec and its program"]
    DATA[("your sources<br/>parquet files and tables")] -->|tidy| TIDY["the tidy tables<br/>as sps.tidy returns them"]
    PROGRAM --> ATTACHED
    TIDY -->|attach| ATTACHED["the data on the program<br/>assumptions checked"]
    ATTACHED -->|build| BUILT["the built model<br/>columns, rows and matrix"]
    BUILT -->|write| FILE["an LP or MPS file"]
    BUILT -->|handoff| LOADED["the solver, holding the model<br/>and any start="]
    LOADED -->|solve| VALUES["the solver's values and duals"]
    VALUES -->|readback| RESULT["the Result<br/>by coordinate"]
    RESULT -->|archive| ARCHIVE[("the archive on disk<br/>metrics.parquet written last")]

Each arrow is one phase, and each box is what that phase produces. Metrics defines each phase.

Every result carries its clocks. Read them as a table, one row per phase:

result = sps.solve(MODEL, sources)
print(result.metrics.phases)
shape: (9, 2)
┌──────────┬──────────┐
│ phase    ┆ seconds  │
│ ---      ┆ ---      │
│ str      ┆ f64      │
╞══════════╪══════════╡
│ load     ┆ 0.000801 │
│ tidy     ┆ 0.001079 │
│ attach   ┆ 0.000789 │
│ build    ┆ 0.004306 │
│ handoff  ┆ 0.000939 │
│ solve    ┆ 0.000293 │
│ readback ┆ 0.000132 │
│ write    ┆ 0.0      │
│ archive  ┆ 0.0      │
└──────────┴──────────┘

A phase that never ran, here write and archive, reads zero. On a model of 300,000 columns, solve took 2.4 s of a 2.5 to 2.6 s call (#2180).

An archive keeps the same row, so you can read the clocks later or on another machine:

print(sps.read_archive('runs/dispatch.zip').metrics.phases)

Every lap, one row each

model.timings() logs every lap the model took, one row each:

model = sps.build(MODEL, sources)
model.solve()
print(model.timings())
shape: (28, 5)
┌─────┬──────────┬─────────────────┬───────────────┬──────────┐
│ run ┆ phase    ┆ step            ┆ entry         ┆ seconds  │
│ --- ┆ ---      ┆ ---             ┆ ---           ┆ ---      │
│ u32 ┆ str      ┆ str             ┆ str           ┆ f64      │
╞═════╪══════════╪═════════════════╪═══════════════╪══════════╡
│ 0   ┆ load     ┆ null            ┆ null          ┆ 0.00077  │
│ 0   ┆ tidy     ┆ read            ┆ null          ┆ 0.00006  │
│ 0   ┆ tidy     ┆ shape           ┆ generator     ┆ 0.000339 │
│ 0   ┆ tidy     ┆ shape           ┆ snapshot      ┆ 0.000235 │
│ 0   ┆ tidy     ┆ shape           ┆ cost          ┆ 0.000154 │
│ 0   ┆ tidy     ┆ shape           ┆ load          ┆ 0.000099 │
│ 0   ┆ tidy     ┆ shape           ┆ p_max         ┆ 0.00009  │
│ 0   ┆ tidy     ┆ shape           ┆ null          ┆ 0.000002 │
│ 0   ┆ attach   ┆ encode          ┆ cost          ┆ 0.000094 │
│ 0   ┆ attach   ┆ content         ┆ cost          ┆ 0.000056 │
│ 0   ┆ attach   ┆ encode          ┆ load          ┆ 0.000025 │
│ 0   ┆ attach   ┆ content         ┆ load          ┆ 0.000193 │
│ 0   ┆ attach   ┆ encode          ┆ p_max         ┆ 0.000053 │
│ 0   ┆ attach   ┆ content         ┆ p_max         ┆ 0.000049 │
│ 0   ┆ attach   ┆ fill            ┆ null          ┆ 0.000031 │
│ 0   ┆ attach   ┆ specialize      ┆ null          ┆ 0.000228 │
│ 0   ┆ attach   ┆ assumptions     ┆ null          ┆ 0.000005 │
│ 0   ┆ build    ┆ variable        ┆ p             ┆ 0.001423 │
│ 0   ┆ build    ┆ constraint      ┆ power_balance ┆ 0.001848 │
│ 0   ┆ build    ┆ objective       ┆ null          ┆ 0.000745 │
│ 0   ┆ build    ┆ matrix          ┆ null          ┆ 0.000162 │
│ 0   ┆ build    ┆ sink_tables     ┆ null          ┆ 0.000101 │
│ 0   ┆ handoff  ┆ match           ┆ null          ┆ 0.000011 │
│ 0   ┆ handoff  ┆ capability      ┆ null          ┆ 0.000046 │
│ 0   ┆ handoff  ┆ solver_instance ┆ null          ┆ 0.000788 │
│ 0   ┆ handoff  ┆ start           ┆ null          ┆ 0.000003 │
│ 0   ┆ solve    ┆ null            ┆ null          ┆ 0.000246 │
│ 0   ┆ readback ┆ null            ┆ null          ┆ 0.00012  │
└─────┴──────────┴─────────────────┴───────────────┴──────────┘
  • run counts the results handed back before the lap. Run 0 ends with the first result.
  • step says what a lap did inside its phase, and entry names the entry it built. The tidy, the attach, the build and the handoff have steps. Elsewhere both are null.
  • The rows add up to the metrics. A phase's rows sum to its clock in model.metrics(), and a run's rows to the metrics of the result that ends it.

The source a tidy spends

Filter the log to the tidy to find the source that took the time:

print(model.timings().filter(phase='tidy').select('step', 'entry', 'seconds'))
shape: (7, 3)
┌───────┬───────────┬──────────┐
│ step  ┆ entry     ┆ seconds  │
│ ---   ┆ ---       ┆ ---      │
│ str   ┆ str       ┆ f64      │
╞═══════╪═══════════╪══════════╡
│ read  ┆ null      ┆ 0.00006  │
│ shape ┆ generator ┆ 0.000339 │
│ shape ┆ snapshot  ┆ 0.000235 │
│ shape ┆ cost      ┆ 0.000154 │
│ shape ┆ load      ┆ 0.000099 │
│ shape ┆ p_max     ┆ 0.00009  │
│ shape ┆ null      ┆ 0.000002 │
└───────┴───────────┴──────────┘

read is every path read at once, so one row for all the files. Then each dimension, relation and parameter has a shape row, for its columns and their types. The last shape row has no entry: it is the refusal that needs every source read, a dimension that got no labels.

The attach has a row per step as well. encode turns a table's labels into its dimensions' own type, and content checks what that shows: every label one of its dimension's, no coordinate given twice, and a row wherever the spec refuses to lack one. Each relation and parameter has one row of each. fill, specialize and assumptions follow, once each: the missing rows a divisor or a power reads written in, the program rewritten with the conditions the data decides, and the spec's assumptions checked.

The entry a build spends

Filter the log to the build, and sort it, to find the entry that took the time:

print(model.timings().filter(phase='build').sort('seconds', descending=True))
shape: (5, 5)
┌─────┬───────┬─────────────┬───────────────┬──────────┐
│ run ┆ phase ┆ step        ┆ entry         ┆ seconds  │
│ --- ┆ ---   ┆ ---         ┆ ---           ┆ ---      │
│ u32 ┆ str   ┆ str         ┆ str           ┆ f64      │
╞═════╪═══════╪═════════════╪═══════════════╪══════════╡
│ 0   ┆ build ┆ constraint  ┆ power_balance ┆ 0.001848 │
│ 0   ┆ build ┆ variable    ┆ p             ┆ 0.001423 │
│ 0   ┆ build ┆ objective   ┆ null          ┆ 0.000745 │
│ 0   ┆ build ┆ matrix      ┆ null          ┆ 0.000162 │
│ 0   ┆ build ┆ sink_tables ┆ null          ┆ 0.000101 │
└─────┴───────┴─────────────┴───────────────┴──────────┘

The build's steps follow it: one variable, sos or constraint row per entry, the objective, then matrix, which stacks every constraint into one matrix, and sink_tables, the rest of what the solver is handed. An entry's seconds are its own: they hold when the entries build in another order. An update that gives only new numbers at the old coordinates reads again just the entries those numbers feed. Its build logs splice, those entries and sink_tables, with no matrix row: a coefficient read again is spliced into the matrix within its constraint's row.

The steps of a handoff

The handoff's rows name its steps, the same for every solver:

print(model.timings().filter(phase='handoff').select('step', 'seconds'))
shape: (4, 2)
┌─────────────────┬──────────┐
│ step            ┆ seconds  │
│ ---             ┆ ---      │
│ str             ┆ f64      │
╞═════════════════╪══════════╡
│ match           ┆ 0.000011 │
│ capability      ┆ 0.000046 │
│ solver_instance ┆ 0.000788 │
│ start           ┆ 0.000003 │
└─────────────────┴──────────┘

A first solve runs match, capability, solver_instance and start. match matches your start= to this build, capability checks the solver can take the model, solver_instance is a new solver instance taking it, and start gives the solver the start. The first solver_instance in a process also imports the solver's package. There are as many solver_instance rows as metrics().solver_instances counts.

A later solve keeps the solver it holds where only numbers moved, and pushes them onto it; otherwise it closes it and takes a new solver_instance. A digest row comes only from an update that rebuilds the model while a solver is held: the held solver reads its fingerprint of its model before the rebuild. Two solves with no update between them log no digest.

Each solve of a loop

A model that you update and solve again logs one run per result. Group the log by run to compare the solves:

for load in ([90.0, 150.0, 200.0, 60.0], [30.0, 60.0, 90.0, 45.0]):
    model.update({'load': pl.DataFrame({'snapshot': range(4), 'value': load})})
    model.solve()

per_run = model.timings().group_by('run', 'phase', maintain_order=True).agg(pl.col('seconds').sum())
print(per_run.pivot('phase', index='run', values='seconds'))
model.close()
shape: (3, 8)
┌─────┬─────────┬──────────┬──────────┬──────────┬──────────┬──────────┬──────────┐
│ run ┆ load    ┆ tidy     ┆ attach   ┆ build    ┆ handoff  ┆ solve    ┆ readback │
│ --- ┆ ---     ┆ ---      ┆ ---      ┆ ---      ┆ ---      ┆ ---      ┆ ---      │
│ u32 ┆ f64     ┆ f64      ┆ f64      ┆ f64      ┆ f64      ┆ f64      ┆ f64      │
╞═════╪═════════╪══════════╪══════════╪══════════╪══════════╪══════════╪══════════╡
│ 0   ┆ 0.00077 ┆ 0.000979 ┆ 0.000734 ┆ 0.004279 ┆ 0.000847 ┆ 0.000246 ┆ 0.00012  │
│ 1   ┆ null    ┆ 0.000762 ┆ 0.000583 ┆ 0.001829 ┆ 0.001006 ┆ 0.000218 ┆ 0.000124 │
│ 2   ┆ null    ┆ 0.000732 ┆ 0.000505 ┆ 0.001701 ┆ 0.000715 ┆ 0.000184 ┆ 0.000116 │
└─────┴─────────┴──────────┴──────────┴──────────┴──────────┴──────────┴──────────┘

Run 0 holds the load and the first build. Each later run holds its update, its build and its solve. An archive written by a solve lands in that solve's run. The result's own row is written into the archive before it lands, so the run holds the landing and the result does not.

What the slow phase points to

Where the time goes What to try
solve start from an earlier answer, accept a gap, and the ways after it
build and handoff, again on every update keep the model loaded
handoff, in solver_instance on every update keep the model loaded: only numbers may move
build on many small models build many small models faster
build on a large model the entry that holds the time, then make the model smaller

Report a slow phase

Open an issue at github.com/fluxopt/specsolve/issues when one phase takes longer than you expect for the size of your model. The clocks tell a maintainer where to look, and an archive lets them run your model again. Write the report in five steps:

  1. Solve the model with an archive. One file then holds the spec, the data, the answer and the clocks.

    sps.solve('model.yaml', sources, archive='runs/slow.zip')
    
  2. Paste the phases, the model's size and the versions.

    result = sps.read_archive('runs/slow.zip')
    print(result.metrics.phases)
    print(result.metrics.columns, result.metrics.rows, result.metrics.nonzeros)
    print(result.provenance)
    

    The provenance names the solver, its version and options, and the specsolve and mathspec versions. Where build is slow, paste the build's rows of model.timings() too.

  3. Say which phase is slow, and why you expected less. The best evidence is the same model at two sizes. "build took 2 s at 1,000 snapshots and 90 s at 10,000" shows a phase that grows faster than the model.

  4. Attach the archive if you may share the data. Anyone can solve it again from the file alone, with sps.solve(result.spec, result.sources). If you may not, attach the spec and give the number of labels in each dimension.

  5. Name the machine. Give its cores, its memory and its operating system, and say whether other work ran during the solve.

A slow solve is the solver's own run. Try the ways before you report it. Report it when another tool hands the same solver the same model and it solves faster.