Skip to content

Add run_scenarios and storage - #3756

Merged
quaquel merged 46 commits into
mesa:mainfrom
quaquel:run_scenarios
Jul 5, 2026
Merged

quaquel merged 46 commits into
mesa:mainfrom
quaquel:run_scenarios

Conversation

@quaquel

@quaquel quaquel commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

This PR builds on #3753 by adding run_scenarios, a protocol for storage (Store, Writer, and Reference), and an implementation of the protocol for in memory storage (InMemoryStore, InMemoryWriter, and InMemoryReference).

The main focus here is hashing out the protocol. For background, see #3483 (comment).

The overarching aim is to replace batch runner with the following basic API

# generate samples with scipy.qmc or salib

scenarios = MyScenario.from_dataframe(samples, rng=42, replications=10)
run_config = RunConfig(MyModel, until=150)

with ProcessPoolExecutor() as executor:
    results = run_scenarios(scenarios, run_config, executor=executor, store=InMemoryStore())

The main challenge is to design all of this such that we can support sequential local running (executor=None), parallel local running (ProcessPoolExecutor), and HPC (mpi4py.futures.MPIPoolExecutor). This brings with it a wide range of design considerations.

Some key considerations are

  • We want to minimize the amount of data being exchanged between the root process and the worker processes.
  • We want to avoid creating many small files (unless you want to be kicked of the HPC by the system administrators)
  • We want to avoid crashing an ensemble run if any individual scenario fails for whatever reason. Instead, we want to log the scenario/replication combination that failed and its cause and move on

To satisfy these and other considerations, this PR adds a bunch of things

  1. A Store protocol that specifies the basic interface of any storage solution. Store always runs root side.
  2. A Writer protocol that specifies how output from RunConfiguration.extract_output is to be send back to the root process (consideration 1). Writer always runs worker side.
  3. A Reference protocol that specifies the fields in a message being send from the worker to the root
  4. Example implementations of all three protocols are provided for in memory storage. So we have InMemoryStore, InMemoryWriter, and InMemoryReference. A future PR will add a disk based implementation of all three protocols while accounting for consideration 2. Note that InMemoryStore is just a simple dict based backend and nothing more fancy. It's here now just to clarify how it all works.
  5. There is an implementation of run_scenarios with support for sequential running. This implementation also handles the safe running of scenarios with graceful handling of failing scenarios (consideration 3). A future PR will add support for ProcessPoolExecutor and MPIPoolExecutor which have the same API so can be handled in the same way.

The sequence diagram shown below shows how it all fits together in practice.

Untitled diagram-2026-06-25-141239

@quaquel

quaquel commented Jun 25, 2026 •

Copy link
Copy Markdown
Member Author

I have done some more work on this to simplify and streamline it. I can really benefit from feedback at this point, so @tpike3, @EwoutH, and @codebreaker32, please chime in. To help clarify what is going on, please check the sequence diagram below.

It shows the flow of information and the basic protocols as specified by this PR. The main thing not yet fully settled is what happens if a model uses a file based DataRecorder. I want to leave that to a future PR.

Untitled diagram-2026-06-25-141239

@codebreaker32 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks Good To Me!

@quaquel

quaquel commented Jun 26, 2026

Copy link
Copy Markdown
Member Author

Thanks! I'll give @EwoutH and @tpike3 a chance to chime in as well before merging it. In the meantime, I'll start on the next step: parallel processing.

@quaquel quaquel added experimental Release notes label feature Release notes label labels Jul 1, 2026
@quaquel quaquel linked an issue Jul 2, 2026 that may be closed by this pull request
@quaquel

quaquel commented Jul 2, 2026

Copy link
Copy Markdown
Member Author

For the record, I pushed an update that back ports some changes identified in the next PR for parallelization support as well as forcing replication_id to always be an int (see #3762).

@EwoutH

EwoutH commented Jul 2, 2026

Copy link
Copy Markdown
Member

Bit of a hectic time. Will try to review this weekend.

@EwoutH

EwoutH commented Jul 3, 2026

Copy link
Copy Markdown
Member

Thanks for this PR. You can see you built this earlier (with the EMAworkbench) it's impressive!

Few questions:

  1. Scope: Previously I think you stated that running (different model configurations) was out of scope and should be handled by external packages. What changed? Or was that only the configuration of scenario's, and is this just providing a convenient, exposed interface?
  2. Storage/serialization: is the plan for the disk backend to delegate to Parquet rather than a custom format? pyarrow.dataset already handles the "one logical dataset, many partitions" case that consideration 2 is about, would that be useful? And in the parallel case, do workers write their own partitions (then consolidate) or send everything back to root for writing? The Writer seam supports both, the disk backend has to pick a lane I think.
  3. Resumption/restart: right now write_scenarios marks everything PENDING and the loop runs all of it. It doesn't skip completed runs, so a sweep that dies at 9,000/10,000 restarts from zero. And do we want caching and/or automated retries?
  4. Store abstraction: would it be useful keeping Store as the pure Protocol and adding an AbstractStore(ABC) for the derived methods? succeeded/failed/pending are identical one-liners for any record-keyed store, and status() is ~10 lines that'd be copied verbatim into every backend.
  5. Is InMemoryStore the right default when store=None, given it's illustrative and holds every run's dataframes in memory? Especially if we consider checkpoints and retries?

@quaquel

quaquel commented Jul 3, 2026 •

Copy link
Copy Markdown
Member Author

Thanks for the comments and suggestions. Below my responses.

Scope: Previously I think you stated that running (different model configurations) was out of scope and should be handled by external packages. What changed? Or was that only the configuration of scenario's, and is this just providing a convenient, exposed interface?

The generation of samples (e.g., Salib, numpy qmc) and the execution (e.g., ProcessPoolExecutor, MPIPoolExecutor) are out of scope. This series of PRs provides the connection between those libraries and Mesa. Below is a quick example from my testing that shows how it fits together. As you can see, this code uses rescale_samples, run_scenario, and RunConfiguration from mesa in combination with numpy, pandas, and concurrent.futures.

    samples = sp.stats.qmc.LatinHypercube(4, rng=42).random(50)
    samples = rescale_samples(samples, np.array([[0.5,1],[0.05, 0.5],[0.2, 0.8],[1,5]]))
    samples[0, :] = np.floor(samples[3, :]) # radius needs to be an integer, this means it will be between 1-4.
    samples = pd.DataFrame(samples, columns=["density", "minoriy_pc", "homophily", "radius"])
    samples.radius = samples.radius.astype(int)

    scenarios = SchellingScenario.from_dataframe(samples, replications=2)

    with ProcessPoolExecutor(max_workers=4) as executor:
        results = run_scenarios(scenarios, RunConfiguration(Schelling, until=100), executor=executor)

    print(results)

Storage/serialization: is the plan for the disk backend to delegate to Parquet rather than a custom format? pyarrow.dataset already handles the "one logical dataset, many partitions" case that consideration 2 is about, would that be useful? And in the parallel case, do workers write their own partitions (then consolidate) or send everything back to root for writing? The Writer seam supports both, the disk backend has to pick a lane I think.

I am about to start on OnDiskStore and I am inclined to provide a reference implementation using parquet but I will check pyarrow as well. In the parallel case, each worker will have its own file. On a big MPI cluster, you don't want to send large amounts of data over the network.

Resumption/restart: right now write_scenarios marks everything PENDING and the loop runs all of it. It doesn't skip completed runs, so a sweep that dies at 9,000/10,000 restarts from zero. And do we want caching and/or automated retries?

This will be handled by a later PR. As you can see in #3768, It is one of the last items on the to do list.

Store abstraction: would it be useful keeping Store as the pure Protocol and adding an AbstractStore(ABC) for the derived methods? succeeded/failed/pending are identical one-liners for any record-keyed store, and status() is ~10 lines that'd be copied verbatim into every backend.

I'll have to see now that I am about to start on an OnDiskStore implementation. If there is overlap between both the InMemoryStore and the OnDiskStore, I'll factor out the overlap into an ABC.

Is InMemoryStore the right default when store=None, given it's illustrative and holds every run's dataframes in memory? Especially if we consider checkpoints and retries?

For smal local debug runs, I think it is a fine default. Moreover, an InMemoryStore default is tricky because you need a file name and directory.

class OutcomeExtractionException(RunStageException):
"""Raised when extracting outcomes from a finished model fails."""

origin = FailureOrigin.EXTRACTING

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make this
origin = FailureOrigin = FailureOrigin.Extracting

for consistency

@edgeofchaos42 edgeofchaos42 left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! This is very awesome! Just one nitpick

@tpike3 tpike3 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@quaquel
quaquel merged commit 5967f4e into mesa:main Jul 5, 2026
10 of 11 checks passed
@quaquel
quaquel deleted the run_scenarios branch July 5, 2026 12:27
@EwoutH EwoutH mentioned this pull request Nov 15, 2026
53 of 65 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

experimental Release notes label feature Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Handling of replication_id=None in Scenario

5 participants