flysim-malecns / docs /live-sim.md
DevNexon's picture
flysim-malecns: connectome-v1 release
aecbd27 verified
|
Raw History Blame Contribute Delete
12.7 kB
# Live simulation worker
*Engine side of the streaming worker in `flysim.live`. Nothing here is a validation result.*
> **Note for this release.** The worker was written for an interactive application (a web app with a 3D view of the brain), which is not part of this release. This document keeps the parts that live in `flysim`: what a block is, the message stream, live or replay, pacing, workers and the cache. The HTTP and WebSocket endpoints, the app settings and the mapping from app inputs to a stimulus were in the application and are left out.
The worker runs one stimulus block at a time on the MaleCNS connectome and streams it in 10 ms chunks. Each chunk carries the new spikes and the readout spike counts. Every live block is recorded, and recordings are replayed when the workers are busy or when the same block is asked for again. The client gives the stimulus and the rate explicitly; the stream is a readout only.
## Where the code is
| Part | Where |
|---|---|
| Block definition, stimuli and chain status, the runner | `flysim/src/flysim/live/model.py` |
| Recordings and the replay cache | `flysim/src/flysim/live/cache.py` |
| Worker processes, queue, wait estimate | `flysim/src/flysim/live/pool.py` |
| Live or replay, pacing, message format, settings (`LiveConfig`) | `flysim/src/flysim/live/service.py` |
| Positions, stimulus targets and readout neurons packed for a 3D view | `flysim/src/flysim/live/brain.py` |
| Tests | `flysim/tests/test_live.py`, `flysim/tests/test_brain.py` |
## What a block is
A block is exactly one trial of the chain tests (`flysim.validation.chains`):
- matrix `full` of `connectome-v1` (the only variant that passed the pruning-equivalence test);
- `CpuEngine(np.float32)` with its default kernel (`vec`, bit for bit equal to the plain kernel on all 1,520 chain-test trials; see `records/results/kernel-check-vec.json`);
- `ModelParams(w_syn=W_SYN_MALE)`;
- 600 ms, with Poisson input over [0, 300) ms into the right-side neurons of the stimulus' source types, and nothing after.
**Every block starts from rest** (`engine.reset()`). There is no "continuous" option that carries state between blocks. LC4 and LPLC-driven stimuli can switch on a self-sustaining loop of 49 VNC-side neurons, which would otherwise leak into the next block (`records/validation-log.md`: *Chain tests on MaleCNS* and *Decision on the VNC loop*, 2026-11-04).
**Seeds** follow the pre-registered seeding rule: `trial_rng(experiment, "<stimulus>/<rate>Hz", seed)`, with experiment `"live"`. With experiment `"chain-tests"`, the same code gives the recorded chain-test trial of that number. The real-connectome test checks this for LC9 at 100 Hz, trial 0: the per-body readout counts and the network spike counts equal the committed `records/results/chain-tests-trials.json`.
**Stimuli and chain status**, with their chain-test verdicts:
| Stimulus | Chain | Readout | `chain_status` |
|---|---|---|---|
| LC4 (55 right-side neurons) | escape | DNp01 | `not_validated` (FAIL: activity persists after the stimulus) |
| LC16 (94) | back away | MDN | `not_validated` (FAIL: readout too weak and not specific; the pre-registered alternative stimulus fails the post-stimulus criterion) |
| LC9 (115) | approach | DNp09 | `validated` (PASS) |
The worker simulates all three. Every message carries `chain_status`, so a client can say when a readout is not a validated response. The alternative stimulus LC16 + LPLC1 + LPLC2 is not offered.
## Using it from Python
`LiveService(source, LiveConfig(...))` with `source = ConnectomeSource(Path("data/connectome-v1"), unpack_dir=...)`. `service.start()` spawns the workers; `service.info()` lists the stimuli, bounds and defaults; `service.stream(BlockRequest(stimulus, rate_hz, seed, min_stretch=None))` is an async iterator of JSON-ready dicts, one per message; `service.close()` stops the pool. A request is the equivalent of this JSON:
```json
{"stimulus": "LC9", "rate_hz": 100, "seed": 0, "min_stretch": 6.0}
```
- `stimulus` is `LC4`, `LC16` or `LC9`.
- `rate_hz` is in [0, 200].
- `seed` is in [0, 2³¹ − 1]. A caller that wants a fresh run picks a fresh seed; the same seed repeats a block exactly (and then replays from the cache).
- `min_stretch` is optional, in [1, 100]; it defaults to `LiveConfig.min_stretch`.
For a single block without the pool, `run_block(make_engine(matrix), LiveModel.build(neurons), BlockSpec(stimulus, rate_hz, seed), experiment)` yields the chunks directly (this is what the real-connectome test does).
## Message format
Each message is a JSON-ready dict. All messages of a block share these fields:
| Field | Meaning |
|---|---|
| `type` | `queued`, `start`, `chunk`, `end` or `error` |
| `run` | id of this stream |
| `source` | `live` or `replay` |
| `stimulus`, `chain`, `readout` | e.g. `LC9`, `approach`, `DNp09` |
| `chain_status` | `validated` or `not_validated` |
A block arrives in this order:
1. **`queued`** (live only): `queue_position` (blocks waiting, this one included) and `expected_wait_s` (`null` while no worker is ready).
2. **`start`**, which describes the block:
- `replay_reason`: `null` for a live block, `"repeat"` or `"busy"` for a replay;
- `rate_hz`, the rounded rate that runs, and `rate_hz_requested`;
- `seed`, the seed that runs (a busy replay may use another one), and `seed_requested`;
- `status_basis`, the chain-test verdict behind `chain_status` (a short string that cites the record);
- `block`: `dt_ms` 0.1, `steps` 6000, `chunk_steps` 100, `chunks` 60, `duration_ms` 600, `stimulus_ms` [0, 300], `starts_from_rest` true;
- `n_neurons`;
- `readouts`: the sides of each readout, e.g. `{"DNp01": ["L", "R"], ...}`;
- `pacing`: `stretch`, `min_stretch`, `compute_ratio`, `margin`.
3. **`chunk`**, 60 times:
- `index` (0–59), `t0_ms`, `t1_ms`;
- `neurons`: the neuron indices that spiked in the chunk, in time order (row order of `neurons.parquet`);
- `steps`: each spike's step within the chunk (0–99, in 0.1 ms);
- `readouts`: spike counts in this chunk per readout and side, e.g. `{"DNp01": {"L": 0, "R": 2}, "MDN": {...}, "DNp09": {...}}`.
4. **`end`**:
- `summary`: total spikes; spikes in the stimulus window; and readout counts per side over the stimulus window (`readouts_stimulus`) and the whole block (`readouts_block`);
- `compute_s` and `compute_ratio` of the live run. A replay repeats the recorded values.
An **`error`** message has `detail` instead, plus the common fields when the request was valid.
For size: LC9 at 100 Hz has about 11.5k spikes per block, and the whole stream is about 125 kB of JSON.
## Live or replay
In this order:
1. If a recording of exactly this (stimulus, rounded rate, seed) exists, it is replayed (`"repeat"`). A block is a pure function of that key, so the replay is the same computation. `serve_repeats=False` turns this off.
2. Otherwise, if a new block would wait at most `max_wait_s` (2 s) for a worker, it runs live.
3. Otherwise a recording of the same stimulus and rounded rate is replayed (`"busy"`): the requested seed if it is stored, else the lowest stored seed. `start.seed` says which seed plays.
4. With no recording to fall back on, the block is queued live anyway. If `max_queue` blocks are already waiting, it is refused instead.
**Rate rounding.** Requested rates are rounded to `rate_step_hz` (5 Hz), and both live runs and replays use the rounded rate. A recording is therefore always exactly the live block its key names.
**Wait estimate** (`flysim.live.pool.expected_wait`). Every block is assumed to take the current estimate of block compute time. That estimate starts at `compute_ratio_prior` × 0.6 s (1.12, the provisional figure of the `vec` kernel) and then follows an exponential moving average (α 0.3) of measured blocks. Running blocks finish at start + estimate. Queued blocks go, first in first out, to the worker that frees up first. The wait is the time until the earliest worker frees up after that. Before any worker has loaded, the wait is infinite, so a recording is replayed if one exists, and otherwise the block waits for the load.
## Pacing (time stretch)
`stretch = max(min_stretch, measured_compute_ratio × 1.2)`, so compute stays ahead of display and a run streams while it is calculated:
- **The worker does not pace.** It sends each chunk as soon as it is computed, so the stream runs ahead of the display.
- **The display applies the stretch.** `start.pacing.stretch` uses the pool's estimated compute ratio at the moment the block starts. The display shows simulated time *t* at wall time *t* × `stretch` after it starts the block. Because the estimate includes the 1.2 margin, chunks normally arrive before they are due. If one is late, the display waits for it.
- **Replays** have no compute to wait for. Their stretch is `min_stretch`.
`min_stretch` defaults to 4.0, a display choice: a 600 ms block then plays over 2.4 s. With the `vec` kernel the compute ratio is about 1.1 on the dev container (1.3 with the margin), so `min_stretch` sets the pace.
## Workers, memory, cache
- **Processes.** The pool is `workers` processes, started with `spawn`. Each loads the matrix once, builds one engine, compiles the kernel with a 10 ms warm-up, and then takes blocks from a shared queue: one block per process at a time. After each chunk, the worker sends it to the parent process.
- A worker that dies fails its block and is replaced.
- When no worker can load (for example, missing data), every waiting block fails, and the service reports live runs as unavailable.
- **Memory.** With `unpack_dir` set, the matrix is unpacked once to `.npy` files there, about 142 MB. Every worker then maps them read-only, so the pages are shared. A worker's RSS was about 250 MB with the mapped matrix touched, where the speed benchmark measured a 590 MB peak when each process decompresses its own copy.
- **Cache.** Every live block is recorded by its worker, even if the client has gone. A recording holds the spikes and the per-chunk readout counts in a compressed `.npz` file of about 29 kB for LC9 at 100 Hz. It is stored as `<cache_dir>/recordings/<fingerprint>/<stimulus>_<rate>Hz_s<seed>.npz` and written atomically.
- The fingerprint covers the matrix and neuron hashes from `SHA256SUMS`, the model parameters, the block layout, the seeding experiment and a format number. A change to any of them starts a fresh cache.
- A damaged file counts as a miss.
- The cache is bounded by `cache_max_bytes` (default 1 GiB, about 35,000 recordings). After each write, recordings of other fingerprints go first (they can never replay), then the least recently used of the current one; a replay counts as a use.
## Settings (`LiveConfig`)
`workers` (default 1; 0 = replay only), `cache_dir`, `unpack_dir`, `min_stretch` (4.0), `max_wait_s` (2.0), `rate_step_hz` (5.0), `compute_ratio_prior` (1.12), `cache_max_bytes` (1 GiB), `stretch_margin` (1.2), `serve_repeats` (true), `max_queue` (8), `event_timeout_s` (120), `experiment` (`"live"`).
## Tests
- **Synthetic network** (40 neurons; no download):
- stimuli, statuses and block constants;
- the stimulus targets (right side) and readout slots;
- request validation and rate rounding;
- chunked stepping gives the same spikes as one whole-trial run on the plain kernel;
- readout counts match the spikes, and there is no input after 300 ms;
- every block starts from rest (a block after another block repeats exactly);
- recording round trip, cache keys and fingerprints, busy fallback to another seed, damaged files;
- `expected_wait` cases;
- a real spawned worker process streams the same chunks as an in-process run, writes the cache and updates the estimate;
- a worker that cannot load fails its block;
- the service: live, then a repeat replay with identical chunks; busy fallback; queue-anyway; refused requests.
- **Brain layout** (`flysim/tests/test_brain.py`): a small table packed and decoded (bounds, a missing position, region codes, stimulus targets, readout sides, the ETag following the checksums), quantization within half a step, and the real layout (165,122 neurons, 496 without a position).
- **Real connectome** (uses `data/connectome-v1/` of this dataset, or set `FLYSIM_CONNECTOME`; skipped if absent): a live block under the chain-test seed key reproduces the committed chain-test record for LC9 at 100 Hz, trial 0.
## Engine API
The runner uses `reset`, `schedule_inputs`, `advance_to` and `spikes_since` only. Two small points:
- `reset()` reallocates the state arrays every block (a few MB, negligible).
- The spike log grows over the whole block, though the runner only reads the last chunk.