Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(models): calibrate VAE working memory per model from the Model Manager (#9910)

Alexander Eichhorn95d7fa46b06d
diff --git a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx
index 4b9c13edb1..9bb48faeb7 100644
--- a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx
+++ b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx
@@ -172,6 +172,20 @@ device_working_mem_gb: 4
Once decoding completes, the model manager "reclaims" the extra VRAM allocated as working memory for future model loading operations.
:::
+#### Calibrating a model's working memory
+
+Invoke's decode estimates are measured on a few reference GPUs. Your GPU, driver and settings can need more or less. A calibration measures what a model's VAE decode really takes on your GPU, and Invoke uses those measurements from then on.
+
+- **What it runs**: a few short text-to-image generations of the model at three sizes, up to the largest your GPU can decode in one piece with the VAE fully loaded in the memory free on it when the calibration is planned, in each VAE precision the model can decode in. Before each measured operation, Invoke moves the other models off the GPU, so the measured model is fully loaded. Each size runs once to warm up and twice more. The generations go through the normal queue, so they wait behind queued work and appear there like any other generation. Their images are intermediates: they never appear in the gallery or on a board, and Clear Intermediates removes them once the calibration has finished.
+- **Who and where**: administrators only. It needs exactly one GPU set as the generation device; with several, it is not available. One calibration runs on the GPU at a time: starting another while one runs, from another browser tab for instance, is refused until it has finished or you stop it. That includes the moment between two of its sizes: another administrator's calibration whose page was closed holds the GPU for two more minutes. Your own interrupted calibration does not hold you back: starting a new one replaces it. If another calibration ran on the GPU in between all the same, the first one cannot go on: calibrate it again. If the model, or another model the calibration loads, is replaced or reinstalled while the calibration runs, the sizes still to come fail with a note to calibrate again, and the calibration counts as stopped: the sizes it already measured are discarded too, since they measured the model as it was before.
+- **What it changes**: decodes up to the largest size measured use the measured values, plus the same 5% margin the built-in values carry. Measurements that a fragmented GPU memory pool inflated, or taken while the VAE was only partly on the GPU, are left out, and the Model Manager shows those sizes as not counted. Larger decodes use whichever of the measured and the built-in estimate is larger. Other models that decode the same way (for example, SD1.5 and SDXL models when you calibrate an SDXL model) use the measurements too. Because the estimate decides when a large decode is split into tiles up front, a calibration can change which large images are decoded in tiles.
+- **Where it applies**: on this kind of GPU only (identical cards share it), and only while the software that affects memory stays the same: the operating system, the PyTorch and GPU runtime versions, the memory-related environment variables and Invoke's memory settings. After such a change Invoke goes back to the built-in values until you calibrate again. A driver update keeps the measurements but marks them as possibly out of date until you calibrate again.
+- **Stopping it**: stopping a calibration started from the Model Manager, or clearing the queue while it runs, discards everything that calibration measured, the sizes that already finished included; the Model Manager shows those sizes as not counted because the calibration was stopped. Calibrate again to measure them. If a size fails for another reason, for example because the GPU runs out of memory at the largest size, the sizes that finished still count. A calibration run sent through the API without an `attempt_id` counts on its own instead: stopped, it keeps the sizes it measured. If they should not count, remove the run through the API (`DELETE /api/v2/models/working_memory/runs/{run_id}`), or reset the model's calibration in the Model Manager.
+- **What it does not cover**: image-to-image and inpainting encodes keep the built-in values.
+- **Reset**: remove a model's calibration from the Model Manager, or every calibration of this GPU; the change applies right away. Resetting one model removes only its own measurements: where other models' measurements cover the same decode, those still apply, and the Model Manager shows which models measured it. Otherwise the built-in values apply again.
+
+The measurements are stored next to the database in `working_memory/<device class id>.json`.
+
### Keeping a RAM weight copy
Invoke has the option of keeping a RAM copy of all model weights, even when they are loaded onto the GPU. This optimization is _on_ by default, and enables faster model switching and LoRA patching. Disabling this feature will reduce the average RAM load while running Invoke (peak RAM likely won't change), at the cost of slower model switching and LoRA patching. If you have limited RAM, you can disable this optimization:
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index 6bb76f6028..23cf30de8f 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -1060,16 +1060,17 @@ To write such an estimator (`invokeai/backend/util/vae_working_memory.py` has fi
- Record the dtype the operation will run in, not the one the cached model holds. The SD1/SDXL nodes cast the shared VAE with `sd_vae_run_dtype`: fp16 for every GPU run that does not ask for fp32 (bf16 never runs), fp32 when asked and for a CPU decode. Their estimate prices the same function's answer, plus what the in-place cast adds to the resident weights. Uncast VAEs compute in their first floating-point parameter wider than a byte, so fp8 or packed SDNQ storage does not count.
- Bump `version` whenever `terms` changes the formula.
- Key the spec by the platform traits its fitted terms depend on (`platform_keys`; the VAE estimators use `conv_backend` and `allocator`), and ship one coefficient entry per measured platform in `invokeai/backend/working_memory/data/`, either with its own `values` or with `values_from` another estimator's entry, which may carry more values than the borrower reads.
- - A platform is the convolution backend (`cudnn`, `miopen`, `mps`, `xpu`, `cpu`), torch's caching allocator and the OS. The allocator is torch's backend first (`cudaMallocAsync` ignores expandable segments), then `expandable` if the allocator environment variables enable expandable segments on the native allocator, else `native`; anything but a CUDA/HIP GPU is `native`.
+ - A platform is the convolution backend (`cudnn`, `miopen`, `mps`, `xpu`, `cpu`), torch's caching allocator and the OS. The allocator is torch's backend first (`cudaMallocAsync` ignores expandable segments), then `expandable` if the allocator environment variables enable expandable segments on the native allocator, else `native`; anything but a CUDA/HIP GPU is `native`. `platform_for(device)` reads them from this process; `platform_for_environment(backend, hard)` reads the same facts from a measurement's recorded environment, through the same function.
- `MEASURED` in `working_memory/platform.py` lists the measured backend, allocator and OS combinations (an OS of `None` for every OS). `priced_as` prices every other pair as one of them, keeping the OS: a backend nothing is measured on as cuDNN with the native allocator, an allocator not measured with its backend as that backend's native allocator. There the entry that carries the values raises them to its `unmeasured_floor`, the pre-dtype slopes.
- An entry applies to the OS only when its platform names one, and then takes precedence there over the one that does not. Only MIOpen names one. With the native allocator, Windows demand is concave and up to 1.6x Linux's, so Windows has its own fit and every other OS keeps the Linux one. Expandable segments are measured on Windows only, where they are Invoke's ROCm default, so `MEASURED` lists them for Windows and every other OS prices them as the native allocator there. cuDNN is priced the same on every OS.
- A spec whose fitted terms no platform trait moves declares `platform_keys=()` and ships one entry with an empty `platform`, read alike on every platform, measured or not, never priced as another or floored; its estimate's `source` names it `any platform`, and its points name no platform. MOSS-Image's denoise estimator does this: its fitted term is GEMM and fused-attention activations, not convolution workspaces, and a backend without a fused SDPA kernel is priced by the analytic score-matrix term.
-- Ship the measured points next to them, each with its `method`, a peak over the value just before the operation: `reserved_peak` (the allocator's reserved bytes), `driver_peak` (the driver-level device usage), or `demand_peak` (the largest of driver-level, reserved and allocated peak, over two runs, which catches the memory HIP maps beyond the allocator on a process's first operation), each one fresh process per point, or `device_peak` (the drop in the driver's free memory, `torch.cuda.mem_get_info` polled during the operation, which also counts what is allocated around the allocator's reserve). A point names the OS only where it measured an OS-specific entry. `tests/backend/working_memory/` holds each estimate to at least its point, and where a fitted term decides an in-fit point, to at most 1.3 times the point, or the point's tighter `max_ratio`. Points no line can hold within 1.3x are listed with their own ratio in the test's `UPPER_BOUND_EXCEPTIONS`. The `device_working_mem_gb` floor counts only where an analytic term decides.
+- Ship the measured points next to them. A point's `method` says how it was read: one fresh process per point for `reserved_peak` (the allocator's peak reserved bytes), `driver_peak` (the driver-level device usage), and `demand_peak` (the largest of driver-level, reserved and allocated peak, over two runs, which catches the memory HIP maps beyond the allocator on a process's first operation); `device_peak`, the drop in the driver's free memory (`torch.cuda.mem_get_info`, polled during the operation) below its value just before it, which also counts what is allocated around the allocator's reserve; or `probe_demand`, the probe's `demand_bytes`, the largest over the valid, fit-eligible windows of calibration runs in a running server. `scripts/working_memory/build_shipped.py` builds `probe_demand` points from calibration store exports and refits the values (see the Family E2E guide). A point names the OS only where it measured an OS-specific entry. `working_memory/bounds.py` holds the rule the data test (`tests/backend/working_memory/`) and the builder apply: each estimate is at least its point, and where a fitted term decides an in-fit point, at most 1.3 times the point, its ratio in `bounds.UPPER_BOUND_EXCEPTIONS` (points no line can hold within 1.3x), or the point's tighter `max_ratio`. A `probe_demand` point is a lower bound only (`MeasuredPoint.holds_upper_bound`) and takes no `max_ratio`: a warm window in a running server reads below the cold first run after a server start, the worst case a reservation must cover. It may raise a line; only the fresh-process points cap one. The `device_working_mem_gb` floor counts only where an analytic term decides.
- Fit the pixel-line values, never hand-tune them. The AutoencoderKL estimators price their convolutions as a line per operation and dtype: `k_<operation>_<dtype>` bytes per output pixel plus a base of `b_<operation>_<dtype>` bytes.
- - `working_memory/fit.py` fits each line on the untiled single-sample in-fit points of every estimator that resolves to the entry. The line is the edge of the points' upper convex hull (with the origin, so the base is never negative) that over-reserves its worst point least, the steeper on a tie and never a falling one. It needs at least two sizes twice apart in pixels. The shipped values add a 5% margin and round up: the slope to a whole byte per pixel, the base to a whole MiB.
+ - `working_memory/fit.py` fits each line on the untiled single-sample in-fit points of every estimator that resolves to the entry, leaving out points whose VAE an in-place cast grew (`upcast_weight_bytes`, a term of its own). The line is the edge of the points' upper convex hull (with the origin, so the base is never negative) that over-reserves least, rated on the highest reading per size of the points that hold an upper bound, the steeper on a tie and never a falling one. A `probe_demand` point is covered by the line and can raise it, but rates no edge. It needs at least two sizes twice apart in pixels. The shipped values add a 5% margin and round up: the slope to a whole byte per pixel, the base to a whole MiB.
- A point measured in a regime its platform does not run sets `in_fit: false`: it fits nothing and gets only the lower bound (CUDA with the math attention kernel forced). The test lists every such point.
- - A line no in-fit point measures is a declared stand-in, listed in the entry's `stand_ins` and never below the pre-dtype slope. MIOpen with the native allocator off Windows prices fp16 and fp32 at the pre-dtype figure, and CogView4's lines there at its expandable-segments ones.
- - Every value an entry carries is a stand-in or decided by an in-fit point. The data test fails when a fitted value is not the fit of its points, naming the value to ship, and when an in-fit point measures a stand-in's line.
+ - A line is fitted only once its in-fit fresh-process points alone span two sizes twice apart (`fit.capping_spans`); `fitted_values` refuses any other line. The shipped pair is the larger, per coefficient, of the fit on all the line's points and the fit on its fresh-process points alone, so a `probe_demand` point that drops a fresh hull vertex lowers neither the slope nor the base.
+ - Until then the line is a declared stand-in, listed in the entry's `stand_ins` and never below the pre-dtype slope. `probe_demand` points on it bound it from below only: `build_shipped.py` raises its slope and base to their fit where that lies above, and notes the raise in the provenance, but never lowers it. MIOpen with the native allocator off Windows prices fp16 and fp32 at the pre-dtype figure, and CogView4's lines there at its expandable-segments ones.
+ - Every value an entry carries is a stand-in or decided by an in-fit point. The data test fails when a fitted value is not the fit of its points, naming the value to ship, and when in-fit fresh-process points that span a fit measure a stand-in's line.
- A value on no pixel line is hand-set, and only a spec keyed by no platform trait may carry one (`hand_set_values` in `fit.py`): its points decide and bound it, but nothing fits it. MOSS-Image's `k_token`, bytes per attended token with no base, is one. A keyed spec's value off a line counts as unfitted and fails the data test.
#### Measuring estimates: the probe
@@ -1088,21 +1089,25 @@ Inside a scope, every `model_on_device(working_memory=...)` on a GPU is a window
#### Calibration runs
-A calibration run measures one model's operations on this machine's GPU. Runs only record; no estimate reads them yet. The service is `invokeai/app/services/working_memory_calibration/`, the routes are in `invokeai/app/api/routers/working_memory.py`, and every route is admin-only (403 otherwise).
+A calibration run measures one model's operations on this machine's GPU; estimates read the result as user fits (below). The service is `invokeai/app/services/working_memory_calibration/`, the routes are in `invokeai/app/api/routers/working_memory.py`, and every route is admin-only (403 otherwise).
-1. `POST /api/v2/models/i/{key}/working_memory/calibrate` takes a client-built graph, batch data and an optional `idempotency_key`. The server turns off `use_cache` on every node, sets `runs=1`, sets the graph's id to the run id, and sets the origin to `invokeai:wm-calibration:<run_id>` and the destination to `invokeai:wm-calibration`. It records the run, enqueues the batch as the requesting admin, then records the run's items.
+1. `POST /api/v2/models/i/{key}/working_memory/calibrate` takes a client-built graph, the identities of the models it names (`graph_models`), batch data, an optional `idempotency_key`, and an optional `attempt_id` with its `attempt_steps`. The server turns off `use_cache` on every node, sets `is_intermediate` on every node and clears the `board` of every `WithBoard` node (a node saves its images with its own flag and that board), sets `runs=1`, sets the graph's id to the run id, and sets the origin to `invokeai:wm-calibration:<run_id>` and the destination to `invokeai:wm-calibration`. It records the run, enqueues the batch as the requesting admin, then records the run's items.
+ - An `attempt_id` (1–64 of letters, digits, `_ - . :`) groups the runs one owner enqueues for one calibration attempt (two owners that send one id start two attempts), and `attempt_steps` (1–256) says how many runs the attempt queues. They come together or not at all (422); the server does not read a count out of the id. Both are stored on the run (and left out of the file when absent, so older readers keep reading such runs) and returned in the run summaries of the status and the model summary. Every run of an attempt sends the same `attempt_steps`: a run that sends another count than the attempt's runs already stored, or a repeat of a keyed request that changes it, is refused with 409 (checked under the store file's lock, so two such runs cannot both be recorded).
+ - One attempt runs on a device class at a time: its steps measure the GPU back to back, each on what the last one left, and another attempt's items between them would measure neither. A run of an attempt is refused with 409 and `detail` `{"code": "calibration_running", "message": "Another calibration is still running on this GPU. Wait until it has finished, or stop it, then calibrate again."}` while the queue holds an item that is pending, in progress or waiting of another attempt's run in the device class's file (`get_unfinished_origins`, read under the file's lock, which the queue takes only outside its transactions), and, with the message `Another calibration on this GPU is between its steps. Try again in a moment, or once it has finished.` under the same code, while another owner's attempt is open: between its steps, short of `attempt_steps` runs, not aborted (no other run since its first included), its model as its runs recorded it, and active within `ATTEMPT_IDLE_GRACE` (two minutes) of its newest run's creation or the latest observation of one of its items. The client posts the next step as soon as the last one finished; a step that runs long is running, and its last observation starts the wait. An attempt idle for longer is taken for abandoned: it blocks nothing, and, short of steps, never feeds. The grace is measured on the stored times against the clock now, so a jump of the wall clock lengthens or shortens it once. The owner's own open attempt blocks nothing while none of its runs is running: an open attempt is almost always one whose submission stopped partway (a full queue, a lost connection, a closed tab), and the owner's new attempt replaces it; the replaced one stays short, so aborted, and a later step of it is refused as interleaved. The attempt's own next steps pass, and so does a repeat of a keyed request that finds its run. A later step of an attempt after any other run of the device class was created since the attempt's first run, another attempt's or one without an attempt (a script's, the family E2E tool's: it measured the GPU in between too), is refused with 409 and `detail` `{"code": "calibration_interleaved", "message": "Another calibration ran on this GPU after this calibration started, so its measurements can no longer be combined. Calibrate again."}`: it would measure the GPU after that calibration, not after its own earlier steps. The attempt then stays short and is aborted; an attempt another run was created between the first and the last run of is aborted too, should a store hold one (`_interleaved_attempts`). Two clients that start attempts at once cannot both pass: every creation of an attempt's run holds one OS file lock, `<db_dir>/working_memory/creations/attempts.lock`, from finding or recording the run to recording its items, in every process serving the root, so the later creation finds the earlier one's items queued. The creation takes it before its run's creation lock (below), and it is a file of its own: on a file they shared, the second lock would wait for the first. A run without an `attempt_id` takes neither the lock nor the check.
+ - The graph names each model it loads as the client compiled it (`ModelIdentifierField`: key, hash, name, base, type), in a node's field or inside one, such as the LoRAs of a collection loader, or as a mapping of that shape in an untyped field, such as a metadata node's record of a model (`graph_model_identifiers`): in the graph's JSON a client cannot tell the two apart. The request states the identity of each of those models as the record the graph was compiled over had it, in `graph_models`: per model key its `hash`, `base`, `type`, `format` and `variant` (`CalibrationCompiledModel`), every one of them required (`format` and `variant` null when the record has none; `hash`, `base` and `type` never null). It names exactly the graph's models; a missing or extra key or an unstated fact is refused with 422. The identities come from the records the graph was compiled over, never from a read at posting time, which would carry the change the comparison has to catch. Under the run's creation locks (below), the creation reads each model's record once and compares it with the graph's identifier and with its `graph_models` entry. A model whose record differs in any of those facts, or that was removed, refuses the request with 409 and `detail` `{"code": "model_changed", "message": "<name> changed after this calibration was planned (<facts>). Calibrate again."}`, the facts among `hash`, `base`, `type`, `format` and `variant`, or with the message `<name> was removed after this calibration was planned. Calibrate again.` So a run always measures the configuration its graph was compiled for. The run records the identity of its model as that comparison read it: `model_hash`, and `model_identity` (base, type, format and variant); and that of every model the graph names, with its hash (`graph_models`), which equals what the client compiled against. A change after that is caught at admission. The run id does not derive from `graph_models`, so a keyed repeat that finds its run without items and has to enqueue its batch also compares its `graph_models` with what the run recorded (an entry the run lacks, or a recorded entry without a hash, compares only what it has); a difference is refused with the same coded 409, since the item would fail at admission on what the run recorded. A later run of an attempt is refused the same way when its model differs from what an earlier run of the attempt recorded for it, or a model its graph names differs from what an earlier run recorded for that model, the hash included (a graph compiled after a reinstall names the new hash): the attempt would measure two versions of a model, and, short of that step, it never feeds a fit. The message names the model that changed.
- The queue takes all of the batch's items or none (`enqueue_batch(..., all_or_none=True)`, checked under its admission lock): a run with only some of its cases would measure only some of them. Without room for all of them nothing is enqueued, the key stays unused, and the run is removed if this request recorded it.
- - With a key, the run id is derived from the owner, the key and the request's fingerprint: the model key, the graph without its id, and the batch data. A client that sends no graph id would otherwise get a fresh one each time and could never repeat a request. A repeated request finds its run and gets the same response; nothing new is enqueued, even after the queue collected the key's receipt. Once a reset removed the run, a repeat is refused (404) whether or not the queue still keeps the receipt: the store keeps the ids of removed runs, so the run is never started again and its queued items keep failing at admission. Another request that reuses the key (another model, graph or batch data) gets another run id and so another origin. While the key's receipt exists, that request is refused (409) and the first run stays; the receipt is checked before the request's model, so an unknown model does not turn the refusal into a 404. Once the queue has collected the acknowledged receipt, the request starts a run of its own. Acknowledge the key through `POST /api/v1/queue/{queue_id}/enqueue_batch/acknowledge`.
+ - With a key, the run id is derived from the owner, the key, the request's fingerprint (the model key, the graph without its id, and the batch data) and the `attempt_id` if given. A client that sends no graph id would otherwise get a fresh one each time and could never repeat a request. A repeated request finds its run and gets the same response; nothing new is enqueued, even after the queue collected the key's receipt. A key therefore names one run. Once a reset removed the run, a repeat is refused (404) whether or not the queue still keeps the receipt: the store keeps the ids of removed runs, so the run is never started again and its queued items keep failing at admission. Another request that reuses the key (another model, graph, batch data or `attempt_id`) gets another run id and so another origin. While the key's receipt exists, that request is refused (409) and the first run stays; the receipt is checked before the request's model, so an unknown model does not turn the refusal into a 404. Once the queue has collected the acknowledged receipt, the request starts a run of its own. Clients make each key unique per run of an attempt, for example from the attempt id and the step. Acknowledge the key through `POST /api/v1/queue/{queue_id}/enqueue_batch/acknowledge`.
- Once its items are queued, the request answers with them, also when the enqueue raised after its commit (the queue announces a batch after committing it). When the queue cannot tell whether it holds them, the run is kept and the enqueue's own error answers.
- If the store fails for a passing reason (an unwritable root, a lock timeout) to record the queued items, a request without a key still succeeds: its items run, and the status finds them by their origin. With a key that is a 503, and a repeat records them: from the key's receipt while the queue keeps it, otherwise from the queue items with the run's origin and the items the runner saw. It never enqueues a second batch for the run: the run is marked before its batch is enqueued (`enqueue_attempted`, set as the run is recorded), and only the attempt that set the mark clears it again, when its own enqueue queued nothing; a replay of the key's receipt never clears it, since the attempt that queued the batch may have queued it. A repeat that finds a marked run without items, without the receipt and with no item in the queue or seen by the runner answers with the run and no items, and the run reads as canceled. That is the case when the items were cleared or pruned before the runner saw them, when the server shut down between the mark and the enqueue, or when an enqueue raised, the queue could not be read to tell what it had queued, and it had queued nothing. Should clearing the mark fail (it is logged), the run stays marked although nothing was queued, and the key cannot start it; a request with another key can. Recording them from the receipt checks neither the model nor the device, so a model removed meanwhile does not fail the repeat; a request that has to enqueue needs the model. A run removed meanwhile (404) or an unusable store file (409) fails the request with or without a key; its queued items then fail at admission.
- - Per run id, one creation runs at a time, and it runs to its end even when its request is canceled: the enqueue runs in a worker thread and can commit after the cancellation. Only the server's shutdown cancels the creation with it; the run then stays as far as it got, and with a key a repeat of the request completes it. For a run with a retry key, "one at a time" holds across every process serving the root: the creation holds an OS file lock (the store's own lock primitive) from finding or recording the run to recording its items, so another process's repeat waits and then finds what the first attempt did. A holder that dies releases the lock with its process. A repeat waits up to 30 s (`LOCK_TIMEOUT_S`) and then answers 503, which with a key can be retried. The run ids share 256 empty lock files, `<db_dir>/working_memory/creations/<xx>.lock` by the first two hex digits of the id's SHA-256. No lock file is ever removed (removing one could let two processes each lock a file of that name), and the folder never holds more than 256. Unrelated runs on one file wait for each other, which costs little for a short administrator's action. Within one process the repeats of a run first wait on an in-process lock per run, on the event loop, so only one of them at a time takes a worker thread to wait for the file lock: a burst of repeats cannot fill the default executor. A run without a key has a fresh id that no other request names, so it takes no lock. A run is removed only when this request recorded it and nothing of it was queued.
- - The destination only stops clients from routing the results to a gallery or canvas view. Images the graph's nodes save are stored like those of any other session: on the board and with the intermediate flag each node sets.
+ - Per run id, one creation runs at a time, and it runs to its end even when its request is canceled: the enqueue runs in a worker thread and can commit after the cancellation. Only the server's shutdown cancels the creation with it; the run then stays as far as it got, and with a key a repeat of the request completes it. For a run with a retry key, "one at a time" holds across every process serving the root: the creation holds an OS file lock (the store's own lock primitive) from finding or recording the run to recording its items, so another process's repeat waits and then finds what the first attempt did. A holder that dies releases the lock with its process. A repeat waits up to 30 s (`LOCK_TIMEOUT_S`) and then answers 503, which with a key can be retried. The run ids share 256 empty lock files, `<db_dir>/working_memory/creations/<xx>.lock` by the first two hex digits of the id's SHA-256. No lock file is ever removed (removing one could let two processes each lock a file of that name), and the folder never holds more than those 256 and `attempts.lock`. Unrelated runs on one file wait for each other, which costs little for a short administrator's action. Within one process the repeats of a run first wait on an in-process lock per run, on the event loop, so only one of them at a time takes a worker thread to wait for the file lock: a burst of repeats cannot fill the default executor. A run without a key has a fresh id that no other request names, so it takes no lock. A run is removed only when this request recorded it and nothing of it was queued.
+ - All of it before the request's fingerprint is taken, so a keyed repeat stays the same request; batch data that sets `use_cache` or `is_intermediate` is refused (422); a board cannot come as batch data, whose items are strings, numbers, images and videos. The images a calibration item saves are therefore intermediates on no board, never in the gallery. They stay until Clear Intermediates removes them, which keeps them while their item runs, as it keeps every active session's. The destination stops clients from routing the results to a gallery or canvas view.
2. `enqueue_batch` refuses any origin that starts with that prefix, in any case, for every user (400). Only the calibration route creates calibration items. Retries and workflow-call children inherit origin and owner from their source item.
3. `DefaultSessionRunner.run()` checks each item's origin once. For a calibration item it calls `admit()` before any node runs, also for one left pending before a restart: the invoker starts the session processor after every other service. (The queue's start cancels the items that were in progress.) Retries and children are checked here too. Otherwise the item fails with the reason. The checks:
- the owner is an active admin (single-user mode counts as admin);
- the machine has exactly one GPU generation device;
- - the run exists for that GPU's device class.
-4. Each admitted node runs in `probe.calibration_scope(...)`, keyed by the node's source id. Its windows are persisted after the node completes, fails or is canceled. Unless the node completed, every one of them is persisted invalid (`exception` when it failed, `canceled` otherwise), including a window whose own operation finished before the node raised: `run_node` swallows the failure or cancellation, so the runner takes the outcome from its node hooks. Windows from a device of another class, or of a run that was removed, are dropped with a warning. So are windows of a model reset after the node started, also by another process sharing the root: the runner reads the device class's reset epochs before the node's scope opens, and the write drops the points of every model whose epoch has moved since. Without that, a reset while the node runs (of a VAE inside a transformer's run, say) would be undone by the node's later write. If they cannot be saved, the item fails and the session stops. Every other item gets no scope and runs as before.
+ - the run exists for that GPU's device class;
+ - the item measures the models the run was planned with: its model's record still has the `model_hash` and the `model_identity` the run recorded (a run stored without the identity compares the hash alone), and every model the graph names still has the hash, base and type it names, and the hash, base, type, format and variant `graph_models` recorded for it (an entry stored without a hash compares the rest). Otherwise the item fails with `Model <key> was removed after this calibration was planned. Calibrate again.` or `<name> changed after this calibration was planned (<facts>). Calibrate again.`, and the run's item records `error_code: model_changed`, which the run's `error_code` in the status and the model summary carries beside the message in `error`.
+4. Each admitted node runs in `probe.calibration_scope(...)`, keyed by the node's source id. Its windows are persisted after the node completes, fails or is canceled. Unless the node completed, every one of them is persisted invalid (`exception` when it failed, `canceled` otherwise), including a window whose own operation finished before the node raised: `run_node` swallows the failure or cancellation, so the runner takes the outcome from its node hooks. Windows from a device of another class, or of a run that was removed, are dropped with a warning. So are windows of a model reset after the node started, also by another process sharing the root: the runner reads the device class's reset epochs before the node's scope opens, and the write drops every point attributed to a model whose epoch has moved since, as the reset attributes them (`measured_models`: a submodel's `<key>:vae` window counts for its model). Without that, a reset while the node runs (of a VAE inside a transformer's run, say) would be undone by the node's later write. If they cannot be saved, the item fails and the session stops. Every other item gets no scope and runs as before.
5. After the item, the runner records the item's outcome in the run, even when the session raised. A queue row that still exists has the last word, failed or canceled included. When the row is gone, the runner's view of how the queue left the item after the session decides:
- The queue completed or failed the item, and a prune or a clear removed it afterwards: the item keeps that outcome, a failure with its error.
- Clear Queue removed the item before the queue settled it: the item is recorded as canceled. (A prune cannot do that: it removes finished items only.)
@@ -1113,10 +1118,11 @@ A calibration run measures one model's operations on this machine's GPU. Runs on
The store has one JSON file per device class at `<db_dir>/working_memory/<device_class_id>.json` (`CalibrationStoreFile`, `schema_version` 1). It is machine data, so it lives next to the database rather than inside it. It holds:
- the device class, with its id;
-- the runs: model key, model hash as provenance, owner, environment, queue items, whether an enqueue of the run's batch may have committed, and the last status the runner saw for each item;
+- the runs: model key, the model's hash and identity at creation (`model_hash`, `model_identity`), owner, environment and its soft facts at creation, queue items, whether an enqueue of the run's batch may have committed (`enqueue_attempted`), and for each item the last status the runner saw, why admission failed it (`error_code`), and every retry of an item, recorded pending as the queue commits it until the runner sees it; how many of the queue's retry operations that retry items of the run are in flight, however many items each retries (`retries_in_flight`); the models the graph names as they were then (`graph_models`); the soft facts, the `model_identity`, the `graph_models`, the `retries_in_flight`, the `error_code`, the `attempt_id` and the `attempt_steps` are left out when absent (or 0), so runs stored without them still load and older readers still read runs that lack them;
- the points: `MeasuredWindow` plus `env_id`;
- the environments those reference;
- the ids of the runs with a retry key that a reset removed (`removed_run_ids`), so that a repeat of the request that started one cannot start it again. They are kept for good, about 40 bytes per removed run. A run without a key gets a fresh id and is never repeated, so its id is not kept;
+- per attempt, an owner's (`user_id`) `attempt_id`, what resets removed of it (`removed_attempt_steps`, a list of such records): how many of its runs (`removed`), the `attempt_steps` they sent, and whether the attempt was running or already stopped when a reset removed one (`aborted`), judged then from the queue. A removed run counts as queued, so the runs left are judged on every run the attempt queued; a later run of the attempt must send the same `attempt_steps`. A record is dropped at a reset once no stored run of its attempt is left, unless that reset found the attempt running, since a later step of it may still come. The key is left out of a file without any record, so readers that predate it still read such files. Development builds stored the records by attempt id alone; such a record reads as the record of each owner whose stored runs carry the id, and one no stored run carries is dropped;
- per model key, its reset epoch (`model_reset_epochs`): how often the model was reset. The reset raises it in the same file change, so it is only written when the reset is.
A file without either of these two fields reads them as empty.
@@ -1133,21 +1139,37 @@ A file is unusable when it has another schema version, invalid content, an id th
A run's status is derived, never stored:
- The live queue items with the run's origin come first. For items the queue has pruned, the runner's recorded statuses are used. An item the queue no longer has and that the runner never saw finish (the process died mid-item) counts as canceled.
-- A retry replaces the item it retried. The queue's own record of the retry links them while it has the retry, also before the runner started it; afterwards, what the runner saw does. A retry the runner never started and the queue no longer has leaves no trace: the run then reads as the outcome of the item it retried, failed for instance. The run's items include each item a known retry came from, even when nothing else knows that item any more.
-- The run is `running` while any item is pending or running, `failed` when any failed, and `completed` when all completed. Otherwise it is `partial` if valid points were recorded, or `canceled` if not: an invalid point measured nothing usable.
+- A retry replaces the item it retried. The queue's own record of the retry links them while it has the retry; the store records it too, with the retry's commit: the announcement after it (`QueueItemsRetriedEvent`) cannot promise a record, since the server may stop before it is handled. `SessionQueue.retry_items_by_id` calls the calibration service before it commits retries (`retries_starting`), which counts the retry operation in flight on each run of a calibration item among the sources (`retries_in_flight`, under the store file's lock, one per operation however many of the run's items it retries), and again once the commit is done (`retries_committed`), which records each retry on its run, pending and standing for the item its lineage started from (the queue's `retried_from_item_id`), and counts down. A full queue, or a failure before the queue's insertions ended, which rolls them back, counts down without recording anything. A failure once they ended can be the commit's own, which may have committed all the same (a lost connection to MySQL or MariaDB): which retries exist is unknown, so the count stays, and is logged. The count-down is tried once more after a lock timeout. The queue holds no transaction while it waits for the file's lock. A retry inherits its source's origin, which names the run: a recreated database that gave a recorded id to an unrelated item cannot make that item's retry the run's, and a bulk retry of generations touches no store file. A store that cannot count the retries refuses them: the queue retries nothing, also the request's items that are no calibration's, and the retry route answers 503. A count left over, because the server stopped, the commit failed that way, or the store could not be written between the count and the record (which is logged), means a retry may exist that the store does not know: the run's attempt never feeds a fit, also after a restart, until a reset removes the run. So a retry canceled and pruned before the runner started it reads as canceled, also after a restart, and a retry the runner admitted before the record keeps what the runner saw. The run's items include each item a known retry came from, even when nothing else knows that item any more.
+- The run is `running` while any item is pending or running, `failed` when any failed (with the first failed item's message as `error` and, when admission failed it, its `error_code`), and `completed` when all completed. Otherwise it is `partial` if valid points were recorded, or `canceled` if not: an invalid point measured nothing usable.
Routes, besides the 403 for non-admins and a 503 when the store cannot be read or written (an unwritable root, a lock timeout):
| Route | Does | Other errors |
| --- | --- | --- |
-| `POST .../i/{key}/working_memory/calibrate` | starts a run (above) | 404 unknown model, the run was removed while it was being created, or a reset removed the run the retry key started; 409 no GPU or several generation devices, unusable store file, no room in the queue for all of the run's items (nothing is enqueued; the run is removed if this request recorded it), or a retry key used for another request; the 404 and 409 for the run's store, and with a key the 503, can come after the items were queued (above); 422 a `call_saved_workflow` node, batch data setting `use_cache`, an invalid batch, or fields the server sets; 429 too many unacknowledged retry keys |
-| `GET .../working_memory/status` | every device class with its runs, point counts per estimator, version, validity and fit eligibility, and environments with hard and soft facts compared to the current environment; `available` says whether a run can start now: one GPU generation device, and a usable store file that can be written. The check stages a temporary file in the store's folder (or the nearest folder above it that exists) and removes it at once, checks that the lock file is writable, and on Windows that the store file is not read-only. | 503 when the store folder cannot be listed |
-| `DELETE .../working_memory/runs/{run_id}` | removes a run and its points; its items that have not started yet fail at admission, also after a repeat of the request that started it | 404 no usable file holds the run |
-| `DELETE .../i/{key}/working_memory` | removes the model's runs with all their points, and every point of the model taken in other runs (a VAE measured inside a transformer's run, say). A submodel's window carries the model cache's key for it, `<key>:<submodel>` (`<key>:vae`), and counts for its model; the reset fence uses the same attribution | 409 no current device class, or an unusable file |
-| `DELETE .../working_memory` | removes every run, point and environment of a device class | 409 as above |
+| `POST .../i/{key}/working_memory/calibrate` | starts a run (above) | 404 unknown model, the run was removed while it was being created, or a reset removed the run the retry key started; 409 no GPU or several generation devices, unusable store file, no room in the queue for all of the run's items (nothing is enqueued; the run is removed if this request recorded it), a retry key used for another request, a run of another attempt still running on the device class (`calibration_running`), or a model the graph names that changed or was removed since the client compiled the graph, or that a repeat of a keyed request states otherwise than the run it names recorded (`model_changed`), these two with `detail` `{code, message}` (above); the 404 and 409 for the run's store, and with a key the 503, can come after the items were queued (above); 422 a `call_saved_workflow` node, batch data setting `use_cache` or `is_intermediate`, an invalid batch, fields the server sets, or `graph_models` that does not name exactly the graph's models, every fact of each (`hash`, `base` and `type` never null); 429 too many unacknowledged retry keys |
+| `GET .../working_memory/status` | every device class with its runs, point counts per estimator, version, validity and fit eligibility, and environments with hard and soft facts compared to the current environment (`soft_matches_current` compares the soft facts first recorded with the environment, not a later run's); `available` says whether a run can start now: one GPU generation device, and a usable store file that can be written. The check stages a temporary file in the store's folder (or the nearest folder above it that exists) and removes it at once, checks that the lock file is writable, and on Windows that the store file is not read-only. Per device class with a generation device here, `measurement_method` (the driver reader its windows use, `counters.driver_method`) and `measurement_verified` (`counters.VERIFIED_METHODS`), null for other classes | 503 when the store folder cannot be listed |
+| `DELETE .../working_memory/runs/{run_id}` | removes a run and its points; its items that have not started yet fail at admission, also after a repeat of the request that started it. A run of an attempt is counted in its owner's attempt's `removed_attempt_steps` record, so the runs left are judged as part of the whole attempt; a reset while the attempt runs, or of a run that ended canceled, marks the attempt stopped. The reset judges that from the queue inside the change that removes the run, under the store file's lock, so a retry queued just before it is seen | 404 no usable file holds the run |
+| `DELETE .../i/{key}/working_memory` | removes the points the summary attributes to the model (`measured_models`): its runs with all their points, and every point of the model or one of its submodels taken in other runs (a VAE measured inside a transformer's run, say); other models' points on the same lines stay. The removed runs of attempts are counted as for a single run. A submodel's window carries the model cache's key for it, `<key>:<submodel>` (`<key>:vae`), and counts for its model; the reset fence uses the same attribution | 409 no current device class, or an unusable file |
+| `DELETE .../working_memory` | removes every run, point and environment of a device class; it keeps only the `removed_attempt_steps` records of attempts that were running, which a later step of them still meets | 409 as above |
| `GET .../working_memory/export` | the file byte for byte: a `CalibrationStoreFile` when this version can read it, otherwise whatever the file holds | 404 no file; 409 no current device class |
+| `GET .../i/{key}/working_memory/plan` | the cases that calibrate the model here (`WorkingMemoryCalibrationPlan`, below), or `supported: false` with the reason | 404 unknown model |
+| `GET .../i/{key}/working_memory/summary` | per line and environment: the lines the model's windows measured, and in the current environment each line the model's decode prices on (its plan's estimator and dtypes) that other models' windows measured. Per line, every window that feeds it (all models' counted windows of that environment that join the same user line): sizes, largest demand, shipped and user estimate; a size whose valid windows all are excluded is listed too, with `counted: false` and `excluded_reason` (`fragmented`, `partial_residency`, or `aborted_attempt` when all its windows come from stopped attempts), its largest such window and the user estimate there; the user line's measured range and state (`in_use`, `stale`, `unusable`, `insufficient`); `own_windows`, the model's share (0 for a line only others measured); `measured_by`, each contributing model with its name (null once uninstalled) and window count. Also the model's windows that fit no line, and its runs, each with `attempt_steps` and `held_back` (`running`, `aborted_attempt`, or null) | 404 unknown model; 409 no current device class |
-The last three act on the current device class unless `device_class_id` is given.
+The reset, export and summary routes act on the current device class unless `device_class_id` is given.
+
+#### User fits
+
+`backend/working_memory/user_fit.py` owns the rule; the calibration service owns the store and the cache.
+
+- A user line is fitted per line of `fit.py`: the shipped entry that carries the values (one hop of `values_from`) and `<operation>_<dtype>`. A window joins where `fit.fits_a_line` admits it (untiled, one sample, no in-place upcast, an AutoencoderKL: the SD estimator's AutoencoderTiny windows join no line), it is valid and fit-eligible, it is not fragmented, its demand is positive, and its estimator version has shipped values on the platform. Every user point is a `probe_demand` window, so all of them rate the hull's edges. `fit.user_pair` adds `USER_MARGIN`, the shipped 5%, to the envelope and rounds up as the shipped values do. A line needs two sizes `MIN_AREA_RATIO` apart.
+- Fragmented windows measured the allocator's history, not the operation. One rule, `fragmentation.fragmented`, judges them for the user fit and for `scripts/working_memory/build_shipped.py`, which flags shipped points by it. It judges a measurement: the fit-eligible windows of one attempt (an owner's `attempt_id`, so two owners' attempts with one id are two measurements; else the run; for the builder also one server lifetime) at one environment, estimator, version and features, in the order they ran. A measurement drops out whole when reserved grew by 10% from its first window to its largest while allocated stayed within 2%, or when its largest window's reserved-to-allocated ratio is 1.2 times the median of the same line's smaller measurements that count, from any attempt. Each attempt is judged on its own, because its windows ran back to back on one allocator state: a recalibration can bring back a size an earlier attempt measured fragmented, and a later fragmented attempt drops no clean one. The ratio rule catches a size whose windows all ran fragmented, or that kept only one fit-eligible window: on an RX 9060 XT the fp32 SDXL decode at 1216 px measured 1.47 against 1.10 at 576 and 832 px, with one fully resident window beside two partly resident ones. Windows of a running attempt are judged but set no reference, as they join no user line yet. Partly resident windows (`partial_residency`) never count and enter neither rule. A size counts when any attempt's windows at it count, and its `windows` and `measured_bytes` cover those windows only.
+- The windows are those of the current device class's file taken under an environment whose hard facts equal the current ones (same `env_id`). A soft-fact difference keeps the fit. The summary reports a line as `stale`, with the facts that changed, when the soft facts of the newest finished run that fed it differ from the current ones; a run stored without soft facts stands for the environment's, those first recorded with it. So recalibrating after a driver update clears `stale`. Older windows of the same hard environment keep feeding the line: the hard facts are what decide whether a window still measures this machine. A hard mismatch leaves the shipped values.
+- `EstimatorSpec.estimate` asks the registered provider (`user_fit.set_user_fit_provider`; the service registers it in `start()` and clears it in `stop()`) for the user fit of the spec, platform and device. Without one, the estimate is the shipped one, bit for bit. With one, `user_fit.resolve` reads the operation's line and output pixels as `fit.line_of` does. At or below the largest measured size the user line replaces the shipped one; above it, the larger of the two estimates wins. A tiled operation is placed by its image, priced on its tile. The `source` starts with `user:<device class id>:<env id>` and names the line where the user line decides. A line the user did not measure stays shipped. Because estimates feed `reservation_bytes`, a user line also moves `should_pretile_vae_decode`.
+- Only finished runs and attempts feed a fit. The windows of a run the queue holds an item of that is pending, in progress or waiting join no user line, whoever refreshes the fits meanwhile. The queue tells by the run's origin, which an item carries from the moment it is queued, before the run records it or the runner admits it; a retry carries it too, so a run that failed holds its windows back again while its retry waits, and releases them once the retry finished or was canceled or removed. Nor do the windows of any run of the same attempt, the same owner's `attempt_id`: the client posts each step of an attempt as its own run, so an attempt's windows feed no fit while any of its runs is in the queue (`held_back: running`), and its later, larger cases are priced without its own earlier windows. Once none is, an attempt feeds a fit only if it is complete and was not stopped (`aborted_attempt`); its windows join at the first refresh after that, whether its runs completed or failed. Complete means it queued `attempt_steps` runs, those a reset removed since included (`removed_attempt_steps`), so removing a run of a finished attempt discards only that run's windows. A reset while the attempt runs, or after it was stopped, stops it for good: its earlier steps are gone, so it cannot measure every size it planned. The UI disables Reset while a calibration runs, so only API clients do that. Stopped also means an item of it interrupted it, judged per item: the item that stands for a lineage, its latest retry or itself, was canceled (Stop cancels what the queue still holds), is gone from the queue before the runner saw it finish (a queue clear), or failed at admission because a model changed after the calibration was planned (`error_code: model_changed`: its later steps would measure another model). So does another run created between its first and its last run. The items are those the store records: the run's batch and every retry, recorded as the queue commits it or by the runner, so a retry canceled and pruned before anything refreshed, a restart included, still stops its attempt; and an attempt one of whose runs has retries in flight left over (`retries_in_flight`) is stopped too, since a retry of it may exist that the store does not record. Any other failed item, such as an out-of-memory error at the largest size, ends that step and not the attempt, also beside a canceled one in a run whose batch data made several items, whose displayed status is then `failed`; a canceled item whose retry completed or failed no longer aborts it, and a retry canceled while it waited does. A run with no item at all, whose items were never recorded nor found by its origin, stops it as well. An attempt with fewer runs and none running is stopped too: Stop, or a submission that failed, ended it before it queued them all (a step not posted yet looks the same until it is). A stopped attempt measured only some of its sizes and never feeds a fit, also when those span enough sizes for a line: its runs read `held_back: aborted_attempt`, its windows are excluded with `excluded_reason: aborted_attempt`, and a line only it measured is `insufficient`, with a `problem` that says a stopped or interrupted calibration measured it. A run without an `attempt_id` is judged on its own and is never stopped this way: canceled, it feeds what it measured; another attempt that finished counts as usual. Runs stored with an `attempt_id` but no `attempt_steps` come only from development builds of the calibration; their attempt is judged on the runs it recorded, as before, rather than making the store file unusable. The summary shows a running run's windows in the sizes, window counts and `measured_by`, while its user line, range, user estimates and state are those of the fit estimates read; a line only a running run measured is `insufficient` and says so.
+- The provider answers from memory. `refresh_user_fits()` rebuilds that memory per GPU generation device. `DefaultSessionRunner.run()` calls it once when it starts any queue item, calibration items included; `get_plan` calls it first, so the case sizes price with the store as it is, and every reset calls it after its write, so a reset applies at once. It stats each device class's file and re-reads it only when the mtime, size or inode or the environment changed. Each refresh of a file with runs, and each model summary, reads the queue to judge the attempts. To tell which runs are running it reads the origins of the queue's unfinished calibration items (`get_unfinished_origins`): the queue finds those items by their status and tests the origin on their rows, so the read costs what the queue has pending or running, not its history; on SQLite about 0.05 ms beside a handful of unfinished items, whatever the history, and 3 ms beside 100 (34 ms beside 1000) pending items of 64 KB sessions, whose overflow pages the origin sits behind. Grouping the runs into attempts costs about 0.5 ms at 180 runs and 11 ms at 3600. To tell whether a settled attempt was stopped it reads by id (`get_queue_item_summaries_by_ids`, the primary key) the items the store records whose end the runner did not see. A finished item never changes, so its outcome is kept, per run and item id (a recreated or restored database can give two runs' items one id), until its run is removed, by a reset or by a creation that queued nothing, and each item is read once it finished; a run with an item the queue shows pending or in progress, a retry queued since the read for running items, holds its attempt back as running for that refresh. Every judgement of these outcomes (a refresh, the model summary, a new attempt's check, a reset), with its read of the store file, and every removal holds one lock of the service, taken before the file's lock, so a removal's runs leave no outcome behind. A row counts only while it carries the run's origin: a recreated or restored database gives the id to an unrelated item, and the run's own item is gone, so it reads as canceled. An unchanged file with an unchanged set of runs held back is not fitted again. A calibration item, a retry included, is in progress when the runner refreshes before it, so it is priced without its own attempt's windows. Nothing on the estimate path reads a file. Several generation devices each use their own class's fit; calibrating them is not supported.
+- Shared lines: on cuDNN the SD, SD3, FLUX.1 and FLUX.2 estimators borrow one entry, so an SDXL fp16 decode calibrates every estimator's fp16 decode there. The plan lists the installed models this affects.
+
+The plan (`working_memory_calibration_plan.py`) covers the decode of SD1, SD2, SDXL, SD3, FLUX.1, FLUX.2, Z-Image and CogView4 main models, and standalone VAEs of those bases through an installed main model that accepts them (`VaeFacet`): through Generate's `vae` slot where the base has one (FLUX.1, FLUX.2, SD3, Z-Image), otherwise with the VAE the main model decodes with, its own or the default VAE its settings name, which prices on the same lines. Each case is a two-step `txt2img` graph-export case per size and decode dtype; the SD bases set `vaePrecision` to fp16 and to fp32, the others run the dtype their loader picks: SD3 the `precision` setting; a standalone FLUX.1 or FLUX.2 VAE, and the one Z-Image decodes with, the configured dtype except fp16, which becomes bf16 where the device has it and fp32 otherwise (`TorchDevice.dtype_avoiding_float16`, which the loaders use too), so `precision: float32` plans the fp32 line at the smaller sizes an fp32 decode fits untiled; a pipeline's own VAE what its loader yields: bf16 for a FLUX.2 Diffusers pipeline, the device's bf16-safe dtype for a Z-Image one, and fp32 for a self-contained SDNQ pipeline, whose loaders call `from_pretrained` without a dtype (bf16 for a FLUX.1 SDNQ pipeline's SDNQ-quantized VAE); `test_working_memory_calibration_plan.py` holds these to the loaders. A pipeline decodes with its own VAE while the `vae` slot is empty: a FLUX.2 or Z-Image Diffusers pipeline, and a self-contained SDNQ pipeline (`is_self_contained_sdnq_pipeline`, for FLUX.1 `is_self_contained_sdnq_flux1_pipeline`). The slot is not empty when the main model's default settings name an installed VAE it accepts (`default_vae`): selecting the model applies it (`getModelDefaultVae`), the SD, SD3, FLUX.1, FLUX.2 and Z-Image graphs decode with it, and the FLUX.2 and Z-Image model loader nodes take it over a pipeline's own VAE, so the plan sizes for that standalone VAE; the graph of a self-contained FLUX.1 SDNQ pipeline, and the CogView4 graph, send no VAE. Another FLUX.2 model decodes with the VAE of the component source Generate picks on its own, the first installed FLUX.2 pipeline whose text encoder fits it ([dev] for [dev], else the Klein variant's Qwen3 size), else the first one; that graph keeps a pipeline that does not fit only beside a standalone encoder of the model's (a Mistral encoder for [dev], else a Qwen3 encoder of the Klein variant's size), which then encodes while the pipeline gives its VAE. Without a pipeline, and for every other FLUX.1 model, a standalone VAE decodes. The sizes are about 0.25, 0.5 and 1.0 of the largest square, in steps of 64 and at most 4096 px, whose calibration reservation (the estimate plus `max(1 GiB, 0.5 × estimate)`, and never below `device_working_mem_gb`, as the lock applies it) leaves the VAE fully resident (`decode_budget`): it must fit both 90% of the card (`VAE_PRETILE_VRAM_FRACTION`) and what the model cache can give on the device, each less 1 GiB for the VAE's weights. Nothing else stays beside it: inside a calibration scope, `model_on_device` first moves every other unlocked model on the device to RAM whole (`ModelCache.offload_unlocked_models_from_vram`, under the global load lock, inside the probe's lock interval; locked models, a window's co-locks among them, stay), and only then locks. The reason: a lock offloads only the shortfall it predicts and splits the last model it reaches, and a split can free a little less than predicted. On an RX 9060 XT, 9 of the 12 calibration decodes that had to split the SDXL UNet came up 35 to 55 MB short and ran the VAE partly resident, so their windows fit no line. Outside a calibration scope, locks are unchanged. That capacity is read when the plan is built, from the device's model cache: `ModelCache.calibration_capacity`, what the calibration's lock then gets from the same cache. It counts as `ModelCache._get_vram_available` counts a lock, through the same `TorchDevice.memory_available_to_process`, within `max_cache_vram_gb`, less `reserve_vram_gb`. On a dedicated card that is the driver's free memory plus what torch has allocated, so the models the pre-lock offload moves out count as available. On a device whose memory is system RAM (MPS, an integrated Intel GPU) it is the RAM the host has available plus what the backend holds for this process, less what the cache's models hold there now (`_get_vram_in_use`): the offload frees nothing on such a device, and the lock subtracts them too. The 90% share of its total would overstate what a decode finds there whenever the host is short of free memory. Memory other processes hold is thereby left out. What this process holds outside torch's allocator counts at the larger of what it holds now and the most a valid stored window of the current environment recorded at its baseline (the driver's figure for the process less torch's reserve, `recorded_outside_torch_bytes`), because it grows with the first generations: on a 16 GB RX 9060 XT under ROCm, HIP's retained pool and MIOpen's workspaces took about 0.3 GB in a fresh server and 2.6 GiB once it had decoded, and sized for the fresh reading its largest cases ran partly resident. A first calibration has no stored window and sizes for the reading alone, so on such a card its largest cases may run partly resident; those windows do not count, and the next plan sizes for what the first one recorded. The recorded figure comes from the store `refresh_user_fits` just read; `estimate_untiled_vae_decode` prices them with the decode nodes' own features. `DECODE_LINES` restates which estimator each base's decode node prices with; `test_working_memory_calibration_plan.py` holds it to the nodes in `invocations/vae/`. Each case runs once to warm up and twice more; `estimated_seconds` is a rough order of magnitude, not a measurement. Encodes are not planned: text-to-image runs none. Two settings of the machine leave nothing to measure, and the plan is then `supported: false` with the way out: under `force_tiled_decode` the SD, FLUX.1, Z-Image and FLUX.2 decode nodes tile every decode, so a case measures no untiled line and no estimate would read one (`FORCE_TILED_BASES`; the plan does not override the setting for calibration items); and a FLUX.1, FLUX.2 or Z-Image model that decodes with a standalone VAE needs a compatible one that runs on the GPU, since a decode on the CPU opens no window. A main model whose default VAE runs on the CPU gets a `vae` pick of the first accepted VAE on the GPU where its base has the slot, and is otherwise `supported: false` (the SD bases have no slot a case could pick through); a standalone SD VAE goes through a compatible main model whose default VAE does not run on the CPU. A FLUX.2 model that is no pipeline needs a text encoder Generate can use, a fitting pipeline's or a standalone one as above: without one no case compiles, and the plan is `supported: false` saying which encoder to install. A standalone FLUX.2 VAE goes through the first compatible main model that has one.
### Emitting model loading events
diff --git a/docs/src/content/docs/development/Guides/family-e2e.mdx b/docs/src/content/docs/development/Guides/family-e2e.mdx
index 0b677ff468..4d830c4e55 100644
--- a/docs/src/content/docs/development/Guides/family-e2e.mdx
+++ b/docs/src/content/docs/development/Guides/family-e2e.mdx
@@ -17,7 +17,7 @@ It is a developer tool. It runs on Windows with NVIDIA and AMD (ROCm) GPUs, wher
- The tool overrides a few settings: a free port on `127.0.0.1`, a plain-format log file in the run directory, the image index off, and the queue cleared at startup. SSL and `base_url` are dropped. On Linux the server sees only the selected GPU, as `cuda:0`, so a `device` of `cuda:N` becomes `cuda:0` and a `generation_devices` list with a CUDA device becomes `auto`.
- `INVOKEAI_*` variables of the calling environment are not passed on. Put settings the server needs into the manifest's `server.env`.
2. **Server.** The tool checks that `server.python` imports `invokeai` from `server.code_dir`. It then starts `<python> <code_dir>/scripts/invokeai-web.py --root <scratch root>` and reads the actual port from the server log. Multiuser mode is refused.
- - On Windows the server runs in a job object of the runner, so it dies with the runner however the runner ends. On Linux it runs in a session of its own. `stop`, an interrupt or a plain kill (SIGTERM) of the runner ends it; a runner killed with SIGKILL leaves it running. While it holds more than 1 GiB on that GPU, `start` and `resume` name it as foreign load and refuse; `stop RUN` ends it. Otherwise the resumed runner stops it first, before it replaces `heartbeat.json`, which names the server for `stop`, or touches the scratch root. If it cannot stop the server, the runner refuses and leaves the scratch root and the server's entries in `heartbeat.json` as they are; `runner.log` names the pid and the run shows as failed.
+ - On Windows the server runs in a job object of the runner, so it dies with the runner however the runner ends. On Linux it runs in a session of its own. `stop`, an interrupt or a plain kill (SIGTERM) of the runner ends it; a runner killed with SIGKILL leaves it running. The runner writes the launched process into `heartbeat.json` before it waits for the server to start, so `stop` and `resume` also find a server whose runner was killed during the startup. While it holds more than 1 GiB on that GPU, `start` and `resume` name it as foreign load and refuse; `stop RUN` ends it. Otherwise the resumed runner stops it first, before it replaces `heartbeat.json`, which names the server for `stop`, or touches the scratch root and a calibration store in it. If it cannot stop the server, the runner refuses and leaves the scratch root with its store and the server's entries in `heartbeat.json` as they are; `runner.log` names the pid and the run shows as failed.
3. **Graphs.** The real webv2 graph builders produce each case's batch through `pnpm graphs:export`, run in the tool checkout. Run `pnpm install` in `invokeai/frontend/webv2` there first.
- The runner disables the invocation cache on every node and saves the batch as `graphs/<case_key>.json`.
- It hashes the graph and its batch data. Uploaded image names are replaced by the input file's hash, so the graph hash changes only when the graph or an input changes.
@@ -35,7 +35,7 @@ It is a developer tool. It runs on Windows with NVIDIA and AMD (ROCm) GPUs, wher
<data_dir>/references/<profile>/<case_key>/ image.png, reference.json (written by `accept` only)
<data_dir>/runs/<run_id>/ run.json, records.jsonl, heartbeat.json, runner.log, server-default.log,
run.lock, graphs/, images/, traces/<record_id>.csv.gz, report.html, summary.md,
- <run_id>.zip (written by `bundle` only)
+ calibration/ (calibration runs only), <run_id>.zip (written by `bundle` only)
<data_dir>/scratch-roots/<run_id>-default/
```
@@ -69,10 +69,10 @@ Run the tool from the repository root with the checkout's environment, for examp
| Command | What it does |
| --- | --- |
-| `start --manifest M [--family F]… [--case ID]…` | Checks the GPU lock, the template's server, unfinished model installs and foreign GPU load. It then creates the run, starts its runner in the background, waits until the runner has registered, and prints the run id, the runner's pid and paths. |
-| `status [RUN]` | Shows progress, the current step, the heartbeat age and whether the runner is alive. |
-| `stop [RUN]` | Marks the run stopped, then kills the runner and its server and removes the run's scratch roots. |
-| `resume [RUN]` | Starts the runner of a stopped or crashed run again, and waits until it has registered. Refuses while the run's runner is alive. On Linux the runner first stops a server its killed predecessor left running (see [How a run works](#how-a-run-works)). |
+| `start --manifest M [--family F]… [--case ID]… [--calibrate]` | Checks the GPU lock, the template's server, unfinished model installs and foreign GPU load. It then creates the run, starts its runner in the background, waits until the runner has registered, and prints the run id, the runner's pid and paths. `--calibrate` makes it a [calibration run](#working-memory-calibration). |
+| `status [RUN]` | Shows progress, the current step, the heartbeat age and whether the runner is alive, and for a calibration run the number of saved store exports. |
+| `stop [RUN]` | Marks the run stopped, then kills the runner and its server, saves a calibration run's store from its scratch roots and removes them. If a process of the run still runs after the kill, `stop` names its pids, keeps the scratch roots with their stores and exits with code 2; end it and `stop` again. |
+| `resume [RUN]` | Starts the runner of a stopped or crashed run again, and waits until it has registered. Refuses while the run's runner is alive. On Linux the runner first stops a server its killed predecessor left running (see [How a run works](#how-a-run-works)); a calibration run's runner then saves a store left in a scratch root (see [Working-memory calibration](#working-memory-calibration)). |
| `report [RUN]` | Writes `report.html` and `summary.md` again. |
| `accept [RUN] [--case KEY]…` | Makes the run's measured results the references of its profile. Nothing else writes references. |
| `bundle [RUN] [--output PATH]` | Packs the run into a zip without this machine's paths, to attach to a PR or an issue (see [Bundle](#bundle)). |
@@ -80,12 +80,40 @@ Run the tool from the repository root with the checkout's environment, for examp
`RUN` is a run directory, or a run id together with `--manifest M`. Without it, the profile's latest run is used.
-A runner registers before it does anything else: it writes its process into `heartbeat.json`, which `stop`, `status` and `resume` read. `stop` marks the run stopped before it reads that file. The mark and a registration each hold `run.lock`, so they cannot interleave: a runner registered before `stop` is killed, and one that registers after it finds the run stopped and exits without touching it. A runner that `stop` could not kill exits before its next server or step. It never overwrites a status other than `running`.
+A runner registers before it does anything else: it writes its process into `heartbeat.json`, which `stop`, `status` and `resume` read. `stop` marks the run stopped before it reads that file. The mark and a registration each hold `run.lock`, so they cannot interleave: a runner registered before `stop` is killed, and one that registers after it finds the run stopped and exits without touching it. The runner also spawns each server under `run.lock` and records it in `heartbeat.json` before it lets go, so `stop` kills every server started before its mark, and no server starts after it. A runner that `stop` could not kill exits before its next server or step; in a calibration run it first saves its server's store, which `run.json` lists without a change of status. It never overwrites a status other than `running`.
On Windows the background runner breaks away from the caller's job object, so a terminal or an agent harness that kills its job's processes does not end a long run. Where breakaway is refused, the runner is created through WMI. It then starts with the user's default environment instead of the caller's.
A resumed run skips every step that already has a final record and keeps the measures of the earlier sessions. Its new server starts with a cold model cache, so each case size with measures left first repeats its last warm-up, once. The manifest, the graphs, and the server's commit and dirty flag must not have changed since the run started; further edits to an already dirty checkout cannot be detected.
+## Working-memory calibration
+
+`start --calibrate` measures what each model operation of the cases needs on this GPU. It runs where the rest of the tool does: on Windows, and on Linux with NVIDIA GPUs, where the server's probe reads the driver's figure through NVML too. Every step compiles its graph as a normal run does, then submits it to `POST /api/v2/models/i/{model}/working_memory/calibrate` with the case's `model` key instead of `enqueue_batch`, stating each model of the graph as the config the case was compiled from has it (`graph_models`, from the run's `case_models`); the server refuses a step whose models changed since. The server runs it with its working-memory probe, which records a window per estimated model operation in its calibration store (see "Calibration runs" in the [model manager architecture](/development/architecture/model-manager/#calibration-runs)). Warm-ups and measures alike are submitted, and every window is kept.
+
+- **Before the steps.** The runner reads `GET /api/v2/models/working_memory/status`. With `available: false` (no GPU, several generation devices, an unusable store file) the run fails with the server's reason. The scratch server runs single-user, so the tool is an administrator.
+- **Refusals.** A 404 or 422 answer to a calibrate request (an unknown model, a graph the run cannot measure) gives that step an error record, and the run goes on. Any other error response ends the run with the server's detail, after its store was saved; fix the cause and `resume`.
+- **Records.** Each accepted step's record carries `calibration`: the calibration run id and the device class. The probe synchronizes and empties the allocator cache around every model operation, so time and VRAM are invalid with that reason; `status` shows it as a calibration marker rather than counting it, and images are still compared. A step foreign load spoiled is not repeated: the server keeps every window. `accept` refuses calibration runs, and reports of later runs do not compare against them.
+- **Exports.** Every server lifetime has its own scratch database and store, so the tool submits each attempt once and sends no retry key. When a lifetime's steps are done, the runner saves `calibration/<run_id>-<n>-<device_class_id>.json` (`GET /api/v2/models/working_memory/export`, byte for byte) and `calibration/<run_id>-<n>-status.json`; `n` counts the run's lifetimes. After a server crash, a runner failure or `stop`, the store file is copied from the scratch root instead, without a status. `run.json` lists them all under `calibration_exports`. When neither the export nor the copy can be saved (a full disk, say), the run fails, or a stop stays stopped, and the scratch root under `<data_dir>/scratch-roots/` is kept with the store: the only copy of that lifetime's windows. `stop` still marks the run stopped, names the kept root and exits with code 2. Fix the cause and `resume`: once a server the earlier runner left running is stopped (see [How a run works](#how-a-run-works)), since it may still write its store, the runner saves a store that runner left in a scratch root (a failed save, or a killed runner), then removes the root. Both come before the new server's scratch root is built. If that save fails too, the runner refuses to go on, `runner.log` names the root and the run shows as failed; move its store away or fix the cause first.
+
+On a machine the tool does not run on, an administrator takes the export of a server's own calibration runs from `GET /api/v2/models/working_memory/export?device_class_id=<id>`; `GET /api/v2/models/working_memory/status` lists the device class ids.
+
+### Building shipped data
+
+```
+uv run --no-sync python -m scripts.working_memory.build_shipped <data_dir>/runs/<run_id>/calibration [more exports or directories] [--write]
+```
+
+`scripts/working_memory/build_shipped.py` reads the exports and prints what it would change in `invokeai/backend/working_memory/data/`; `--write` writes it. A directory stands for the exports in it, in lifetime order. Then run `uv run --no-sync pytest tests/backend/working_memory`.
+
+- **Points.** Every valid, fit-eligible window with a positive demand becomes a `probe_demand` point. Per card, estimator, version, platform and features it takes the largest `demand_bytes` of all windows given: repetitions, lifetimes, and several runs or machines with the same card. A card is a device class: vendor, name, memory size, backend and architecture. Cards of one name and another memory size stay apart: a point's `device` is the card's name and its device class id, e.g. `NVIDIA GeForce RTX 4060 Ti (0123456789abcdef)`. A window given twice (the same store in two files) counts once. The provenance names the card, the torch and runtime versions, the calibration run, item and node of the largest window, and its export file. Each point line shows its windows' demands in the order they ran and the largest over the first (`[3 windows, MiB 1960, 1820, 1820; max/first 1.00]`).
+- **Fragmentation.** A point whose reserved bytes grew by 10% or more from its first window to its largest while the allocated bytes stayed within 2% gets a `warning: fragmentation?` line with both series. That is the allocator's cache growing around the same tensors in a long-running server, not the operation needing more.
+- **Platforms.** A point's platform is the one `platform_for` gives on the machine that measured it, derived from the export's device class and its environment's hard facts (`platform_for_environment`), whatever machine the builder runs on. It names the OS only where an entry for that platform names it. A window whose environment lacks a fact the platform is read from is left out and counted.
+- **Bounds.** `probe_demand` points bound their estimates from below only: the estimate must cover them, and they may raise a line, but they take no part in choosing it (`fit.upper_envelope`), and the 1.3x upper bound and `max_ratio` stay with the fresh-process points, because the cold first run after a server start is the worst case.
+- **Merge and fit.** A point joins the data file that declares the estimator's coefficients; where a `probe_demand` point of the same card, platform and features is there, the larger of the two stays. The carried values are then refitted with `fit.py`. A stand-in line is fitted from then on only once its in-fit fresh-process points alone span two sizes twice apart; until then it stays a stand-in, which `probe_demand` points raise where their fit lies above it but never lower. A fitted line takes, per coefficient, the larger of its fit on all points and its fit on the fresh-process points alone. A refitted entry's provenance gets a note, and so does a raised stand-in's. Every moved line gets a `line` row: old and new slope and base, whether it was raised, and its new points.
+- **Refusals.** An export of another estimator version than the registered one, a window whose features the estimator cannot evaluate, a platform `MEASURED` does not list, and a line whose points span less than twice the pixels: exit code 2. Exit code 1, with nothing written:
+ - any point of the result breaks its bounds (`working_memory/bounds.py`, the rule the data test applies); the error lists them. A probe point that raises a line above what the fresh-process points of that line allow is refused this way;
+ - with `--write`, a line is raised on a point flagged as fragmentation, unless `--accept-fragmentation` is given.
+
## Bundle
`bundle` writes one zip that opens without this machine's data, by default `<run_dir>/<run_id>.zip`, and prints its path and size. Apart from that default zip, the run directory stays as it is. It refuses while the run's runner is alive. A stopped or failed run can be bundled, and its report states the status; a run whose runner died without recording it shows as interrupted.
@@ -102,7 +130,7 @@ The zip holds one folder, `<run_id>/`, with:
- `reference/<case_key>/reference.json` for each case whose accepted reference the report could read: the reference's run, graph hash, medians and environment, so a reader can tell `BASELINE` from `PASS` and redo the comparisons. A case without a readable reference has none; the file is optional in format version 2.
- `run.json`, `records.jsonl`, `graphs/` and `traces/`.
-Logs, `heartbeat.json`, `inputs/`, `export/`, scratch roots and images the report does not show stay out. On the way in:
+Logs, `heartbeat.json`, `inputs/`, `export/`, a calibration run's `calibration/`, scratch roots and images the report does not show stay out. On the way in:
- **`run.json`.** A value that is an absolute path keeps only its last component: `manifest_path`, `code_dir`, `python`, `invokeai_file`, the paths in `server_cmd` and the path settings in `runtime_config`. `extra_env` keeps its variable names; its values become `<redacted>`. So do the `runtime_config` settings that hold a string, list or mapping under a name that looks like a credential (`token`, `secret`, `key`, `auth`, `credential`, `pass`, `api`, `proxy`, `db_url`); flags such as `log_tokenization` stay.
- **`reference.json`.** Its environment is sanitized like those in `run.json`, and its `extra_env` credentials are removed from all text like the run's own.
@@ -178,4 +206,5 @@ Database migrations of a newer `code_dir` run against the scratch database only.
- img2img starts inside the schedule at a family-specific step, so the count is inferred. When steps are faster than 0.2 s that inference can be off by a factor, so the time per step is left empty.
- Ideogram 4 ignores `steps`; its step count follows `settings.ideogram4Steps` or `settings.ideogram4SamplerPreset`. `img2img` and `controlnet` are not available for ERNIE-Image and Ideogram 4. Dynamic prompts, canvas rasterization, video and upscale graphs are not covered.
- A bundle finds other paths in free text by their drive letter, or as POSIX paths of two or more components that start after a space, a quote or a bracket. Such a path, and a path below the home directory, keeps what follows a space in one of its directory names; a POSIX path at the root (`/x`) or right after `:` stays. A UNC path in free text stays as it is. An `extra_env` credential shorter than 8 characters is redacted in `run.json` only.
+- A calibration run measures the windows of estimated model operations only, inside a running server: they are not a fresh process's first operation, as the `demand_peak` points are.
- AMD GPUs on Linux and A/B runs of two checkouts are not available yet.
diff --git a/invokeai/app/api/routers/session_queue.py b/invokeai/app/api/routers/session_queue.py
index 25a25c4d8e..4b8f010c79 100644
--- a/invokeai/app/api/routers/session_queue.py
+++ b/invokeai/app/api/routers/session_queue.py
@@ -43,6 +43,7 @@ from invokeai.app.services.shared.pagination import SQLiteDirection
from invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundException
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
CALIBRATION_ORIGIN_PREFIX,
+ CalibrationStoreError,
is_reserved_origin,
)
@@ -622,14 +623,23 @@ def cancel_by_destination(
@session_queue_router.put(
"/{queue_id}/retry_items_by_id",
operation_id="retry_items_by_id",
- responses={200: {"model": RetryItemsResult}},
+ responses={
+ 200: {"model": RetryItemsResult},
+ 503: {
+ "description": "The items include a working-memory calibration's, and its store cannot be written now "
+ "(unwritable root, lock timeout): no item is retried, the request's other items included"
+ },
+ },
)
def retry_items_by_id(
current_user: CurrentUserOrDefault,
queue_id: str = Path(description="The queue id to perform this operation on"),
item_ids: list[int] = Body(description="The queue item ids to retry"),
) -> RetryItemsResult:
- """Retries the given queue items. Users can only retry their own items unless they are an admin."""
+ """Retries the given queue items. Users can only retry their own items unless they are an admin.
+
+ A calibration item's retry is recorded in the calibration store as it commits. When that store cannot be written,
+ the request retries nothing, also its items that are no calibration's (503); retry again once it can."""
try:
# Check queue membership for all items and ownership for non-admins.
valid_item_ids: list[int] = []
@@ -659,6 +669,12 @@ def retry_items_by_id(
)
except HTTPException:
raise
+ except CalibrationStoreError:
+ # The error names the store's path on the server.
+ raise HTTPException(
+ status_code=503,
+ detail="The working-memory calibration store cannot be written now, so no item was retried. Try again.",
+ )
except Exception as e:
raise HTTPException(status_code=500, detail=f"Unexpected error while retrying queue items: {e}")
diff --git a/invokeai/app/api/routers/working_memory.py b/invokeai/app/api/routers/working_memory.py
index b11ad76277..d1477ac479 100644
--- a/invokeai/app/api/routers/working_memory.py
+++ b/invokeai/app/api/routers/working_memory.py
@@ -23,12 +23,18 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibration
WorkingMemoryCalibrationServiceBase,
)
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
+ CalibrationAttemptBusyError,
+ CalibrationAttemptConflictError,
+ CalibrationAttemptInterleavedError,
CalibrationGraphError,
+ CalibrationModelChangedError,
CalibrationQueueFullError,
CalibrationRunNotFoundError,
CalibrationStoreError,
CalibrationStoreUnusableError,
CalibrationUnavailableError,
+ WorkingMemoryCalibrationModelSummary,
+ WorkingMemoryCalibrationPlan,
WorkingMemoryCalibrationRequest,
WorkingMemoryCalibrationResetResult,
WorkingMemoryCalibrationRunCreated,
@@ -62,6 +68,11 @@ def _service() -> WorkingMemoryCalibrationServiceBase:
def _http_error(error: Exception) -> HTTPException:
+ if isinstance(
+ error, (CalibrationAttemptBusyError, CalibrationAttemptInterleavedError, CalibrationModelChangedError)
+ ):
+ # Coded, as other routes' refusals a client acts on are: it tells these 409s from the others.
+ return HTTPException(status_code=409, detail={"code": error.code, "message": str(error)})
if isinstance(error, (CalibrationRunNotFoundError, UnknownModelException)):
return HTTPException(status_code=404, detail=str(error))
if isinstance(error, CalibrationGraphError):
@@ -72,6 +83,7 @@ def _http_error(error: Exception) -> HTTPException:
CalibrationUnavailableError,
CalibrationStoreUnusableError,
CalibrationQueueFullError,
+ CalibrationAttemptConflictError,
EnqueueIdempotencyConflictError,
),
):
@@ -95,10 +107,21 @@ def _http_error(error: Exception) -> HTTPException:
409: {
"description": "This machine cannot calibrate now (no GPU, or several generation devices), the device "
"class's store file is unusable and kept as it is (possibly after the items were queued, which then fail "
- "when they start), the queue has no room for all of the run's items (it then takes none), or the "
- "idempotency key was used for another request"
+ "when they start), the queue has no room for all of the run's items (it then takes none), the "
+ "idempotency key was used for another request, or attempt_steps differs from that of the attempt's runs "
+ "already stored (or of the run a repeated request names). Three of them carry a code, as "
+ '`{"code": ..., "message": ...}` in `detail`: `calibration_running`, another calibration attempt still '
+ "runs on this GPU, or another owner's attempt is between its steps and was active in the last two "
+ "minutes (an owner's new attempt replaces its own attempt that stopped between steps); "
+ "`calibration_interleaved`, a later step of an attempt after another calibration ran on this GPU since "
+ "the attempt began; `model_changed`, a model the graph names changed or was removed since the graph was "
+ "compiled (its record differs from the graph's identifier or its graph_models entry), or since an earlier "
+ "step of the attempt"
+ },
+ 422: {
+ "description": "The graph cannot be measured as a calibration run, graph_models does not state exactly "
+ "the graph's models, or attempt_id and attempt_steps were not sent together"
},
- 422: {"description": "The graph cannot be measured as a calibration run"},
429: {"description": "Too many unacknowledged idempotency keys; acknowledge or wait, then retry"},
503: {
"description": "The calibration store cannot be read or written (unwritable root, lock timeout); with an "
@@ -111,8 +134,9 @@ async def calibrate_model_working_memory(
key: str = Path(description="Key of the model the run calibrates"),
request: WorkingMemoryCalibrationRequest = Body(description="The batch to measure"),
) -> WorkingMemoryCalibrationRunCreated:
- """Start a working-memory calibration run: enqueue the batch with every node uncached and measure each node's
- model operations on the generation device. Needs exactly one generation device, and it must be a GPU. The queue
+ """Start a working-memory calibration run: enqueue the batch with every node uncached, its images intermediates
+ on no board (never in the gallery; clearing intermediates removes them), and measure each node's model operations
+ on the generation device. Needs exactly one generation device, and it must be a GPU. The queue
takes all of the batch's items or none.
Once the items are queued, a request without an `idempotency_key` succeeds even when the store fails for a passing
@@ -135,6 +159,10 @@ async def calibrate_model_working_memory(
CalibrationUnavailableError,
CalibrationStoreError,
CalibrationQueueFullError,
+ CalibrationAttemptConflictError,
+ CalibrationAttemptBusyError,
+ CalibrationAttemptInterleavedError,
+ CalibrationModelChangedError,
EnqueueIdempotencyConflictError,
EnqueueReceiptLimitError,
) as error:
@@ -155,6 +183,49 @@ def get_working_memory_calibration_status(current_admin: AdminUserOrDefault) ->
raise _http_error(error) from error
+@working_memory_router.get(
+ "/i/{key}/working_memory/plan",
+ operation_id="get_model_working_memory_calibration_plan",
+ response_model=WorkingMemoryCalibrationPlan,
+ responses={404: {"description": "The model could not be found"}},
+)
+def get_model_working_memory_calibration_plan(
+ current_admin: AdminUserOrDefault,
+ key: str = Path(description="Key of the model to calibrate"),
+) -> WorkingMemoryCalibrationPlan:
+ """The text-to-image cases that calibrate the model's decode on this machine's GPU, how often each runs, which
+ other installed models the calibration also moves, or why the model cannot be calibrated here (`supported`)."""
+ try:
+ return _service().get_plan(key)
+ except UnknownModelException as error:
+ raise _http_error(error) from error
+
+
+@working_memory_router.get(
+ "/i/{key}/working_memory/summary",
+ operation_id="get_model_working_memory_calibration_summary",
+ response_model=WorkingMemoryCalibrationModelSummary,
+ responses={
+ 404: {"description": "The model could not be found"},
+ 409: {"description": "No device_class_id was given and there is no current one"},
+ 503: _STORE_UNREADABLE,
+ },
+)
+def get_model_working_memory_calibration_summary(
+ current_admin: AdminUserOrDefault,
+ key: str = Path(description="Key of the model whose measurements to summarise"),
+ device_class_id: Optional[str] = _DEVICE_CLASS_ID,
+) -> WorkingMemoryCalibrationModelSummary:
+ """What the calibration windows of the model's lines measured on one device class, per estimator line and
+ environment: the sizes, the largest demand, the shipped and the user estimate, whether the user line is in use,
+ stale or unusable, and which models measured it, also for a line the model's decode shares with other models'
+ measurements; and the model's runs."""
+ try:
+ return _service().get_model_summary(key, device_class_id)
+ except (UnknownModelException, CalibrationUnavailableError, CalibrationStoreError) as error:
+ raise _http_error(error) from error
+
+
@working_memory_router.delete(
"/working_memory/runs/{run_id}",
operation_id="delete_working_memory_calibration_run",
@@ -169,7 +240,11 @@ def delete_working_memory_calibration_run(
current_admin: AdminUserOrDefault,
run_id: str = Path(description="The calibration run to remove"),
) -> WorkingMemoryCalibrationResetResult:
- """Remove a calibration run and its measurements. Its queue items that have not run yet fail when they start."""
+ """Remove a calibration run and its measurements. Its queue items that have not run yet fail when they start.
+
+ A removed run of an attempt still counts toward the attempt's runs (`attempt_steps`), so the rest of a finished
+ attempt is judged as before. Removing a run while its attempt runs, or after it was stopped (a canceled item),
+ stops the attempt for good: none of its measurements count."""
try:
return _service().reset_run(run_id)
except (CalibrationRunNotFoundError, CalibrationStoreError) as error:
@@ -188,7 +263,8 @@ def reset_model_working_memory_calibration(
device_class_id: Optional[str] = _DEVICE_CLASS_ID,
) -> WorkingMemoryCalibrationResetResult:
"""Remove a model's calibration runs with all their measurements, and every measurement of the model taken in
- other runs (a VAE measured inside a transformer's run, say), from one device class."""
+ other runs (a VAE measured inside a transformer's run, say), from one device class. Removed runs of an attempt
+ still count toward its runs; an attempt that was running is stopped for good, its later steps included."""
try:
return _service().reset_model(key, device_class_id)
except (CalibrationUnavailableError, CalibrationStoreError) as error:
@@ -205,7 +281,8 @@ def reset_working_memory_calibration(
current_admin: AdminUserOrDefault,
device_class_id: Optional[str] = _DEVICE_CLASS_ID,
) -> WorkingMemoryCalibrationResetResult:
- """Remove every calibration run and measurement of one device class."""
+ """Remove every calibration run and measurement of one device class. An attempt that was running is stopped
+ for good: its later steps never count either."""
try:
return _service().reset_all(device_class_id)
except (CalibrationUnavailableError, CalibrationStoreError) as error:
diff --git a/invokeai/app/invocations/flux2/flux2_klein_model_loader.py b/invokeai/app/invocations/flux2/flux2_klein_model_loader.py
index 4e7ab21d42..5c7424e5bb 100644
--- a/invokeai/app/invocations/flux2/flux2_klein_model_loader.py
+++ b/invokeai/app/invocations/flux2/flux2_klein_model_loader.py
@@ -39,7 +39,7 @@ from invokeai.backend.model_manager.taxonomy import (
# Variants sharing a Qwen3 entry (`klein_9b` and `klein_9b_base`) are valid encoder sources for
# each other. [dev] is deliberately absent: it uses a Mistral encoder, so it can never satisfy a
# Klein transformer, and `.get()` returning None is what makes the guards below fail closed.
-_KLEIN_TO_QWEN3_VARIANT: dict[Flux2VariantType, Qwen3VariantType] = {
+KLEIN_TO_QWEN3_VARIANT: dict[Flux2VariantType, Qwen3VariantType] = {
Flux2VariantType.Klein4B: Qwen3VariantType.Qwen3_4B,
Flux2VariantType.Klein4BBase: Qwen3VariantType.Qwen3_4B,
Flux2VariantType.Klein9B: Qwen3VariantType.Qwen3_8B,
@@ -236,7 +236,7 @@ class Flux2KleinModelLoaderInvocation(BaseInvocation):
"""
config = self._validate_diffusers_format(context, model, model_name)
source_variant = getattr(config, "variant", None)
- source_qwen3 = _KLEIN_TO_QWEN3_VARIANT.get(source_variant)
+ source_qwen3 = KLEIN_TO_QWEN3_VARIANT.get(source_variant)
# An allowlist, not "reject [dev]": a future third FLUX.2 variant has to fail closed here
# the way the [dev] loader's guard already makes it, rather than being silently accepted.
@@ -249,7 +249,7 @@ class Flux2KleinModelLoaderInvocation(BaseInvocation):
"(Its VAE is compatible - this only blocks encoder extraction.)"
)
- required_qwen3 = _KLEIN_TO_QWEN3_VARIANT.get(getattr(main_config, "variant", None))
+ required_qwen3 = KLEIN_TO_QWEN3_VARIANT.get(getattr(main_config, "variant", None))
if required_qwen3 is not None and source_qwen3 != required_qwen3:
raise ValueError(
f"Qwen3 encoder variant mismatch: FLUX.2 Klein {main_config.variant.value} requires a "
@@ -274,7 +274,7 @@ class Flux2KleinModelLoaderInvocation(BaseInvocation):
if qwen3_variant is None:
return
- expected_qwen3_variant = _KLEIN_TO_QWEN3_VARIANT.get(getattr(main_config, "variant", None))
+ expected_qwen3_variant = KLEIN_TO_QWEN3_VARIANT.get(getattr(main_config, "variant", None))
if expected_qwen3_variant is not None and qwen3_variant != expected_qwen3_variant:
raise ValueError(
f"Qwen3 encoder variant mismatch: FLUX.2 Klein {main_config.variant.value} requires "
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index 47cd1473af..6ad998f177 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -319,6 +319,7 @@ class DefaultSessionRunner(SessionRunnerBase):
def run(self, queue_item: SessionQueueItem):
# Exceptions raised outside `run_node` are handled by the processor. There is no need to catch them here.
+ self._refresh_user_fits()
# getattr, like the workflow-call lifecycle's reads: runners also execute stand-in items without an origin.
run_id = calibration_run_id(getattr(queue_item, "origin", None))
if run_id is not None:
@@ -328,6 +329,18 @@ class DefaultSessionRunner(SessionRunnerBase):
self._run_session_loop(queue_item)
self._on_after_run_session(queue_item=queue_item)
+ def _refresh_user_fits(self) -> None:
+ """Let this item's estimates read the calibration store as it is now: once per item, never per estimate."""
+ # getattr: stand-in service containers that runners execute with need not carry the calibration service.
+ service = getattr(self._services, "working_memory_calibration", None)
+ if service is None:
+ return
+ try:
+ service.refresh_user_fits()
+ except Exception:
+ # The fits read so far stay in force; a store that cannot be read must not fail a generation.
+ self._services.logger.warning("Could not refresh the working-memory user fits", exc_info=True)
+
def _run_calibration_item(self, queue_item: SessionQueueItem, run_id: str) -> None:
"""Run a working-memory calibration item, measuring each node (see `working_memory.probe`).
diff --git a/invokeai/app/services/session_queue/session_queue_base.py b/invokeai/app/services/session_queue/session_queue_base.py
index aaa93cfe6d..cddc3cfcbf 100644
--- a/invokeai/app/services/session_queue/session_queue_base.py
+++ b/invokeai/app/services/session_queue/session_queue_base.py
@@ -316,6 +316,12 @@ class SessionQueueBase(ABC):
case), in no order."""
pass
+ @abstractmethod
+ def get_unfinished_origins(self, queue_id: str, origin_prefix: str) -> set[str]:
+ """The origins of the items pending, in progress or waiting whose origin starts with `origin_prefix` (ignoring
+ case). Found through the items' status: it costs the queue's unfinished items, not its history."""
+ pass
+
@abstractmethod
def get_queue_item_summaries_by_ids(self, queue_id: str, item_ids: list[int]) -> list[SessionQueueItemSummary]:
"""Gets lightweight queue item summaries in the requested item ID order."""
diff --git a/invokeai/app/services/session_queue/session_queue_default.py b/invokeai/app/services/session_queue/session_queue_default.py
index cd79dafe1a..95ba79b2fe 100644
--- a/invokeai/app/services/session_queue/session_queue_default.py
+++ b/invokeai/app/services/session_queue/session_queue_default.py
@@ -1073,6 +1073,9 @@ class SessionQueue(SessionQueueBase):
)
]
+ def get_unfinished_origins(self, queue_id: str, origin_prefix: str) -> set[str]:
+ return set(self._queries.session_queue.unfinished_origins(queue_id, origin_prefix))
+
def get_queue_item_summaries_by_ids(self, queue_id: str, item_ids: list[int]) -> list[SessionQueueItemSummary]:
if not item_ids:
return []
@@ -1258,18 +1261,51 @@ class SessionQueue(SessionQueueBase):
clones = self._queries.run(survey, read_only=True)
+ # Whether the last run of `admit` reached its end: a run that raises before it rolls back. `run` repeats it
+ # after a conflict, so each run starts it over.
+ admit_ended = False
+
def admit(q: Queries) -> Optional[list[tuple[int, str, int]]]:
"""The clones the queue had room for, inserted one by one for their ids; None when it is full."""
+ nonlocal admit_ended
+ admit_ended = False
q.locks.acquire(*_ADMISSION, also_shared=_PROTECTING_MEDIA)
max_new_queue_items = max_queue_size - q.session_queue.pending_count(queue_id)
- if max_new_queue_items <= 0:
- return None
- return [
- (root_item_id, user_id, q.session_queue.insert_item(dict(zip(ITEM_COLUMNS, values, strict=True))))
- for root_item_id, user_id, values in clones[:max_new_queue_items]
- ]
-
- admitted = self._queries.run(admit)
+ inserted = (
+ None
+ if max_new_queue_items <= 0
+ else [
+ (root_item_id, user_id, q.session_queue.insert_item(dict(zip(ITEM_COLUMNS, values, strict=True))))
+ for root_item_id, user_id, values in clones[:max_new_queue_items]
+ ]
+ )
+ admit_ended = True
+ return inserted
+
+ # A calibration attempt feeds a fit only if its store knows every retry of its items, also one canceled and
+ # pruned before anything else saw it. Announcing a retry cannot promise that: the server may stop before the
+ # announcement is handled. So the store counts the retries in flight before they commit and records them
+ # after, and a count left over keeps the attempt out.
+ calibration = self.__invoker.services.working_memory_calibration
+ in_flight = None
+ if calibration is not None:
+ origin_at, retried_from_at = ITEM_COLUMNS.index("origin"), ITEM_COLUMNS.index("retried_from_item_id")
+ in_flight = calibration.retries_starting(
+ {root_item_id: (values[origin_at], values[retried_from_at]) for root_item_id, _, values in clones}
+ )
+ try:
+ admitted = self._queries.run(admit)
+ except Exception:
+ if calibration is not None and in_flight is not None:
+ # A failure once `admit` ended can be the commit's own, which may have committed all the same (a lost
+ # connection to MySQL or MariaDB): which retries exist is unknown, and the count stays.
+ calibration.retries_committed(in_flight, None if admit_ended else [])
+ raise
+ if calibration is not None and in_flight is not None:
+ calibration.retries_committed(
+ in_flight,
+ [RetriedQueueItem(source_item_id=root, item_id=item_id) for root, _, item_id in admitted or []],
+ )
if admitted is None:
return RetryItemsResult(queue_id=queue_id, retried_item_ids=[])
retried_item_ids_by_user: dict[str, list[int]] = {}
diff --git a/invokeai/app/services/shared/database/queries/session_queue.py b/invokeai/app/services/shared/database/queries/session_queue.py
index 0e8056d09a..e78bcde4b8 100644
--- a/invokeai/app/services/shared/database/queries/session_queue.py
+++ b/invokeai/app/services/shared/database/queries/session_queue.py
@@ -497,6 +497,11 @@ _BATCH_ITEM_IDS = select(_Q.item_id).where(_IN_BATCH).order_by(_Q.item_id)
_ACTIVE_WORK = (
select(literal(1)).where(_Q.status.in_([literal("pending"), literal("in_progress")])).limit(fixed_limit(1))
)
+# The unfinished items found by their status, the origin then tested on their rows: the read costs the queue's live
+# items, where the listing index would walk its whole history.
+_UNFINISHED_ORIGINS = select(_Q.origin).where(
+ _IN_QUEUE_UNINDEXED, _Q.status.in_([literal(status) for status in ACTIVE_QUEUE_STATUSES]), _origin_matches()
+)
_THE_RECEIPT = and_(
_R.queue_id == bindparam("queue_id"),
@@ -855,6 +860,12 @@ class SessionQueueQueries(QueryModule):
"""Id, status, origin and retry source of the queue's items with the origin, in no order."""
return conn.execute(_LINEAGE, {"queue_id": queue_id, "origin_pattern": like_prefix(origin_prefix)}).all()
+ @read
+ def unfinished_origins(self, conn: Connection, queue_id: str, origin_prefix: str) -> list[str]:
+ """The origin of each of the queue's items pending, in progress or waiting with the origin, in no order."""
+ parameters = {"queue_id": queue_id, "origin_pattern": like_prefix(origin_prefix)}
+ return list(conn.execute(_UNFINISHED_ORIGINS, parameters).scalars().all())
+
@mapped(_summaries)
@read
def summaries(self, conn: Connection, queue_id: str, item_ids: Sequence[int]) -> Sequence[Row[Any]]:
diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_base.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_base.py
index 87a8b78c6f..076350b243 100644
--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_base.py
+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_base.py
@@ -1,9 +1,12 @@
from abc import ABC, abstractmethod
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from typing import Optional
-from invokeai.app.services.session_queue.session_queue_common import SessionQueueItem
+from invokeai.app.services.session_queue.session_queue_common import RetriedQueueItem, SessionQueueItem
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
+ RetriesInFlight,
+ WorkingMemoryCalibrationModelSummary,
+ WorkingMemoryCalibrationPlan,
WorkingMemoryCalibrationRequest,
WorkingMemoryCalibrationResetResult,
WorkingMemoryCalibrationRunCreated,
@@ -29,6 +32,22 @@ class WorkingMemoryCalibrationServiceBase(ABC):
def admit(self, queue_item: SessionQueueItem, run_id: str) -> Optional[str]:
"""Called by the session runner before a calibration item runs: None to run it, or why it must fail."""
+ @abstractmethod
+ def retries_starting(self, sources: Mapping[int, tuple[Optional[str], int]]) -> Optional[RetriesInFlight]:
+ """Called by the session queue before it commits retries: per item a retry is made of, that item's origin and
+ the item its lineage started from. Counts the retries in flight on the runs of the calibration items among
+ them, in the store, so that a retry the store then fails to record keeps its attempt from feeding a fit. None
+ when no item is a calibration's, which touches no store file. Raises `CalibrationStoreError` when the store
+ cannot be written: the queue then retries nothing."""
+
+ @abstractmethod
+ def retries_committed(self, in_flight: RetriesInFlight, retried: Optional[Iterable[RetriedQueueItem]]) -> None:
+ """Called by the session queue once it committed the retries `retries_starting` counted, or rolled them back
+ (`retried` empty): record each retry of `retried` on its run, pending and standing for the item its lineage
+ started from, and count the retries in flight down again. `retried` None when the queue failed at or after its
+ commit, which may have committed: the count then stays. Never raises; a failure is logged and leaves the count
+ up."""
+
@abstractmethod
def model_reset_epochs(self, run_id: str) -> dict[str, int]:
"""The reset epoch of every model reset on the run's device class; empty when the run does not exist. Read
@@ -76,3 +95,25 @@ class WorkingMemoryCalibrationServiceBase(ABC):
@abstractmethod
def export(self, device_class_id: Optional[str] = None) -> Optional[bytes]:
"""The device class's store file as it is on disk, the current one by default; None when it has none."""
+
+ @abstractmethod
+ def refresh_user_fits(self) -> None:
+ """Bring the user fits estimates read (`backend/working_memory/user_fit.py`) up to date with the store: per
+ GPU generation device, the fit of its device class's windows in the current environment, leaving out the
+ windows of calibration runs still running. Re-reads a file only when its signature or the environment changed,
+ so an unchanged store whose runs all finished costs one stat per device; while a run is unfinished, also one
+ queue read of its unfinished items by id. The session runner calls this when it starts any queue item;
+ building a plan and a reset call it too. Estimates read the fits from memory."""
+
+ @abstractmethod
+ def get_plan(self, model_key: str) -> WorkingMemoryCalibrationPlan:
+ """The cases that calibrate the model on this machine's GPU, or why it cannot be calibrated here. Raises
+ UnknownModelException for an unknown key."""
+
+ @abstractmethod
+ def get_model_summary(
+ self, model_key: str, device_class_id: Optional[str] = None
+ ) -> WorkingMemoryCalibrationModelSummary:
+ """What the windows that feed the model's lines measured on one device class, the current one by default: per
+ line and environment, the shipped and the user estimate at each size, whether the user line applies, and which
+ models measured it; and the model's runs. Raises UnknownModelException for an unknown key."""
diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_common.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_common.py
index 74fa75f9e6..4e3532d887 100644
--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_common.py
+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_common.py
@@ -3,14 +3,27 @@
A calibration run is a batch an administrator enqueues to measure one model's working memory. Its queue items carry the
reserved origin `CALIBRATION_ORIGIN_PREFIX` + run id; the session runner measures every node of such an item with the
working-memory probe and hands the windows to the calibration service, which keeps them in one JSON file per device
-class (`CalibrationStoreFile`). Recording only: nothing here changes an estimate.
+class (`CalibrationStoreFile`). The service fits the windows of the current environment into user lines that estimates
+read (`backend/working_memory/user_fit.py`), plans the cases a client runs to calibrate a model, and summarises what a
+model's runs measured.
"""
import datetime
-from typing import Final, Literal, Optional
-
-from pydantic import BaseModel, ConfigDict, Field, model_validator
-
+from collections.abc import Iterator, Mapping
+from dataclasses import dataclass
+from typing import Any, Final, Literal, Optional
+
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SerializerFunctionWrapHandler,
+ ValidationError,
+ model_serializer,
+ model_validator,
+)
+
+from invokeai.app.invocations.model import ModelIdentifierField
from invokeai.app.services.session_queue.session_queue_common import QUEUE_ITEM_STATUS, BatchDataCollection
from invokeai.app.services.shared.graph import Graph
from invokeai.backend.working_memory.counters import Backend
@@ -22,6 +35,8 @@ CALIBRATION_ORIGIN_PREFIX: Final = "invokeai:wm-calibration:"
CALIBRATION_DESTINATION: Final = "invokeai:wm-calibration"
"""The destination of calibration items: not a gallery or canvas destination, so no client routes their results."""
STORE_SCHEMA_VERSION: Final = 1
+ATTEMPT_STEPS_MAX: Final = 256
+"""The most runs one attempt may plan. A plan has at most a few dozen steps (`working_memory_calibration_plan.py`)."""
def calibration_origin(run_id: str) -> str:
@@ -35,6 +50,32 @@ def calibration_run_id(origin: Optional[str]) -> Optional[str]:
return origin[len(CALIBRATION_ORIGIN_PREFIX) :]
+def graph_model_identifiers(graph: Graph) -> Iterator[ModelIdentifierField]:
+ """The models a graph's nodes name: their model fields, also inside a field's model, list or mapping (a LoRA
+ collection's `LoRAField.lora`), and every mapping that reads as a model identifier, such as a model a metadata
+ node's untyped field records. A client sees the graph as JSON, where those look alike, so both count."""
+
+ def within(value: object) -> Iterator[ModelIdentifierField]:
+ if isinstance(value, ModelIdentifierField):
+ yield value
+ elif isinstance(value, BaseModel):
+ for _, field in value:
+ yield from within(field)
+ elif isinstance(value, Mapping):
+ try:
+ yield ModelIdentifierField.model_validate(value)
+ except ValidationError:
+ for entry in value.values():
+ yield from within(entry)
+ elif isinstance(value, (list, tuple)):
+ for entry in value:
+ yield from within(entry)
+
+ for node in graph.nodes.values():
+ for _, value in node:
+ yield from within(value)
+
+
def is_reserved_origin(origin: Optional[str]) -> bool:
"""Whether a client-supplied origin claims the calibration prefix. Case-insensitive, because the queue's origin
filters are: a look-alike origin would otherwise be counted among a run's items."""
@@ -100,15 +141,81 @@ class CalibrationPoint(MeasuredWindow):
env_id: str
+CalibrationErrorCode = Literal["model_changed"]
+"""Why a run's item failed, where a client acts on it: model_changed, a model its graph names changed or was removed
+after the calibration was planned, so the item failed at admission; calibrate again."""
+
+MODEL_CHANGED: Final[CalibrationErrorCode] = "model_changed"
+CALIBRATION_RUNNING: Final = "calibration_running"
+"""The code of the 409 that refuses a new attempt while another one runs, or is still open, on the GPU's device
+class."""
+
+CALIBRATION_INTERLEAVED: Final = "calibration_interleaved"
+"""The code of the 409 that refuses a later step of an attempt once another calibration ran on the GPU since the
+attempt began."""
+
+
class ObservedItem(_StoreModel):
- """What the session runner saw of one of the run's queue items. Kept so that a run's status survives the queue
- pruning its items."""
+ """What the session runner saw of one of the run's queue items, or what the calibration service recorded of a
+ retry as the queue committed it. Kept so that a run's status survives the queue pruning its items."""
status: QUEUE_ITEM_STATUS
error_message: Optional[str] = None
+ error_code: Optional[CalibrationErrorCode] = None
retried_from_item_id: Optional[int] = None
observed_at: datetime.datetime
+ @model_serializer(mode="wrap")
+ def _omit_absent_fields(self, handler: SerializerFunctionWrapHandler) -> dict:
+ # Written only when set: an observation without it stays readable by a version that forbids the unknown field.
+ data = handler(self)
+ if data.get("error_code") is None:
+ data.pop("error_code", None)
+ return data
+
+
+class CalibrationModelIdentity(_StoreModel):
+ """What a calibration run's model was when the run was created, beside its hash (`CalibrationRun.model_hash`): the
+ facts that decide which decode the graph runs and which line it measures."""
+
+ base: Optional[str] = None
+ type: Optional[str] = None
+ format: Optional[str] = None
+ variant: Optional[str] = None
+
+
+class CalibrationGraphModel(CalibrationModelIdentity):
+ """A model a calibration run's graph names, as it was when the run was created: its identity and its hash."""
+
+ hash: Optional[str] = None
+
+ def changes(self, current: "CalibrationGraphModel") -> list[str]:
+ """The facts in which `current` differs from this record. A hash this record lacks (stored before hashes were
+ recorded) is not compared."""
+ return [
+ fact
+ for fact in type(self).model_fields
+ if (value := getattr(self, fact)) != getattr(current, fact) and (fact != "hash" or value is not None)
+ ]
+
+ @model_serializer(mode="wrap")
+ def _omit_absent_hash(self, handler: SerializerFunctionWrapHandler) -> dict:
+ data = handler(self)
+ if data.get("hash") is None:
+ data.pop("hash", None)
+ return data
+
+
+class CalibrationCompiledModel(CalibrationGraphModel):
+ """A model a calibration request's graph names, as the record the client compiled the graph against has it. Every
+ fact is required: format and variant are null for a record without one, the rest is never null."""
+
+ hash: str = Field(description="The model's hash, as the graph's identifier names it")
+ base: str
+ type: str
+ format: Optional[str] = Field(description="The model's format; null for a record without one")
+ variant: Optional[str] = Field(description="The model's variant; null for a record without one")
+
class CalibrationRun(_StoreModel):
run_id: str
@@ -127,6 +234,89 @@ class CalibrationRun(_StoreModel):
observed: dict[int, ObservedItem] = Field(
default_factory=dict, description="The last status the session runner saw per item, retries included"
)
+ attempt_id: Optional[str] = Field(default=None, description="The client's attempt the run belongs to, if any")
+ attempt_steps: Optional[int] = Field(
+ default=None,
+ ge=1,
+ description="How many runs the attempt planned, as its runs sent it; only with attempt_id. Absent in runs "
+ "stored before it was sent, whose attempt is judged on the runs it recorded",
+ )
+ soft: Optional[dict[str, Optional[str]]] = Field(
+ default=None,
+ description="The soft facts of the environment the run was created under; absent in runs stored before they "
+ "were recorded, which fall back to the environment's",
+ )
+ model_identity: Optional[CalibrationModelIdentity] = Field(
+ default=None,
+ description="The model as it was when the run was created; an item fails at admission once it changed. Absent "
+ "in runs stored before it was recorded, which compare the hash alone",
+ )
+ graph_models: dict[str, CalibrationGraphModel] = Field(
+ default_factory=dict,
+ description="Per model key, each model the run's graph names as the client compiled the graph against it "
+ "(the request's graph_models), which the run's creation found unchanged. An item fails at admission once one "
+ "changed, and a later run of the attempt is refused once one differs from what this run recorded. Absent in "
+ "runs stored before it was recorded",
+ )
+ retries_in_flight: int = Field(
+ default=0,
+ ge=0,
+ description="How many retry operations of the queue that retry items of this run are in flight, however many "
+ "items each retries: counted up before the operation commits and down once its retries are recorded or it "
+ "rolled back (`retries_starting`, `retries_committed`). One left over means the server stopped, the commit "
+ "failed in a way that may have committed, or the store could not be written, between the count and the "
+ "record: a retry may exist that the run does not record, so the run's attempt never feeds a fit until a reset "
+ "removes the run",
+ )
+
+ @model_validator(mode="after")
+ def _steps_belong_to_an_attempt(self) -> "CalibrationRun":
+ if self.attempt_steps is not None and self.attempt_id is None:
+ raise ValueError(f"Run {self.run_id} plans attempt_steps without an attempt_id")
+ return self
+
+ @model_serializer(mode="wrap")
+ def _omit_absent_fields(self, handler: SerializerFunctionWrapHandler) -> dict:
+ # Written only when set: a run without them stays readable by a version that forbids the unknown fields.
+ data = handler(self)
+ for name in ("attempt_id", "attempt_steps", "soft", "model_identity"):
+ if data.get(name) is None:
+ data.pop(name, None)
+ if not data.get("graph_models"):
+ data.pop("graph_models", None)
+ if not data.get("retries_in_flight"):
+ data.pop("retries_in_flight", None)
+ return data
+
+
+class RemovedAttemptSteps(_StoreModel):
+ """What resets removed of one attempt, an owner's attempt_id: what judging the runs of it that are left needs."""
+
+ user_id: str = Field(description="The owner of the attempt's runs")
+ attempt_id: str
+ removed: int = Field(ge=1, description="How many of the attempt's runs resets removed; they count as queued")
+ aborted: bool = Field(
+ default=False,
+ description="Whether the attempt was running or already aborted when a reset removed a run of it: it then "
+ "never feeds a fit",
+ )
+ attempt_steps: Optional[int] = Field(
+ default=None,
+ ge=1,
+ description="The attempt_steps the removed runs sent, which a later run of the attempt must send too; null "
+ "for runs stored before it was sent",
+ )
+
+
+@dataclass(frozen=True)
+class RetriesInFlight:
+ """The calibration runs a retry is committing items of, as `retries_starting` counted them
+ (`CalibrationRun.retries_in_flight`), for `retries_committed` to record the retries on and count down again."""
+
+ runs: Mapping[str, frozenset[str]]
+ """Per device class, the runs counted on its file."""
+ lineages: Mapping[int, tuple[str, int]]
+ """Per item a retry is made of: its run, and the item the lineage started from, which the retry stands for."""
class CalibrationStoreFile(_StoreModel):
@@ -147,20 +337,91 @@ class CalibrationStoreFile(_StoreModel):
description="Per model key, how often the model was reset. A node's points of a model reset after the node "
"started are dropped",
)
+ removed_attempt_steps: list[RemovedAttemptSteps] = Field(
+ default_factory=list,
+ description="Per attempt (owner and attempt_id), what resets removed of it, so that the runs of it that are "
+ "left are judged on every run it queued. Kept while a stored run of the attempt is left, or a later step of it "
+ "may still come: the attempt was running when a reset removed a run of it",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def _records_of_owners(cls, data: Any) -> Any:
+ # Development builds keyed the records by attempt id alone. Each becomes the record of every owner whose stored
+ # runs carry that attempt id; one no stored run carries any more judges nothing, and is dropped.
+ if not isinstance(data, dict) or not isinstance(data.get("removed_attempt_steps"), dict):
+ return data
+ runs = [run for run in data.get("runs") or [] if isinstance(run, dict)]
+ records = [
+ {**record, "user_id": owner, "attempt_id": attempt_id}
+ for attempt_id, record in data["removed_attempt_steps"].items()
+ for owner in sorted({run.get("user_id") for run in runs if run.get("attempt_id") == attempt_id})
+ if isinstance(record, dict) and isinstance(owner, str)
+ ]
+ return {**data, "removed_attempt_steps": records}
+
+ @model_serializer(mode="wrap")
+ def _omit_absent_fields(self, handler: SerializerFunctionWrapHandler) -> dict:
+ # Written only while a reset's record is kept: a file without one stays readable by a version that forbids the
+ # unknown field.
+ data = handler(self)
+ if not data.get("removed_attempt_steps"):
+ data.pop("removed_attempt_steps", None)
+ return data
# endregion
# region API
+ATTEMPT_ID_DESCRIPTION: Final = (
+ "A client-generated id of the calibration attempt the run belongs to (1-64 letters, digits, '_', '-', '.', ':'), "
+ "so a client that enqueues one run per step can group them. Sent together with attempt_steps, never alone (422). No "
+ "window of an attempt feeds an estimate until it queued attempt_steps runs and every one has finished; a run a "
+ "reset removed still counts as queued, without its measurements. An aborted attempt never feeds one: an item of "
+ "it ended canceled (Stop, a queue clear) or failed because a model changed after the calibration was planned "
+ "(error_code model_changed), it ended before it queued all its runs (Stop, a failed submission), another "
+ "calibration ran on the GPU between its runs, or a reset removed a run of it while it ran. An item that failed "
+ "ends that step, not the attempt. "
+ "The run id derives from the idempotency_key, the request and the attempt, so an idempotency_key names one run: "
+ "repeating the request under the same attempt returns that run, and reusing the key under another attempt is "
+ "refused with 409 while the queue keeps the key's receipt. Make each key unique per run of an attempt."
+)
+ATTEMPT_STEPS_DESCRIPTION: Final = (
+ f"How many runs the attempt (attempt_id) queues, 1-{ATTEMPT_STEPS_MAX}. Sent together with attempt_id, never "
+ "alone (422), and the same by every run of the attempt: a run that sends another number than the attempt's runs "
+ "already stored is refused with 409. The attempt's windows feed estimates only once it queued that many runs, "
+ "those a reset removed since included, and all of them have finished with no item canceled."
+)
+MEASUREMENT_METHOD_DESCRIPTION: Final = (
+ "Where a window on a GPU of this class here reads its driver figure (`counters.Method`): torch-only when this "
+ "platform has no driver reader; null when no generation device of this class is present"
+)
+MEASUREMENT_VERIFIED_DESCRIPTION: Final = (
+ "Whether that method was checked against real hardware on this backend (`counters.VERIFIED_METHODS`); null when "
+ "no generation device of this class is present"
+)
+
+
+GRAPH_MODELS_DESCRIPTION: Final = (
+ "Per model key, every model the graph names (in a node's field, inside one, or in a mapping that reads as a model "
+ "identifier), as the client compiled the graph against its record. Exactly the graph's models are named (422 "
+ "otherwise). "
+ "The run's creation compares each with the model's record now, and refuses the run with 409 `model_changed` when "
+ "any differs, so send the records the graph was compiled from, never ones read again before posting. The run "
+ "records them, and admission compares them again when its item starts."
+)
+
class WorkingMemoryCalibrationRequest(BaseModel):
"""The batch a calibration run enqueues, built by the client. The server sets origin, destination, runs and the
- graph's id, and turns the node cache off."""
+ graph's id, turns the node cache off, and makes every node's images intermediates on no board: never in the
+ gallery, and removed by clearing intermediates."""
model_config = ConfigDict(extra="forbid")
graph: Graph = Field(description="The graph to measure")
+ graph_models: dict[str, CalibrationCompiledModel] = Field(description=GRAPH_MODELS_DESCRIPTION)
data: Optional[BatchDataCollection] = Field(default=None, description="The batch data collection")
idempotency_key: Optional[str] = Field(
default=None,
@@ -170,6 +431,37 @@ class WorkingMemoryCalibrationRequest(BaseModel):
"nothing new; once a reset removed that run, the repeat is refused. Reusing the key for another request "
"(another model, graph or batch data) is rejected while the queue keeps the key's enqueue receipt.",
)
+ attempt_id: Optional[str] = Field(
+ default=None,
+ min_length=1,
+ max_length=64,
+ pattern=r"^[A-Za-z0-9_.:-]+$",
+ description=ATTEMPT_ID_DESCRIPTION,
+ )
+ attempt_steps: Optional[int] = Field(
+ default=None, ge=1, le=ATTEMPT_STEPS_MAX, description=ATTEMPT_STEPS_DESCRIPTION
+ )
+
+ @model_validator(mode="after")
+ def _attempt_comes_with_its_steps(self) -> "WorkingMemoryCalibrationRequest":
+ if (self.attempt_id is None) != (self.attempt_steps is None):
+ raise ValueError("attempt_id and attempt_steps are sent together or not at all")
+ return self
+
+ @model_validator(mode="after")
+ def _graph_models_name_the_graphs_models(self) -> "WorkingMemoryCalibrationRequest":
+ named = {identifier.key for identifier in graph_model_identifiers(self.graph)}
+ problems = [
+ f"the graph names {key}, which graph_models lacks" for key in sorted(named - self.graph_models.keys())
+ ]
+ problems += [
+ f"graph_models names {key}, which the graph does not" for key in sorted(self.graph_models.keys() - named)
+ ]
+ if problems:
+ raise ValueError(
+ f"graph_models must name every model the graph names, and only those: {'; '.join(problems)}"
+ )
+ return self
class WorkingMemoryCalibrationRunCreated(BaseModel):
@@ -184,6 +476,22 @@ class WorkingMemoryCalibrationRunCreated(BaseModel):
CalibrationRunStatus = Literal["running", "completed", "failed", "partial", "canceled"]
+CalibrationHoldBack = Literal["running", "aborted_attempt"]
+"""Why no window of a run feeds a fit: running, the queue holds an unfinished item of it or of a run of its attempt;
+aborted_attempt, none is running and its attempt was aborted: an item of it ended canceled (Stop, a queue clear) or
+failed because a model changed after the calibration was planned (`model_changed`), it queued fewer runs than its
+attempt_steps (Stop, or a failed submission, ended it before it queued them all; a run a reset removed counts as
+queued), another calibration ran on the GPU between its runs, or a reset removed a run of it while it ran or after it
+was aborted. An aborted attempt never feeds a fit."""
+
+_RUN_ERROR_CODE_DESCRIPTION: Final = (
+ "Why the failed item failed, where a client acts on it (`CalibrationErrorCode`): model_changed, a model its graph "
+ "names changed or was removed after the calibration was planned. Null otherwise"
+)
+_RUN_ATTEMPT_STEPS_DESCRIPTION: Final = (
+ "How many runs the run's attempt planned; null without an attempt, and for a run stored before it was sent"
+)
+
class WorkingMemoryCalibrationRunSummary(BaseModel):
run_id: str
@@ -198,8 +506,11 @@ class WorkingMemoryCalibrationRunSummary(BaseModel):
"valid points were recorded, else canceled"
)
error: Optional[str] = Field(description="The error of a failed item, when the run failed")
+ error_code: Optional[CalibrationErrorCode] = Field(description=_RUN_ERROR_CODE_DESCRIPTION)
item_ids: list[int] = Field(description="Every queue item of the run known, retries and the items they retried")
point_count: int
+ attempt_id: Optional[str] = Field(description="The client's attempt the run belongs to; null when none was sent")
+ attempt_steps: Optional[int] = Field(description=_RUN_ATTEMPT_STEPS_DESCRIPTION)
class WorkingMemoryCalibrationPointCount(BaseModel):
@@ -218,7 +529,8 @@ class WorkingMemoryCalibrationEnvironment(BaseModel):
description="Whether the current environment has the same hard facts; null off the current device class"
)
soft_matches_current: Optional[bool] = Field(
- description="Whether the current environment has the same soft facts; null off the current device class"
+ description="Whether the current environment has the soft facts first recorded with this environment (`soft`); "
+ "a later run's own soft facts are not compared here. Null off the current device class"
)
point_count: int
@@ -229,6 +541,8 @@ class WorkingMemoryCalibrationDeviceClass(BaseModel):
usable: bool
problem: Optional[str] = Field(description="Why the file is unusable. It is kept as it is and never written")
is_current: bool
+ measurement_method: Optional[str] = Field(description=MEASUREMENT_METHOD_DESCRIPTION)
+ measurement_verified: Optional[bool] = Field(description=MEASUREMENT_VERIFIED_DESCRIPTION)
runs: list[WorkingMemoryCalibrationRunSummary]
point_counts: list[WorkingMemoryCalibrationPointCount]
envs: list[WorkingMemoryCalibrationEnvironment]
@@ -250,6 +564,188 @@ class WorkingMemoryCalibrationResetResult(BaseModel):
points_removed: int
+class WorkingMemoryCalibrationDeviceClassRef(BaseModel):
+ id: str
+ name: str
+
+
+class WorkingMemoryCalibrationCase(BaseModel):
+ """One generation a calibration plan runs, in the fields of the client's graph-export case (mode txt2img)."""
+
+ id: str = Field(description="Unique within the plan; becomes the graph id")
+ mode: Literal["txt2img"] = "txt2img"
+ model_key: str = Field(description="The main model the case generates with")
+ components: dict[str, str] = Field(
+ description="Component picks by Generate slot key; `vae` when a standalone VAE is calibrated or a GPU VAE "
+ "must be picked over one that runs on the CPU"
+ )
+ width: int
+ height: int
+ steps: int = Field(description="The fewest steps that still run the whole pipeline")
+ seed: int
+ positive_prompt: str
+ negative_prompt: str
+ settings: dict[str, str] = Field(
+ description="Generate settings overrides: `vaePrecision` (fp16 or fp32) where the decode node casts the VAE"
+ )
+ estimator: str = Field(description="The working-memory estimator of the operation the case measures")
+ line: str = Field(description="The estimator line the case measures, `<operation>_<dtype>`")
+
+
+class WorkingMemoryCalibrationRepetitions(BaseModel):
+ warm_up: int = Field(description="Runs of each case before the measured ones; their windows count too")
+ measured: int
+
+
+class WorkingMemoryCalibrationSharedModel(BaseModel):
+ key: str
+ name: str
+ base: str
+ type: str
+ lines: list[str] = Field(description="The lines it shares with the planned model, `<operation>_<dtype>`")
+
+
+class WorkingMemoryCalibrationPlan(BaseModel):
+ """What calibrating one model on this machine's GPU runs, or why it cannot."""
+
+ model_key: str
+ supported: bool
+ reason: Optional[str] = Field(description="Why the model cannot be calibrated here, when it cannot")
+ device_class: Optional[WorkingMemoryCalibrationDeviceClassRef] = Field(
+ description="The class of the GPU the cases run on; null without exactly one GPU generation device"
+ )
+ calibrated_through: Optional[str] = Field(
+ description="For a standalone VAE, the installed main model the cases generate with"
+ )
+ estimators: list[str] = Field(description="The working-memory estimators of the model's covered operations")
+ cases: list[WorkingMemoryCalibrationCase]
+ repetitions: WorkingMemoryCalibrationRepetitions
+ estimated_seconds: Optional[int] = Field(
+ description="A rough order of magnitude for all cases and repetitions, model load included; not a measurement"
+ )
+ shared_with: list[WorkingMemoryCalibrationSharedModel] = Field(
+ description="Other installed models whose operations price with the same lines on this GPU, so a calibration "
+ "changes their estimates too"
+ )
+ not_covered: list[str] = Field(description="Operations of the model a calibration does not measure, and why")
+
+
+CalibrationLineState = Literal["in_use", "stale", "unusable", "insufficient"]
+
+CalibrationSizeExclusion = Literal["fragmented", "partial_residency", "aborted_attempt"]
+
+
+class WorkingMemoryCalibrationLineSize(BaseModel):
+ width: int
+ height: int
+ pixels: int
+ windows: int = Field(
+ description="Counted: the windows at this size that feed the line, valid, fit-eligible and not fragmented, of "
+ "every model in the environment; those of a calibration run still running are counted, and join the fit once "
+ "it finished. Not counted: the valid windows measured at this size"
+ )
+ measured_bytes: int = Field(description="The largest demand of those windows")
+ counted: bool = Field(description="Whether windows of this size feed the user line")
+ excluded_reason: Optional[CalibrationSizeExclusion] = Field(
+ description="Why a size is not counted: fragmented, its windows measured the allocator's fragmentation "
+ "(`backend/working_memory/fragmentation.py`); partial_residency, the model was not fully on the device; "
+ "aborted_attempt, its windows come from aborted attempts (Stop, a queue clear, a failed submission, a model "
+ "changed after the calibration was planned), which never feed a line. Null for a counted size"
+ )
+ shipped_bytes: Optional[int] = Field(
+ description="The shipped estimate at this size, priced with the line's estimator where one of its windows "
+ "measured the size, otherwise with that of the largest window; null when the platform of the environment is "
+ "unknown"
+ )
+ user_bytes: Optional[int] = Field(
+ description="The estimate with the user line applied, as estimates read it (without the windows of runs still "
+ "running); null without a user line"
+ )
+
+
+class WorkingMemoryCalibrationPixelRange(BaseModel):
+ min_pixels: int
+ max_pixels: int
+
+
+class WorkingMemoryCalibrationLineContributor(BaseModel):
+ """A model whose windows feed a line: the model a run calibrated, or the model a window measured."""
+
+ model_key: str
+ name: Optional[str] = Field(description="The model's name; null when it is no longer installed")
+ windows: int = Field(description="Its counted windows on the line: valid, fit-eligible and not fragmented")
+
+
+class WorkingMemoryCalibrationModelLine(BaseModel):
+ """One estimator line in one environment: one the model's windows measured, or, in the current environment, one
+ the model's decode prices on that other models' windows measured."""
+
+ estimator: str
+ version: int
+ line: str = Field(description="`<operation>_<dtype>`")
+ carrier: Optional[str] = Field(description="The estimator whose shipped entry carries the line on this platform")
+ env_id: str
+ state: CalibrationLineState = Field(
+ description="in_use: the user line applies; stale: it applies, but the soft facts of the newest finished run "
+ "that contributed a window differ from the current ones; unusable: hard facts "
+ "differ from the current environment (or no GPU of this class generates here), so shipped values apply; "
+ "insufficient: the windows of finished, complete attempts cannot fit a line (yet); `problem` says why"
+ )
+ changed_facts: list[str] = Field(
+ description="The soft facts that changed (stale) or the hard facts that differ (unusable)"
+ )
+ problem: Optional[str] = Field(description="Why no line could be fitted, when it could not")
+ measured_range: Optional[WorkingMemoryCalibrationPixelRange] = Field(
+ description="The sizes the user line was fitted on, over every model's windows of the line from finished runs"
+ )
+ slope_bytes_per_pixel: Optional[int]
+ base_bytes: Optional[int]
+ sizes: list[WorkingMemoryCalibrationLineSize]
+ own_windows: int = Field(description="The model's own windows that feed the line; 0 when only other models' do")
+ measured_by: list[WorkingMemoryCalibrationLineContributor] = Field(
+ description="Every model whose windows feed the line, this one included when it has any; by name, then key"
+ )
+
+
+class WorkingMemoryCalibrationModelRun(BaseModel):
+ run_id: str
+ status: CalibrationRunStatus
+ error: Optional[str]
+ error_code: Optional[CalibrationErrorCode] = Field(description=_RUN_ERROR_CODE_DESCRIPTION)
+ created_at: datetime.datetime
+ point_count: int
+ attempt_id: Optional[str] = Field(description="The client's attempt the run belongs to; null when none was sent")
+ attempt_steps: Optional[int] = Field(description=_RUN_ATTEMPT_STEPS_DESCRIPTION)
+ held_back: Optional[CalibrationHoldBack] = Field(
+ description="Why no window of the run feeds a fit: running, it or a run of its attempt is still in the queue, "
+ "and its windows join once all have finished; aborted_attempt, its attempt was aborted, and its windows never "
+ "feed one: an item of it ended canceled (Stop, a queue clear) or failed because a model changed after "
+ "the calibration was planned (model_changed), another calibration ran on the GPU between its runs, the "
+ "attempt ended before it queued all "
+ "attempt_steps runs (Stop, a failed submission), or a reset removed a run of it while it ran. Null when its "
+ "windows are judged like any finished run's"
+ )
+
+
+class WorkingMemoryCalibrationModelSummary(BaseModel):
+ """What one model's calibration runs measured on one device class, and what estimates make of it."""
+
+ model_key: str
+ device_class_id: str
+ usable: bool
+ problem: Optional[str] = Field(description="Why the store file is unusable")
+ current_env_id: Optional[str] = Field(description="Null when no generation device of this class is present")
+ measurement_method: Optional[str] = Field(description=MEASUREMENT_METHOD_DESCRIPTION)
+ measurement_verified: Optional[bool] = Field(description=MEASUREMENT_VERIFIED_DESCRIPTION)
+ lines: list[WorkingMemoryCalibrationModelLine]
+ excluded_windows: int = Field(
+ description="The model's windows that feed no line: invalid, not fit-eligible, fragmented, of an aborted "
+ "attempt, tiled, batched, upcast, a VAE outside the AutoencoderKL family, or no demand. The valid ones among "
+ "them still show as sizes that are not counted"
+ )
+ runs: list[WorkingMemoryCalibrationModelRun]
+
+
# endregion
# region Errors
@@ -277,6 +773,32 @@ class CalibrationQueueFullError(Exception):
"""The queue had no room for all of the run's items, so it took none."""
+class CalibrationModelChangedError(Exception):
+ """A model the run's graph names is not the one it was planned with any more: changed, or removed. The route
+ answers 409 with `code` `model_changed`."""
+
+ code: Final = MODEL_CHANGED
+
+
+class CalibrationAttemptBusyError(Exception):
+ """Another calibration attempt still runs on the GPU's device class. The route answers 409 with `code`
+ `calibration_running`."""
+
+ code: Final = CALIBRATION_RUNNING
+
+
+class CalibrationAttemptInterleavedError(Exception):
+ """Another calibration ran on the GPU's device class after the attempt's first run: its later steps would measure
+ the GPU after that calibration, not after its own earlier steps. The route answers 409 with `code`
+ `calibration_interleaved`."""
+
+ code: Final = CALIBRATION_INTERLEAVED
+
+
+class CalibrationAttemptConflictError(Exception):
+ """The run's attempt_steps differs from that of the run, or of the attempt's other runs, already stored."""
+
+
class CalibrationStoreError(Exception):
"""The store could not be read or written."""
@@ -285,4 +807,8 @@ class CalibrationStoreUnusableError(CalibrationStoreError):
"""The device class's file has an unknown schema or is invalid; it is kept untouched and not written."""
+class CalibrationStoreLockTimeoutError(CalibrationStoreError):
+ """Another holder kept a store lock past `LOCK_TIMEOUT_S`; the same change may pass once it let go."""
+
+
# endregion
diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py
index f5a6e7492f..a4e6779e62 100644
--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py
+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_default.py
@@ -2,36 +2,55 @@ import asyncio
import datetime
import hashlib
import json
+import os
+import threading
import uuid
import weakref
-from collections.abc import AsyncIterator, Callable, Mapping
-from contextlib import ExitStack, asynccontextmanager
+from bisect import bisect_left, bisect_right
+from collections.abc import AsyncIterator, Callable, Iterable, Mapping
+from contextlib import AbstractContextManager, ExitStack, asynccontextmanager
+from dataclasses import dataclass
from functools import partial
from itertools import chain
-from typing import TYPE_CHECKING, Final, NamedTuple, Optional
+from pathlib import Path
+from types import SimpleNamespace
+from typing import TYPE_CHECKING, Any, Final, NamedTuple, Optional
import torch
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
+from invokeai.app.invocations.fields import WithBoard
+from invokeai.app.services.model_records import UnknownModelException
from invokeai.app.services.session_queue.session_queue_common import (
DEFAULT_QUEUE_ID,
QUEUE_ITEM_STATUS,
Batch,
EnqueueIdempotencyConflictError,
QueueItemLineage,
+ RetriedQueueItem,
SessionQueueItem,
SessionQueueItemNotFoundError,
)
+from invokeai.app.services.shared.graph import Graph
from invokeai.app.services.working_memory_calibration.working_memory_calibration_base import (
WorkingMemoryCalibrationServiceBase,
)
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
CALIBRATION_DESTINATION,
CALIBRATION_ORIGIN_PREFIX,
+ MODEL_CHANGED,
STORE_SCHEMA_VERSION,
+ CalibrationAttemptBusyError,
+ CalibrationAttemptConflictError,
+ CalibrationAttemptInterleavedError,
CalibrationDeviceClass,
CalibrationEnvironment,
+ CalibrationErrorCode,
CalibrationGraphError,
+ CalibrationGraphModel,
+ CalibrationHoldBack,
+ CalibrationModelChangedError,
+ CalibrationModelIdentity,
CalibrationPoint,
CalibrationQueueFullError,
CalibrationRun,
@@ -39,11 +58,17 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibration
CalibrationRunStatus,
CalibrationStoreError,
CalibrationStoreFile,
+ CalibrationStoreLockTimeoutError,
CalibrationStoreUnusableError,
CalibrationUnavailableError,
ObservedItem,
+ RemovedAttemptSteps,
+ RetriesInFlight,
WorkingMemoryCalibrationDeviceClass,
WorkingMemoryCalibrationEnvironment,
+ WorkingMemoryCalibrationModelRun,
+ WorkingMemoryCalibrationModelSummary,
+ WorkingMemoryCalibrationPlan,
WorkingMemoryCalibrationPointCount,
WorkingMemoryCalibrationRequest,
WorkingMemoryCalibrationResetResult,
@@ -52,18 +77,38 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibration
WorkingMemoryCalibrationStatus,
calibration_origin,
calibration_run_id,
+ graph_model_identifiers,
+)
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_fits import (
+ HeldBack,
+ measured_models,
+ model_lines,
+ recorded_outside_torch_bytes,
+ run_models,
+ user_fit_of,
+)
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_plan import (
+ VaeDtypes,
+ build_plan,
+ decode_lines_of,
)
from invokeai.app.services.working_memory_calibration.working_memory_calibration_store import (
CalibrationStore,
StoreRead,
)
from invokeai.app.util.misc import uuid_string
+from invokeai.backend.model_manager.load.load_default import resolve_submodel_path
from invokeai.backend.model_manager.taxonomy import SubModelType
+from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder
from invokeai.backend.util.devices import TorchDevice
-from invokeai.backend.working_memory import fingerprint
-from invokeai.backend.working_memory.counters import backend_for
+from invokeai.backend.util.vae_working_memory import dtype_name, estimate_untiled_vae_decode
+from invokeai.backend.working_memory import fingerprint, user_fit
+from invokeai.backend.working_memory.counters import Backend, backend_for, driver_method, method_verified, read_counters
from invokeai.backend.working_memory.fingerprint import DeviceClass, Environment
+from invokeai.backend.working_memory.platform import Platform, platform_for, platform_for_environment
from invokeai.backend.working_memory.probe import MeasuredWindow
+from invokeai.backend.working_memory.spec import EstimatorSpec, import_estimator_modules
+from invokeai.backend.working_memory.user_fit import UserFit
if TYPE_CHECKING:
from invokeai.app.services.invocation_services import InvocationServices
@@ -89,6 +134,29 @@ _RUNNING: Final[frozenset[QUEUE_ITEM_STATUS]] = frozenset({"pending", "in_progre
_RESET: Final = "was reset; a repeat of the request that started it cannot start it again"
+ATTEMPT_IDLE_GRACE: Final = datetime.timedelta(minutes=2)
+"""How long an attempt between its steps stays open (`_attempt_blocks`) after its last activity: its newest run's
+creation, or the latest observation of one of its items. The client posts the next step as soon as the last one
+finished, within seconds; a step that runs long (a large model's largest decode) is running, and its items' last
+observation, as the runner settles them, starts the wait. Past it the attempt is taken for abandoned: a client that
+went away. It no longer blocks another attempt, and it never feeds a fit, being short of steps."""
+
+_RUNNING_ELSEWHERE: Final = (
+ "Another calibration is still running on this GPU. Wait until it has finished, or stop it, then calibrate again."
+)
+
+_BETWEEN_STEPS: Final = (
+ "Another calibration on this GPU is between its steps. Try again in a moment, or once it has finished."
+)
+
+_INTERLEAVED: Final = (
+ "Another calibration ran on this GPU after this calibration started, so its measurements can no longer be "
+ "combined. Calibrate again."
+)
+
+_ATTEMPTS_LOCK: Final = "calibration-attempts"
+"""This process's gate in front of the lock every attempt's creation takes (`_attempt_lock`)."""
+
SettingValue = str | int | float | bool | None
@@ -105,31 +173,84 @@ def _now() -> datetime.datetime:
return datetime.datetime.now(datetime.timezone.utc)
-def _add_env(file: CalibrationStoreFile, env: Environment) -> None:
- if all(known.id != env.id for known in file.envs):
- file.envs.append(CalibrationEnvironment.of(env))
+def _untiled_decode_reservation(estimator: str, height: int, width: int, dtype: str, device: torch.device) -> int:
+ return estimate_untiled_vae_decode(estimator, height, width, dtype, device).reservation_bytes
-def _prune_envs(file: CalibrationStoreFile) -> None:
- used = {run.env_id for run in file.runs} | {point.env_id for point in file.points}
- file.envs = [env for env in file.envs if env.id in used]
+@dataclass(frozen=True)
+class DeviceMemory:
+ """A calibration device's memory as the plan sizes for it, read now."""
+
+ capacity_bytes: int
+ """What the device's model cache can give a calibration's measured lock, the decode's working memory and its VAE
+ together (`ModelCache.calibration_capacity`): with `reserve_vram_gb` and `max_cache_vram_gb` applied, and, on a
+ device that shares system memory (MPS, an integrated XPU), what is allocated there now taken off, since nothing
+ moves out of the way of the lock."""
+ outside_torch_bytes: Optional[int]
+ """What this process holds outside torch's allocator: the driver's figure for it less torch's reserve. None where
+ the counters give no such pair: MPS reads no reserve beside the driver's figure, and XPU's driver figure is
+ device-wide. On a device that shares system memory, the rest of what the process holds is already out of
+ `capacity_bytes`, which counts the RAM the host has available."""
+
+
+def _vae_dtypes(device: torch.device, models_path: Path) -> VaeDtypes:
+ """What the VAE loaders choose on `device`, by the loaders' own rules, for models installed under `models_path`."""
+
+ def sdnq_quantized_vae(config: Any) -> bool:
+ # Where `FluxSDNQDiffusersModel._load_model` looks, with the path the loader makes absolute.
+ pipeline = SimpleNamespace(path=models_path / config.path, submodels=getattr(config, "submodels", None))
+ return is_sdnq_folder(resolve_submodel_path(pipeline, SubModelType.VAE, pipeline.path / SubModelType.VAE.value))
+
+ return VaeDtypes(
+ standalone_flux=dtype_name(TorchDevice.dtype_avoiding_float16(TorchDevice.choose_torch_dtype(device), device)),
+ z_image_pipeline=dtype_name(TorchDevice.choose_bfloat16_safe_dtype(device)),
+ sdnq_quantized_vae=sdnq_quantized_vae,
+ )
-_SUBMODEL_TYPES: Final = frozenset(submodel.value for submodel in SubModelType)
+def _measurement(backend: Optional[Backend]) -> tuple[Optional[str], Optional[bool]]:
+ """The driver reader a window of a `backend` GPU here uses, and whether it is verified; both None for a device
+ class no generation device here belongs to."""
+ if backend is None:
+ return None, None
+ return driver_method(backend), method_verified(backend)
-def measured_models(point: CalibrationPoint, run_models: Mapping[str, str]) -> frozenset[str]:
- """The models a window is attributed to: the model its run calibrated (`run_models`, by run id), and the model it
- measured, where a submodel's window (`<key>:vae`, the model cache's key for it) counts for its model. Resetting
- the model removes exactly these."""
- head, separator, tail = point.model_key.rpartition(":")
- measured = head if separator and tail in _SUBMODEL_TYPES else point.model_key
- run_model = run_models.get(point.run_id)
- return frozenset({measured} if run_model is None else {measured, run_model})
+def _device_key(device: torch.device) -> str:
+ """One name per device, whether or not it carries its index: the cache's devices may come without one."""
+ if device.index is not None or device.type == "cpu":
+ return str(device)
+ index = torch.cuda.current_device() if device.type == "cuda" and torch.cuda.is_available() else 0
+ return f"{device.type}:{index}"
-def run_models(file: CalibrationStoreFile) -> dict[str, str]:
- return {run.run_id: run.model_key for run in file.runs}
+FileSignature = Optional[tuple[int, int, int]]
+"""A store file's mtime, size and inode (file index on Windows), None when it has none. Every write replaces the file,
+so a change shows in at least one of them."""
+
+
+@dataclass(frozen=True)
+class _DeviceFit:
+ """What `refresh_user_fits` found for one generation device, and what it found it from."""
+
+ signature: FileSignature
+ env_id: str
+ platform: Platform
+ fit: Optional[UserFit]
+ file: Optional[CalibrationStoreFile]
+ """The file the fit was made from, kept to re-fit it when only the runs held back changed."""
+ held_back: HeldBack
+ """The runs whose windows the fit left out, and why (`_held_back`)."""
+
+
+def _add_env(file: CalibrationStoreFile, env: Environment) -> None:
+ if all(known.id != env.id for known in file.envs):
+ file.envs.append(CalibrationEnvironment.of(env))
+
+
+def _prune_envs(file: CalibrationStoreFile) -> None:
+ used = {run.env_id for run in file.runs} | {point.env_id for point in file.points}
+ file.envs = [env for env in file.envs if env.id in used]
def _add_points(
@@ -159,14 +280,69 @@ def _add_points(
return True, len(kept)
-def derive_run_status(
- run: CalibrationRun, live: Mapping[int, QueueItemLineage], valid_point_count: int
-) -> tuple[CalibrationRunStatus, Optional[str], list[int]]:
- """A run's status, error and items, from its items: `live` as the queue has them now, the run's own observations
- for items the queue no longer has. An item the queue no longer has counts as canceled unless the runner saw it
- finish. A retry stands in for the item it retried, also before the runner started it. A run that ended without
- completing is partial only with valid points: an invalid one (a canceled or failed operation, a spill) measured
- nothing usable."""
+AttemptKey = tuple[str, str]
+"""An attempt: the owner of its runs and its `attempt_id`. Two owners' attempts never share runs, whatever their ids."""
+
+
+def _attempt_key(run: CalibrationRun) -> Optional[AttemptKey]:
+ return (run.user_id, run.attempt_id) if run.attempt_id is not None else None
+
+
+def _removed_steps(file: CalibrationStoreFile) -> dict[AttemptKey, RemovedAttemptSteps]:
+ return {(record.user_id, record.attempt_id): record for record in file.removed_attempt_steps}
+
+
+def _queued_runs(runs: list[CalibrationRun], removed: Optional[RemovedAttemptSteps]) -> tuple[int, int]:
+ """How many runs the attempt of `runs` queued, those resets removed (`removed`) included, and how many it planned:
+ the `attempt_steps` its runs sent, which the calibrate route keeps the same across them. A run without an attempt
+ plans itself. Runs stored before attempt_steps was sent come only from development builds of this calibration,
+ which never shipped; their attempt is judged on the runs it recorded, as it was then, rather than making their
+ store file unusable."""
+ queued = len(runs) + (removed.removed if removed is not None else 0)
+ steps = {run.attempt_steps for run in runs} | {removed.attempt_steps if removed is not None else None}
+ return queued, max((step for step in steps if step is not None), default=queued)
+
+
+def _note_removed_steps(
+ file: CalibrationStoreFile, removed: list[CalibrationRun], reasons: Mapping[str, Optional[CalibrationHoldBack]]
+) -> None:
+ """Note per attempt what a reset removed of it (`removed_attempt_steps`), once `file.runs` holds the runs left,
+ and drop the notes nothing references any more.
+
+ A removed run counts as queued. Its attempt is marked aborted when it was running (a later step of it may still
+ come, with its earlier ones gone) or aborted (by a canceled item of the removed run, say), as `reasons`
+ (`_hold_reasons`) had it when the reset took the file's lock; a run unknown to them is taken for running. A note
+ stays while a stored run of its attempt is left, or while a later step of it may still come: this reset found the
+ attempt running."""
+ notes = _removed_steps(file)
+ running: set[AttemptKey] = set()
+ for run in removed:
+ if (key := _attempt_key(run)) is None:
+ continue
+ reason = reasons.get(run.run_id, "running")
+ note = notes.get(key)
+ notes[key] = RemovedAttemptSteps(
+ user_id=key[0],
+ attempt_id=key[1],
+ removed=(note.removed if note is not None else 0) + 1,
+ aborted=(note is not None and note.aborted) or reason is not None,
+ attempt_steps=note.attempt_steps
+ if note is not None and note.attempt_steps is not None
+ else run.attempt_steps,
+ )
+ if reason == "running":
+ running.add(key)
+ referenced = {key for run in file.runs if (key := _attempt_key(run)) is not None} | running
+ file.removed_attempt_steps = [note for key, note in notes.items() if key in referenced]
+
+
+def _lineage_outcomes(
+ run: CalibrationRun, live: Mapping[int, QueueItemLineage]
+) -> tuple[list[int], dict[int, QUEUE_ITEM_STATUS]]:
+ """Every item of a run known, and the status of each item that stands for its lineage: the latest retry of an
+ item, or the item itself. `live` as the queue has them now, the run's own observations for items the queue no
+ longer has. An item the queue no longer has counts as canceled unless the runner saw it finish. A retry stands in
+ for the item it retried, also before the runner started it."""
item_ids = sorted(set(run.queue_item_ids) | set(run.observed) | set(live))
def status_of(item_id: int) -> QUEUE_ITEM_STATUS:
@@ -191,21 +367,138 @@ def derive_run_status(
latest[lineage] = max(latest.get(lineage, item_id), item_id)
# A retry names the item it came from, which may be known by nothing else any more.
item_ids = sorted(set(item_ids) | set(latest))
- effective = sorted(latest.values())
- statuses = {item_id: status_of(item_id) for item_id in effective}
+ return item_ids, {item_id: status_of(item_id) for item_id in sorted(latest.values())}
+
+
+def _count_retries(run_ids: frozenset[str], file: CalibrationStoreFile) -> tuple[bool, frozenset[str]]:
+ """A store change: count one more retry in flight on each run of `run_ids` the file holds. Returns those."""
+ counted = frozenset(run.run_id for run in file.runs if run.run_id in run_ids)
+ for run in file.runs:
+ if run.run_id in counted:
+ run.retries_in_flight += 1
+ return bool(counted), counted
+
+
+def _record_committed_retries(
+ run_ids: frozenset[str], retries: Mapping[str, list[tuple[int, int]]], file: CalibrationStoreFile
+) -> tuple[bool, None]:
+ """A store change: on each run of `run_ids` the file still holds, record its retries (`retries`: per run, each
+ retry's item id and the item its lineage started from) pending, and count one retry in flight less. A retry the
+ runner already admitted keeps that observation."""
+ changed = False
+ for run in file.runs:
+ if run.run_id not in run_ids:
+ continue
+ changed = True
+ run.retries_in_flight = max(0, run.retries_in_flight - 1)
+ for item_id, started_from in retries.get(run.run_id, []):
+ if item_id not in run.observed:
+ run.observed[item_id] = ObservedItem(
+ status="pending", retried_from_item_id=started_from, observed_at=_now()
+ )
+ return changed, None
- if not effective:
- return "canceled", None, item_ids
+
+def _last_activity(runs: Iterable[CalibrationRun]) -> datetime.datetime:
+ """When an attempt last did something: its newest run's creation, or the latest observation of its items."""
+ return max(
+ chain(
+ (run.created_at for run in runs),
+ (observed.observed_at for run in runs for observed in run.observed.values()),
+ )
+ )
+
+
+def _cut_off(file: CalibrationStoreFile, key: AttemptKey) -> bool:
+ """Whether another run (another attempt's, or one without an attempt: a script, the family E2E tool) was created
+ on the device class after the first run of attempt `key`: a later step of it would measure the GPU after that run,
+ so none is accepted (`CalibrationAttemptInterleavedError`)."""
+ own = [run.created_at for run in file.runs if _attempt_key(run) == key]
+ return bool(own) and any(_attempt_key(run) != key and run.created_at > min(own) for run in file.runs)
+
+
+def _interleaved_attempts(file: CalibrationStoreFile) -> set[AttemptKey]:
+ """The attempts another run was created between the first and the last run of: their later steps measured the GPU
+ after that run, not after their own earlier steps. The calibrate route refuses such a step
+ (`CalibrationAttemptInterleavedError`), so only a store written otherwise holds one."""
+ created = sorted(run.created_at for run in file.runs)
+ spans: dict[AttemptKey, list[datetime.datetime]] = {}
+ for run in file.runs:
+ if (key := _attempt_key(run)) is not None:
+ spans.setdefault(key, []).append(run.created_at)
+ interleaved: set[AttemptKey] = set()
+ for key, times in spans.items():
+ first, last = min(times), max(times)
+ between = bisect_left(created, last) - bisect_right(created, first)
+ if between > sum(1 for time in times if first < time < last):
+ interleaved.add(key)
+ return interleaved
+
+
+def _interrupts(run: CalibrationRun, item_id: int, status: QUEUE_ITEM_STATUS) -> bool:
+ """Whether the item that stands for a lineage of `run` interrupted its attempt: canceled, or failed at admission
+ because a model changed after the calibration was planned."""
+ if status == "canceled":
+ return True
+ observed = run.observed.get(item_id)
+ return status == "failed" and observed is not None and observed.error_code == MODEL_CHANGED
+
+
+class RunStatus(NamedTuple):
+ status: CalibrationRunStatus
+ error: Optional[str]
+ error_code: Optional[CalibrationErrorCode]
+ item_ids: list[int]
+
+
+def derive_run_status(run: CalibrationRun, live: Mapping[int, QueueItemLineage], valid_point_count: int) -> RunStatus:
+ """A run's status, error (with its code, where the runner gave one) and items, from its items
+ (`_lineage_outcomes`). A failed item decides over a canceled one. A run that ended without completing is partial
+ only with valid points: an invalid one (a canceled or failed operation, a spill) measured nothing usable."""
+ item_ids, statuses = _lineage_outcomes(run, live)
+ if not statuses:
+ return RunStatus("canceled", None, None, item_ids)
if any(status in _RUNNING for status in statuses.values()):
- return "running", None, item_ids
+ return RunStatus("running", None, None, item_ids)
failed = [item_id for item_id, status in statuses.items() if status == "failed"]
if failed:
observed = run.observed.get(failed[0])
error = observed.error_message if observed is not None and observed.error_message else None
- return "failed", error or f"Queue item {failed[0]} failed", item_ids
+ code = observed.error_code if observed is not None else None
+ return RunStatus("failed", error or f"Queue item {failed[0]} failed", code, item_ids)
if all(status == "completed" for status in statuses.values()):
- return "completed", None, item_ids
- return ("partial" if valid_point_count > 0 else "canceled"), None, item_ids
+ return RunStatus("completed", None, None, item_ids)
+ return RunStatus("partial" if valid_point_count > 0 else "canceled", None, None, item_ids)
+
+
+def _model_identity(config: Any) -> CalibrationModelIdentity:
+ def name(field: object) -> Optional[str]:
+ return None if field is None else str(getattr(field, "value", field))
+
+ return CalibrationModelIdentity(
+ base=name(getattr(config, "base", None)),
+ type=name(getattr(config, "type", None)),
+ format=name(getattr(config, "format", None)),
+ variant=name(getattr(config, "variant", None)),
+ )
+
+
+def _graph_model(config: Any) -> CalibrationGraphModel:
+ return CalibrationGraphModel(**_model_identity(config).model_dump(), hash=getattr(config, "hash", None))
+
+
+def _changed(name: str, facts: Iterable[str]) -> str:
+ return f"{name} changed after this calibration was planned ({', '.join(facts)}). Calibrate again."
+
+
+def _identity_changes(run: CalibrationRun, model_hash: Optional[str], identity: CalibrationModelIdentity) -> list[str]:
+ """What differs between the model `run` recorded at its creation and one of `model_hash` and `identity`: the hash,
+ and, for a run that recorded its identity (runs stored before it compare the hash alone), base, type, format and
+ variant."""
+ recorded = run.model_identity.model_dump() if run.model_identity is not None else {}
+ current = identity.model_dump()
+ facts = [fact for fact, value in recorded.items() if current[fact] != value]
+ return (["hash"] if model_hash != run.model_hash else []) + facts
class _Enqueue(NamedTuple):
@@ -221,8 +514,9 @@ class _Enqueue(NamedTuple):
class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
"""Calibration runs and their store.
- `generation_devices`, `device_class_for` and `environment_for` default to the machine's own; tests pass their own
- because a device class can only be read from real hardware.
+ `generation_devices`, `device_class_for`, `environment_for`, `untiled_decode_reservation`, `device_memory` and
+ `vae_dtypes` default to the machine's own; tests pass their own because a device class, its memory and the dtypes
+ it supports can only be read from real hardware.
"""
def __init__(
@@ -234,11 +528,17 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
environment_for: Callable[
[torch.device, Mapping[str, SettingValue]], Environment
] = fingerprint.environment_for,
+ untiled_decode_reservation: Callable[[str, int, int, str, torch.device], int] = _untiled_decode_reservation,
+ device_memory: Optional[Callable[[torch.device], DeviceMemory]] = None,
+ vae_dtypes: Callable[[torch.device, Path], VaeDtypes] = _vae_dtypes,
) -> None:
self._store = store
self._generation_devices = generation_devices
self._device_class_for = device_class_for
self._environment_for = environment_for
+ self._untiled_decode_reservation = untiled_decode_reservation
+ self._device_memory = device_memory or self._cache_memory
+ self._vae_dtypes = vae_dtypes
# A card's class cannot change while the process runs; reading it touches the driver.
self._device_classes: dict[str, DeviceClass] = {}
# Which file holds a run, so admitting an item and recording its windows do not scan every file.
@@ -248,9 +548,23 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
# Per run id while a creation of this process uses it, in front of the file lock (see `_creation_lock`).
self._run_gates: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()
self._invoker: Optional["Invoker"] = None
+ # The user fit per generation device: replaced whole by `refresh_user_fits`, read by every estimate.
+ self._fits: Mapping[str, _DeviceFit] = {}
+ self._fits_lock = threading.Lock()
+ # The status of each calibration item `_canceled_runs` found finished in the queue, per run and item id: a
+ # finished item never changes, so an entry holds until its run is removed (`_forget`). Keyed by the run too: a
+ # recreated or restored database numbers its items anew, and two runs can then record one id. Read and written
+ # under `_fits_lock`.
+ self._item_outcomes: dict[tuple[str, int], QUEUE_ITEM_STATUS] = {}
+ # One object, so that `stop` unregisters exactly what `start` registered.
+ self._provider: user_fit.UserFitProvider = self._user_fit_for
def start(self, invoker: "Invoker") -> None:
self._invoker = invoker
+ user_fit.set_user_fit_provider(self._provider)
+
+ def stop(self, invoker: "Invoker") -> None:
+ user_fit.clear_user_fit_provider(self._provider)
@property
def _services(self) -> "InvocationServices":
@@ -317,14 +631,15 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
@staticmethod
def _identify(model_key: str, request: WorkingMemoryCalibrationRequest, user_id: str) -> str:
- """Check the request's graph and turn its node cache off, then return the run's id, which also becomes the
- graph's id.
-
- Without a retry key the id is fresh. With one it is derived from the owner, the key and the request's
- fingerprint: the model and the batch the server builds (graph and batch data). A repeat of the request finds
- its run by that id, and another request reusing the key gets another id. The id is part of the batch's
- origin, so the queue's receipt for the key refuses that other request. The client's graph id is not part of
- the request: a graph sent without one gets a fresh id each time, so a repeat could never match.
+ """Check the request's graph, turn its node cache off and make every node's output an intermediate on no
+ board, then return the run's id, which also becomes the graph's id.
+
+ Without a retry key the id is fresh. With one it is derived from the owner, the key, the request's
+ fingerprint (the model and the batch the server builds: graph and batch data) and the client's attempt, if it
+ names one. A repeat of the request finds its run by that id, and another request reusing the key, another
+ attempt included, gets another id. The id is part of the batch's origin, so the queue's receipt for the key
+ refuses that other request. The client's graph id is not part of the request: a graph sent without one gets a
+ fresh id each time, so a repeat could never match.
"""
graph = request.graph
for node in graph.nodes.values():
@@ -338,9 +653,20 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
raise CalibrationGraphError(
f"Batch data sets use_cache on node {datum.node_path}; calibration runs every node uncached."
)
- # A cached output would skip the very operation the run measures.
+ # A board cannot come as batch data: batch items are strings, numbers, images and videos.
+ if datum.field_name == "is_intermediate":
+ raise CalibrationGraphError(
+ f"Batch data sets is_intermediate on node {datum.node_path}; a calibration's images are "
+ "intermediates."
+ )
for node in graph.nodes.values():
+ # A cached output would skip the very operation the run measures.
node.use_cache = False
+ # Its images are measurement by-products: never in the gallery or on a board; clearing intermediates
+ # removes them. A node saves with its own flag and its `WithBoard` board.
+ node.is_intermediate = True
+ if isinstance(node, WithBoard):
+ node.board = None
if request.idempotency_key is None:
run_id = uuid_string()
else:
@@ -354,7 +680,9 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
digest = hashlib.sha256(
json.dumps(fingerprint, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
).hexdigest()
- run_id = str(uuid.uuid5(_RUN_ID_NAMESPACE, f"{user_id}\x00{request.idempotency_key}\x00{digest}"))
+ # Appended only with an attempt: a request without one keeps the id it had before attempts existed.
+ attempt = f"\x00{request.attempt_id}" if request.attempt_id is not None else ""
+ run_id = str(uuid.uuid5(_RUN_ID_NAMESPACE, f"{user_id}\x00{request.idempotency_key}\x00{digest}{attempt}"))
# The queue's receipt hashes the batch, graph id included: a repeat must build the same one.
graph.id = run_id
return run_id
@@ -371,13 +699,31 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
if not _is_keyed(run_id):
yield
return
- gate = self._run_gates.get(run_id)
+ async with self._file_lock(run_id, partial(self._store.creation_lock, run_id)):
+ yield
+
+ @asynccontextmanager
+ async def _attempt_lock(self, request: WorkingMemoryCalibrationRequest) -> AsyncIterator[None]:
+ """For a run of an attempt, hold the lock every attempt's creation takes, from the run's record through its
+ enqueue to the record of its items, in every process serving the root: the next attempt's creation finds the
+ items of the last one in the queue, and refuses while they run (`CalibrationAttemptBusyError`). The runs of one
+ attempt are posted one after the other, so they barely wait. A run without an attempt takes no lock."""
+ if request.attempt_id is None:
+ yield
+ return
+ async with self._file_lock(_ATTEMPTS_LOCK, self._store.attempts_lock):
+ yield
+
+ @asynccontextmanager
+ async def _file_lock(self, name: str, os_lock: Callable[[], AbstractContextManager[None]]) -> AsyncIterator[None]:
+ """Hold the store's OS lock `os_lock`, behind this process's gate `name` for it (`_creation_lock`)."""
+ gate = self._run_gates.get(name)
if gate is None:
- gate = self._run_gates[run_id] = asyncio.Lock()
+ gate = self._run_gates[name] = asyncio.Lock()
async with gate:
held = ExitStack()
# A file lock: taken in a worker thread, which waits for another holder without blocking the loop.
- acquiring = asyncio.ensure_future(asyncio.to_thread(held.enter_context, self._store.creation_lock(run_id)))
+ acquiring = asyncio.ensure_future(asyncio.to_thread(held.enter_context, os_lock()))
try:
await asyncio.shield(acquiring)
except asyncio.CancelledError:
@@ -415,9 +761,9 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
self, model_key: str, request: WorkingMemoryCalibrationRequest, user_id: str
) -> WorkingMemoryCalibrationRunCreated:
run_id = await asyncio.to_thread(self._identify, model_key, request, user_id)
- # Recording the run, enqueuing its batch and recording its items or removing it: one step for each run id, in
- # every process serving the root.
- async with self._creation_lock(run_id):
+ # Recording the run, enqueuing its batch and recording its items or removing it: one step for each run id, and
+ # for every attempt, in every process serving the root.
+ async with self._attempt_lock(request), self._creation_lock(run_id):
prepared = await asyncio.to_thread(self._prepare_run, model_key, request, user_id, run_id)
if isinstance(prepared, WorkingMemoryCalibrationRunCreated):
return prepared
@@ -485,6 +831,12 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
found: Optional[tuple[str, CalibrationRun]] = None
if key is not None and (found := self._find_run(run_id)) is not None:
device_class_id, run = found
+ # The run id does not derive from attempt_steps: a repeat that changes it is another request.
+ if run.attempt_steps != request.attempt_steps:
+ raise CalibrationAttemptConflictError(
+ f"Calibration run {run_id} plans {run.attempt_steps} runs for attempt {run.attempt_id}, and the "
+ f"repeat of its request {request.attempt_steps}"
+ )
if run.queue_item_ids:
return WorkingMemoryCalibrationRunCreated(
run_id=run_id, device_class_id=device_class_id, item_ids=list(run.queue_item_ids)
@@ -526,12 +878,24 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
device = self._calibration_device()
# Raises UnknownModelException for an unknown key.
config = self._services.model_manager.store.get_model(model_key)
+ changed, graph_configs = self._changed_models(request.graph, request.graph_models)
+ if changed is not None:
+ raise CalibrationModelChangedError(changed)
+ # The records the comparison found as the client compiled the graph against them: what the run records.
+ config = graph_configs.get(model_key, config)
+ graph_models = {key: _graph_model(graph_config) for key, graph_config in graph_configs.items()}
batch = self._batch(request, run_id)
if found is not None:
+ # The run id does not derive from graph_models: a repeat may state other identities than the run recorded,
+ # and its item would fail at admission. A run stored without some of them compares the rest.
+ for key, recorded in found[1].graph_models.items():
+ if (stated := request.graph_models.get(key)) is not None and (facts := recorded.changes(stated)):
+ raise CalibrationModelChangedError(_changed(getattr(graph_configs[key], "name", key), facts))
# The run is recorded without items and unmarked, and nothing of it is queued: enqueue its batch.
return _Enqueue(batch, found[0], created=False, marks=True)
device_class = self._device_class(device)
env = self._environment(device)
+ run_identity = _model_identity(config)
run = CalibrationRun(
run_id=run_id,
model_key=model_key,
@@ -539,6 +903,11 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
user_id=user_id,
created_at=_now(),
env_id=env.id,
+ attempt_id=request.attempt_id,
+ attempt_steps=request.attempt_steps,
+ soft=env.soft,
+ model_identity=run_identity,
+ graph_models=graph_models,
# Marked as it is recorded: the enqueue follows, and nothing else is written in between.
enqueue_attempted=True,
)
@@ -548,14 +917,143 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
raise CalibrationRunNotFoundError(run_id, _RESET)
if any(known.run_id == run_id for known in file.runs):
return False, False
+ if (key := _attempt_key(run)) is not None:
+ if _cut_off(file, key):
+ # Its next step would measure the GPU after that other calibration: the attempt stays short, and
+ # so aborted.
+ raise CalibrationAttemptInterleavedError(_INTERLEAVED)
+ # The queue is read under the file's lock; the queue takes it only outside its transactions.
+ if (busy := self._attempt_blocks(file, key)) is not None:
+ raise CalibrationAttemptBusyError(busy)
+ # The attempt's earlier steps measured the models as they were then: the model calibrated, and every
+ # model their graphs named, hash included, which a graph compiled since names as it is now.
+ for known in file.runs:
+ if _attempt_key(known) != key:
+ continue
+ if known.model_key == model_key and (
+ facts := _identity_changes(known, run.model_hash, run_identity)
+ ):
+ raise CalibrationModelChangedError(_changed(getattr(config, "name", model_key), facts))
+ for named, recorded in known.graph_models.items():
+ if named in graph_models and (facts := recorded.changes(graph_models[named])):
+ raise CalibrationModelChangedError(
+ _changed(getattr(graph_configs[named], "name", named), facts)
+ )
+ # Under the file's lock: two runs of one attempt that plan different counts cannot both be recorded.
+ planned = {known.attempt_steps for known in file.runs if _attempt_key(known) == key}
+ if (removed := _removed_steps(file).get(key)) is not None:
+ planned.add(removed.attempt_steps)
+ if planned - {request.attempt_steps}:
+ raise CalibrationAttemptConflictError(
+ f"Attempt {request.attempt_id} plans {', '.join(sorted(map(str, planned)))} runs, and this "
+ f"run of it {request.attempt_steps}: every run of an attempt sends the same attempt_steps"
+ )
file.runs.append(run)
_add_env(file, env)
return True, True
- created = bool(self._store.change(device_class.id, add, create=CalibrationDeviceClass.of(device_class)))
+ # The attempt check judges other runs' items (`_attempt_blocks`) under the lock that orders those judgements
+ # with removals, taken before the file's lock as every holder of both takes them.
+ with self._fits_lock:
+ created = bool(self._store.change(device_class.id, add, create=CalibrationDeviceClass.of(device_class)))
self._run_files[run_id] = device_class.id
return _Enqueue(batch, device_class.id, created=created, marks=created)
+ def _attempt_blocks(self, file: CalibrationStoreFile, key: AttemptKey) -> Optional[str]:
+ """Why another attempt than `key` holds the device class, or None: one of its runs is running (an item pending,
+ in progress or waiting), or another owner's attempt is open. One attempt runs on a device class at a time: its
+ runs measure the GPU back to back, each step on what the last one left, and another attempt's items in between
+ would measure neither.
+
+ Open: between its steps, short of `attempt_steps` runs (those resets removed included), not aborted (no item
+ of it canceled or failed for a changed model, no reset that stopped it, no other run since its first), its
+ model as its runs recorded it (`_can_continue`: a later step would be refused otherwise), and active within
+ `ATTEMPT_IDLE_GRACE`. Past that it is taken for abandoned and blocks nothing; it can never feed a fit, being
+ short. The owner's own open attempt blocks nothing: its client posts each step as soon as the last one
+ finished, so an open attempt is almost always one whose submission stopped partway (a full queue, a lost
+ connection, a closed tab), and its owner's new attempt replaces it. The replaced attempt stays short, so
+ aborted, and a later step of it is refused (`_cut_off`).
+
+ The grace is measured on the stored times against the clock now: a jump of the wall clock lengthens or
+ shortens it once."""
+ origins = self._services.session_queue.get_unfinished_origins(DEFAULT_QUEUE_ID, CALIBRATION_ORIGIN_PREFIX)
+ running = {run_id for origin in origins if (run_id := calibration_run_id(origin)) is not None}
+ attempts: dict[AttemptKey, list[CalibrationRun]] = {}
+ for run in file.runs:
+ if (other := _attempt_key(run)) is not None and other != key:
+ attempts.setdefault(other, []).append(run)
+ notes = _removed_steps(file)
+ interleaved = _interleaved_attempts(file)
+ now = _now()
+ between_steps: list[list[CalibrationRun]] = []
+ for other, runs in attempts.items():
+ if any(run.run_id in running for run in runs):
+ return _RUNNING_ELSEWHERE
+ removed = notes.get(other)
+ queued, planned = _queued_runs(runs, removed)
+ if (
+ other[0] == key[0]
+ or queued >= planned
+ or (removed is not None and removed.aborted)
+ or other in interleaved
+ or _cut_off(file, other)
+ ):
+ continue
+ if now - _last_activity(runs) <= ATTEMPT_IDLE_GRACE and self._can_continue(runs):
+ between_steps.append(runs)
+ if not between_steps:
+ return None
+ canceled, started = self._canceled_runs([run for runs in between_steps for run in runs])
+ for runs in between_steps:
+ if any(run.run_id in started for run in runs):
+ return _RUNNING_ELSEWHERE
+ if not any(run.run_id in canceled for run in runs):
+ return _BETWEEN_STEPS
+ return None
+
+ def _can_continue(self, runs: list[CalibrationRun]) -> bool:
+ """Whether a later step of the attempt of `runs` could still be accepted as far as its model goes: its newest
+ run's model is still installed as that run recorded it. Otherwise every later step is refused
+ (`CalibrationModelChangedError`), and the attempt holds nothing open."""
+ newest = max(runs, key=lambda run: run.created_at)
+ try:
+ config = self._services.model_manager.store.get_model(newest.model_key)
+ except UnknownModelException:
+ return False
+ return not _identity_changes(newest, getattr(config, "hash", None), _model_identity(config))
+
+ def _changed_models(
+ self, graph: Graph, expected: Mapping[str, CalibrationGraphModel]
+ ) -> tuple[Optional[str], dict[str, Any]]:
+ """Why a model the graph names is not the one the graph was compiled against any more, or None; and the record
+ of each of the graph's models this comparison read, once per key. Changed: its record is gone, or names another
+ hash, base or type than the graph does, or, for one in `expected`, another hash, base, type, format or variant
+ than that names. `expected` is the request's `graph_models` at the run's creation (the client's compiled
+ identities, one per model the graph names) and the run's `graph_models` at admission."""
+ store = self._services.model_manager.store
+ configs: dict[str, Any] = {}
+ for named in graph_model_identifiers(graph):
+ config = configs.get(named.key)
+ if config is None:
+ try:
+ config = configs[named.key] = store.get_model(named.key)
+ except UnknownModelException:
+ return f"{named.name} was removed after this calibration was planned. Calibrate again.", configs
+ facts = [
+ fact
+ for fact, planned, current in (
+ ("hash", named.hash, getattr(config, "hash", None)),
+ ("base", str(named.base.value), str(getattr(config.base, "value", config.base))),
+ ("type", str(named.type.value), str(getattr(config.type, "value", config.type))),
+ )
+ if planned != current
+ ]
+ if (identity := expected.get(named.key)) is not None:
+ facts += [fact for fact in identity.changes(_graph_model(config)) if fact not in facts]
+ if facts:
+ return _changed(named.name, facts), configs
+ return None, configs
+
@staticmethod
def _batch(request: WorkingMemoryCalibrationRequest, run_id: str) -> Batch:
try:
@@ -588,7 +1086,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
have queued the batch."""
try:
if created:
- self._remove_run(run_id, remember=False)
+ self._remove_run(run_id, reset=False)
elif marks:
self._set_enqueue_attempted(device_class_id, run_id, False)
except Exception:
@@ -634,12 +1132,26 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
found = self._find_run(run_id)
if found is None:
return f"Calibration run {run_id} does not exist; it was reset or never created."
- device_class_id, _ = found
+ device_class_id, run = found
if device_class_id != self._device_class(device).id:
return (
f"Calibration run {run_id} was created for device class {device_class_id}, and this machine's GPU "
f"is of class {self._device_class(device).id}."
)
+ if (changed := self._model_changed_since(run, queue_item)) is not None:
+ # The code reaches the run's summary: the observation the runner records next keeps it.
+ self._observe(
+ run_id,
+ queue_item.item_id,
+ ObservedItem(
+ status="failed",
+ error_message=changed,
+ error_code=MODEL_CHANGED,
+ retried_from_item_id=queue_item.retried_from_item_id,
+ observed_at=_now(),
+ ),
+ )
+ return changed
self._observe(
run_id,
queue_item.item_id,
@@ -649,6 +1161,20 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
)
return None
+ def _model_changed_since(self, run: CalibrationRun, queue_item: SessionQueueItem) -> Optional[str]:
+ """Why the item would not measure the model its run was planned with, or None: the run's model is gone, or its
+ hash, base, type, format or variant changed since the run was created; or a model the graph names changed
+ since it was compiled (`_changed_models`). Runs stored before the rest was recorded compare the hash alone."""
+ try:
+ config = self._services.model_manager.store.get_model(run.model_key)
+ except UnknownModelException:
+ return f"Model {run.model_key} was removed after this calibration was planned. Calibrate again."
+ facts = _identity_changes(run, getattr(config, "hash", None), _model_identity(config))
+ if facts:
+ return _changed(getattr(config, "name", run.model_key), facts)
+ session = getattr(queue_item, "session", None)
+ return self._changed_models(session.graph, run.graph_models)[0] if session is not None else None
+
def _observe(self, run_id: str, item_id: int, observation: ObservedItem) -> None:
found = self._find_run(run_id)
if found is None:
@@ -658,13 +1184,14 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
for run in file.runs:
if run.run_id == run_id:
previous = run.observed.get(item_id)
- if observation.retried_from_item_id is None and previous is not None:
- observation_ = observation.model_copy(
- update={"retried_from_item_id": previous.retried_from_item_id}
- )
- else:
- observation_ = observation
- run.observed[item_id] = observation_
+ # A later observation keeps what an earlier one knew and it does not: the item's lineage, and why
+ # admission failed it.
+ kept = {
+ field: getattr(previous, field)
+ for field in ("retried_from_item_id", "error_code")
+ if previous is not None and getattr(observation, field) is None
+ }
+ run.observed[item_id] = observation.model_copy(update=kept) if kept else observation
return True, None
return False, None
@@ -716,6 +1243,73 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
),
)
+ def retries_starting(self, sources: Mapping[int, tuple[Optional[str], int]]) -> Optional[RetriesInFlight]:
+ """Count a retry in flight on each run one of whose items the queue is about to retry, before it commits the
+ retries: the store then records every retry of a calibration item, or keeps its attempt out of every fit.
+
+ A retry inherits its source's origin, which names the run: a recreated or restored database that gave a
+ recorded id to an unrelated item cannot make that item's retry the run's, and a bulk retry of generations
+ touches no store file. A run no usable file holds (a reset removed it) is not counted; its retries fail at
+ admission. Raises when a file cannot be written; what was counted is counted down again first."""
+ lineages = {
+ source_item_id: (run_id, started_from)
+ for source_item_id, (origin, started_from) in sources.items()
+ if (run_id := calibration_run_id(origin)) is not None
+ }
+ if not lineages:
+ return None
+ run_ids = frozenset(run_id for run_id, _ in lineages.values())
+ counted: dict[str, frozenset[str]] = {}
+ try:
+ for device_class_id in self._store.device_class_ids():
+ try:
+ marked = self._store.change(device_class_id, partial(_count_retries, run_ids))
+ except CalibrationStoreUnusableError:
+ # Kept as it is and never written: it holds no run a calibration item can be admitted for.
+ continue
+ if marked:
+ counted[device_class_id] = marked
+ except Exception:
+ # The queue retries nothing.
+ self.retries_committed(RetriesInFlight(runs=counted, lineages=lineages), [])
+ raise
+ return RetriesInFlight(runs=counted, lineages=lineages) if counted else None
+
+ def retries_committed(self, in_flight: RetriesInFlight, retried: Optional[Iterable[RetriedQueueItem]]) -> None:
+ """Record each retry the queue committed on its run, pending and standing for the item its lineage started
+ from, as the queue links it, and count the run's retries in flight down; for a run none of whose items the
+ queue had room to retry, or whose retry rolled back, only count down. `retried` None: the queue failed at or
+ after its commit, which may have committed all the same, so which retries exist is unknown. The count then
+ stays, and is logged.
+
+ One change per store file, tried once more after a lock timeout. A file that still cannot be written is
+ logged and keeps its count. A count left over keeps the attempts of the file's counted runs out of every fit
+ until a reset removes them, since a retry of theirs may exist that the store does not record."""
+ if retried is None:
+ self._services.logger.warning(
+ "Retrying the items of calibration runs "
+ f"{', '.join(sorted(chain.from_iterable(in_flight.runs.values())))} failed at its commit, which may "
+ "have committed; their attempts no longer feed a fit"
+ )
+ return
+ retries: dict[str, list[tuple[int, int]]] = {}
+ for retry in retried:
+ if (lineage := in_flight.lineages.get(retry.source_item_id)) is not None:
+ retries.setdefault(lineage[0], []).append((retry.item_id, lineage[1]))
+ for device_class_id, run_ids in in_flight.runs.items():
+ change = partial(self._store.change, device_class_id, partial(_record_committed_retries, run_ids, retries))
+ try:
+ try:
+ change()
+ except CalibrationStoreLockTimeoutError:
+ change()
+ except Exception:
+ self._services.logger.warning(
+ f"Could not record the retries of calibration runs {', '.join(sorted(run_ids))}; their attempts "
+ "no longer feed a fit",
+ exc_info=True,
+ )
+
def model_reset_epochs(self, run_id: str) -> dict[str, int]:
found = self._find_run(run_id)
if found is None:
@@ -785,6 +1379,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
unavailable = str(error)
live = self._live_items()
+ present = self._present_backends()
device_class_ids = set(self._store.device_class_ids())
if current_class is not None:
device_class_ids.add(current_class.id)
@@ -805,7 +1400,9 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
if problem is not None:
unavailable = f"The calibration store of this GPU's device class cannot be written: {problem}"
device_classes.append(
- self._device_class_status(read, is_current, current_env if is_current else None, live)
+ self._device_class_status(
+ read, is_current, current_env if is_current else None, live, present.get(device_class_id)
+ )
)
return WorkingMemoryCalibrationStatus(
available=unavailable is None,
@@ -821,7 +1418,9 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
is_current: bool,
current_env: Optional[Environment],
live: Mapping[str, Mapping[int, QueueItemLineage]],
+ backend: Optional[Backend],
) -> WorkingMemoryCalibrationDeviceClass:
+ method, verified = _measurement(backend)
file = read.file
if file is None:
return WorkingMemoryCalibrationDeviceClass(
@@ -830,6 +1429,8 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
usable=False,
problem=read.problem,
is_current=is_current,
+ measurement_method=method,
+ measurement_verified=verified,
runs=[],
point_counts=[],
envs=[],
@@ -848,7 +1449,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
runs = []
for run in file.runs:
point_count = points_per_run.get(run.run_id, 0)
- status, error, item_ids = derive_run_status(
+ status, error, error_code, item_ids = derive_run_status(
run, live.get(run.run_id, {}), valid_points_per_run.get(run.run_id, 0)
)
runs.append(
@@ -861,8 +1462,11 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
env_id=run.env_id,
status=status,
error=error,
+ error_code=error_code,
item_ids=item_ids,
point_count=point_count,
+ attempt_id=run.attempt_id,
+ attempt_steps=run.attempt_steps,
)
)
envs = [
@@ -882,6 +1486,8 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
usable=True,
problem=None,
is_current=is_current,
+ measurement_method=method,
+ measurement_verified=verified,
runs=runs,
point_counts=[
WorkingMemoryCalibrationPointCount(
@@ -894,20 +1500,412 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
# endregion
+ # region User fits
+
+ def _user_fit_for(self, spec: EstimatorSpec, platform: Platform, device: torch.device) -> Optional[UserFit]:
+ """What estimates ask (`user_fit.user_fit_for`): a lookup in memory, no file or device access."""
+ found = self._fits.get(_device_key(device))
+ if found is None or found.platform != platform:
+ return None
+ return found.fit
+
+ @staticmethod
+ def _signature(path: str) -> FileSignature:
+ try:
+ stat = os.stat(path)
+ except FileNotFoundError:
+ return None
+ return stat.st_mtime_ns, stat.st_size, stat.st_ino
+
+ def refresh_user_fits(self) -> None:
+ with self._fits_lock:
+ fits: dict[str, _DeviceFit] = {}
+ for device in self._devices():
+ if backend_for(device) is None:
+ continue
+ device_class = self._device_class(device)
+ env = self._environment(device)
+ platform = platform_for(device)
+ signature = self._signature(str(self._store.path_for(device_class.id)))
+ key = _device_key(device)
+ known = self._fits.get(key)
+ file: Optional[CalibrationStoreFile] = None
+ held_back: Optional[HeldBack] = None
+ if known is not None and (known.signature, known.env_id, known.platform) == (
+ signature,
+ env.id,
+ platform,
+ ):
+ if known.file is None:
+ fits[key] = known
+ continue
+ # The same file: only the queue (an item that finished, a retry queued) can change the runs it
+ # leaves out.
+ held_back = self._held_back(known.file)
+ if held_back == known.held_back:
+ fits[key] = known
+ continue
+ file = known.file
+ elif signature is not None:
+ read = self._store.read(device_class.id)
+ if read is not None and read.file is None:
+ self._services.logger.warning(
+ f"Working-memory estimates on {device} keep the shipped values: {read.problem}"
+ )
+ file = read.file if read is not None else None
+ if held_back is None:
+ held_back = self._held_back(file) if file is not None else {}
+ fit = user_fit_of(file, env.id, platform, held_back=held_back)[0] if file is not None else None
+ fits[key] = _DeviceFit(
+ signature=signature, env_id=env.id, platform=platform, fit=fit, file=file, held_back=held_back
+ )
+ self._fits = fits
+
+ def _held_back(self, file: CalibrationStoreFile) -> dict[str, CalibrationHoldBack]:
+ """The runs whose windows no fit takes, and why, judged per attempt (an owner's `attempt_id`, `AttemptKey`; a
+ run without one is an attempt of its own):
+
+ - running: the queue holds an item of one of the attempt's runs that is pending, in progress or waiting. An
+ item carries its run's origin from the moment it is queued, before the run records it or the runner admits
+ it, and so does a retry: a run that failed holds its windows back again while its retry waits, and stops once
+ the retry finished or was canceled or removed. A client posts each step of an attempt as its own run: the
+ finished earlier steps must not price the later, larger ones either.
+ - aborted_attempt: none of its runs is running, and the attempt (one owner's `attempt_id`) was aborted. Either
+ an item of it ended canceled (`_canceled_runs`: Stop cancels what the queue still holds, and a queue clear
+ removes it); or it queued fewer runs than it planned (`_queued_runs`): Stop, or a submission that failed,
+ ended it before it queued them all; or a reset removed a run of it while it ran or after it was aborted
+ (`RemovedAttemptSteps.aborted`); or another run was created between its first and its last
+ (`_interleaved_attempts`); or a retry of one of its items may exist that the store does not record
+ (`retries_in_flight` left over: the server stopped, or the store could not be written, between the retry's
+ commit and its record). Either way it measured only some of its sizes, measured them around another
+ calibration, or cannot be told complete, and it never feeds a fit. A step not posted yet looks the same until
+ it is. An item that failed (an out-of-memory error at the largest
+ size) ends that step, not the attempt. A run without an attempt is never aborted: canceled, it feeds what it
+ measured, as before.
+
+ A run a reset removed counts as queued (`removed_attempt_steps`), so removing a run of a finished attempt
+ discards only its own points.
+
+ One read of the queue per call (`get_unfinished_origins`), which costs the queue's unfinished items, not its
+ history; and the reads by id `_canceled_runs` makes. None for a file without runs."""
+ if not file.runs:
+ return {}
+ origins = self._services.session_queue.get_unfinished_origins(DEFAULT_QUEUE_ID, CALIBRATION_ORIGIN_PREFIX)
+ # The queue's origin filter ignores case; only the exact prefix is the server's.
+ running = {run_id for origin in origins if (run_id := calibration_run_id(origin)) is not None}
+ attempts: dict[tuple[Optional[AttemptKey], str], list[CalibrationRun]] = {}
+ for run in file.runs:
+ key = _attempt_key(run)
+ attempts.setdefault((key, "" if key is not None else run.run_id), []).append(run)
+ notes = _removed_steps(file)
+ interleaved = _interleaved_attempts(file)
+ held_back: dict[str, CalibrationHoldBack] = {}
+
+ def hold(runs: list[CalibrationRun], reason: CalibrationHoldBack) -> None:
+ held_back.update(dict.fromkeys((run.run_id for run in runs), reason))
+
+ settled: list[list[CalibrationRun]] = []
+ for (key, _), runs in attempts.items():
+ is_attempt = key is not None
+ removed = notes.get(key) if key is not None else None
+ queued, planned = _queued_runs(runs, removed)
+ if any(run.run_id in running for run in runs):
+ hold(runs, "running")
+ elif (
+ (removed is not None and removed.aborted)
+ or queued < planned
+ or key in interleaved
+ or (is_attempt and any(run.retries_in_flight for run in runs))
+ ):
+ hold(runs, "aborted_attempt")
+ elif is_attempt:
+ # A run without an attempt is judged on its own, as before: a canceled one feeds what it measured.
+ settled.append(runs)
+ canceled, started = self._canceled_runs([run for runs in settled for run in runs])
+ for runs in settled:
+ if any(run.run_id in started for run in runs):
+ # An item of it the store records runs after all: a retry queued since the read for running items.
+ hold(runs, "running")
+ elif any(run.run_id in canceled for run in runs):
+ hold(runs, "aborted_attempt")
+ return held_back
+
+ def _canceled_runs(self, runs: list[CalibrationRun]) -> tuple[set[str], set[str]]:
+ """The runs among `runs`, none of them running when `_held_back` asked the queue, whose attempt an item of
+ theirs interrupted: the item that stands for one of its lineages, its latest retry or itself
+ (`_lineage_outcomes`), was canceled, or is gone from the queue before the runner saw it finish, or admission
+ failed it because a model changed after the calibration was planned (`error_code` `model_changed`: the rest of
+ the attempt would measure another model); and a run with no item at all, whose items were never recorded.
+ Judged per item, so such an item counts beside a failed one, which decides a run's displayed status; an item
+ that failed otherwise (out of memory at the largest size) ends that step, not the attempt; and an item whose
+ retry completed or failed no longer counts. And the runs one of whose items the queue shows running after all:
+ they are not judged yet.
+
+ The items are those the store records: the run's batch, and every retry (recorded as the queue commits it,
+ `retries_committed`, and by the runner's observations). The runner's observation decides an item it saw
+ finish. Any other is read from the queue by id once it finished, kept until its run is removed since a
+ finished item never changes, and only as the queue holds it with the run's origin: a recreated or restored
+ database gives the id to an unrelated item, or to another run's, and the run's own is gone. Reads the queue
+ only for items without such an outcome.
+
+ Called under `_fits_lock`, from a read of the store file made under it too: a removal's `_forget` then cannot
+ run between the read and the outcomes this writes, which would keep outcomes of a run that is gone."""
+ if not runs:
+ return set(), set()
+ unknown: dict[tuple[str, int], CalibrationRun] = {
+ (run.run_id, item_id): run
+ for run in runs
+ for item_id in set(run.queue_item_ids) | set(run.observed)
+ if (run.run_id, item_id) not in self._item_outcomes
+ and ((observed := run.observed.get(item_id)) is None or observed.status in _RUNNING)
+ }
+ started: set[str] = set()
+ if unknown:
+ queue = self._services.session_queue
+ ids = sorted({item_id for _, item_id in unknown})
+ found = {
+ summary.item_id: summary for summary in queue.get_queue_item_summaries_by_ids(DEFAULT_QUEUE_ID, ids)
+ }
+ for key, run in unknown.items():
+ summary = found.get(key[1])
+ if summary is None or summary.origin != calibration_origin(run.run_id):
+ self._item_outcomes[key] = "canceled"
+ elif summary.status in _RUNNING:
+ # Defensive: every item read here is the store's, of a run the read for unfinished items found
+ # settled, and a settled item does not start again (a retry is a new item, which that read would
+ # have found). Should one run all the same, its status is not final: it must not enter the kept
+ # outcomes, and the run waits for the next refresh.
+ started.add(run.run_id)
+ else:
+ self._item_outcomes[key] = summary.status
+ canceled: set[str] = set()
+ for run in runs:
+ if run.run_id in started:
+ continue
+ outcomes: dict[int, QueueItemLineage] = {}
+ for item_id in set(run.queue_item_ids) | set(run.observed):
+ status = self._item_outcomes.get((run.run_id, item_id))
+ if status is None:
+ continue
+ observed = run.observed.get(item_id)
+ outcomes[item_id] = QueueItemLineage(
+ item_id=item_id,
+ status=status,
+ origin=None,
+ retried_from_item_id=observed.retried_from_item_id if observed is not None else None,
+ )
+ _, statuses = _lineage_outcomes(run, outcomes)
+ if not statuses or any(_interrupts(run, item_id, status) for item_id, status in statuses.items()):
+ canceled.add(run.run_id)
+ return canceled, started
+
+ def _try_refresh_user_fits(self, when: str) -> None:
+ """Refresh the fits `when` (for the log). A store that cannot be read now must not fail what triggered it, a
+ reset that already happened or a plan; the fits read so far then stay until the next refresh."""
+ try:
+ self.refresh_user_fits()
+ except Exception:
+ self._services.logger.warning(f"Could not refresh the working-memory user fits {when}", exc_info=True)
+
+ # endregion
+
+ # region Plan and summary
+
+ def get_plan(self, model_key: str) -> WorkingMemoryCalibrationPlan:
+ store = self._services.model_manager.store
+ # Raises UnknownModelException for an unknown key.
+ target = store.get_model(model_key)
+ # The case sizes price the decode with the fits estimates read: the store as it is now, not as the last
+ # queue item found it.
+ self._try_refresh_user_fits("before building a calibration plan")
+ device: Optional[torch.device] = None
+ unavailable: Optional[str] = None
+ try:
+ device = self._calibration_device()
+ except CalibrationUnavailableError as error:
+ unavailable = str(error)
+
+ def reservation(estimator: str, height: int, width: int, dtype: str) -> int:
+ assert device is not None
+ return self._untiled_decode_reservation(estimator, height, width, dtype, device)
+
+ return build_plan(
+ target,
+ store.all_models(),
+ device_class=self._device_class(device) if device is not None else None,
+ unavailable=unavailable,
+ platform=platform_for(device) if device is not None else None,
+ precision=self._services.configuration.precision,
+ vae_dtypes=self._vae_dtypes_on(device),
+ reservation=reservation,
+ specs=import_estimator_modules(),
+ capacity_bytes=self._decode_capacity(device) if device is not None else None,
+ working_memory_floor_bytes=int(self._services.configuration.device_working_mem_gb * 2**30),
+ force_tiled_decode=self._services.configuration.force_tiled_decode,
+ )
+
+ def _vae_dtypes_on(self, device: Optional[torch.device]) -> VaeDtypes:
+ """What the VAE loaders choose on `device`, by default the one models load onto."""
+ return self._vae_dtypes(device or TorchDevice.choose_torch_device(), self._services.configuration.models_path)
+
+ def _cache_memory(self, device: torch.device) -> DeviceMemory:
+ """`DeviceMemory` for a GPU `device`: the capacity its model cache gives a calibration's lock, which that lock
+ then asks the same cache for."""
+ load = self._services.model_manager.load
+ cache = load.ram_caches.get(str(TorchDevice.normalize(device))) or load.ram_cache
+ reading = read_counters(device)
+ outside = None if reading.driver is None or reading.reserved is None else reading.driver - reading.reserved
+ return DeviceMemory(capacity_bytes=cache.calibration_capacity(), outside_torch_bytes=outside)
+
+ def _decode_capacity(self, device: torch.device) -> int:
+ """What the model cache can give one decode and its VAE on `device` (`DeviceMemory.capacity_bytes`): what a
+ calibration's lock gets once its pre-lock offload ran, the cache's reserves and cap applied.
+
+ This process's memory outside torch's allocator counts at the larger of what it is now and the most a stored
+ window of this environment found it at (`recorded_outside_torch_bytes`): it grows with the first generations
+ (on ROCm under Windows, HIP's retained pool and MIOpen's workspaces, from about 0.3 GB in a fresh server to
+ 2.6 GB on an RX 9060 XT), so a fresh server's reading alone overstates what a decode will find. Without a stored
+ window, a first calibration sizes for the reading alone. Where the driver gives no figure now, the recorded one
+ counts whole. The store is the one `refresh_user_fits` read last; nothing here reads it again."""
+ memory = self._device_memory(device)
+ capacity = memory.capacity_bytes
+ known = self._fits.get(_device_key(device))
+ if known is not None and known.file is not None:
+ recorded = recorded_outside_torch_bytes(known.file, known.env_id)
+ if recorded is not None:
+ capacity -= max(0, recorded - (memory.outside_torch_bytes or 0))
+ return capacity
+
+ def _present_backends(self) -> dict[str, Backend]:
+ """The backend of each device class a GPU generation device here belongs to, by device class id."""
+ present: dict[str, Backend] = {}
+ for device in self._devices():
+ backend = backend_for(device)
+ if backend is not None:
+ present[self._device_class(device).id] = backend
+ return present
+
+ def _present_device(self, device_class_id: str) -> Optional[torch.device]:
+ """A GPU generation device of this class; None when no generation device is one."""
+ for device in self._devices():
+ if backend_for(device) is not None and self._device_class(device).id == device_class_id:
+ return device
+ return None
+
+ def _present(self, device_class_id: str) -> Optional[tuple[Environment, Platform]]:
+ """The environment and platform of a GPU generation device of this class; None when no such device is one."""
+ device = self._present_device(device_class_id)
+ return None if device is None else (self._environment(device), platform_for(device))
+
+ def get_model_summary(
+ self, model_key: str, device_class_id: Optional[str] = None
+ ) -> WorkingMemoryCalibrationModelSummary:
+ store = self._services.model_manager.store
+ # Raises UnknownModelException for an unknown key.
+ target = store.get_model(model_key)
+ class_id = self._current_device_class_id(device_class_id)
+ with self._fits_lock:
+ read = self._store.read(class_id)
+ held_back = self._held_back(read.file) if read is not None and read.file is not None else {}
+ present = self._present(class_id)
+ method, verified = _measurement(self._present_backends().get(class_id))
+ summary = WorkingMemoryCalibrationModelSummary(
+ model_key=model_key,
+ device_class_id=class_id,
+ usable=read is None or read.file is not None,
+ problem=read.problem if read is not None else None,
+ current_env_id=present[0].id if present is not None else None,
+ measurement_method=method,
+ measurement_verified=verified,
+ lines=[],
+ excluded_windows=0,
+ runs=[],
+ )
+ if read is None or read.file is None:
+ return summary
+ file = read.file
+ runs = [run for run in file.runs if run.model_key == model_key]
+ run_ids = {run.run_id for run in runs}
+
+ def name_of(key: str) -> Optional[str]:
+ try:
+ return getattr(store.get_model(key), "name", None)
+ except UnknownModelException:
+ return None
+
+ def platform_of(env: CalibrationEnvironment) -> Optional[Platform]:
+ if present is not None and env.id == present[0].id:
+ return present[1]
+ try:
+ return platform_for_environment(file.device_class.backend, env.hard)
+ except ValueError:
+ return None
+
+ lines, excluded = model_lines(
+ file,
+ model_key,
+ present[0] if present is not None else None,
+ platform_of,
+ import_estimator_modules(),
+ priced_on=decode_lines_of(
+ target,
+ self._services.configuration.precision,
+ self._vae_dtypes_on(self._present_device(class_id)),
+ store.all_models(),
+ ),
+ name_of=name_of,
+ held_back=held_back,
+ )
+ points_per_run: dict[str, int] = {}
+ valid_points_per_run: dict[str, int] = {}
+ for point in file.points:
+ if point.run_id in run_ids:
+ points_per_run[point.run_id] = points_per_run.get(point.run_id, 0) + 1
+ if point.valid:
+ valid_points_per_run[point.run_id] = valid_points_per_run.get(point.run_id, 0) + 1
+ live = self._live_items() if runs else {}
+ model_runs = []
+ for run in sorted(runs, key=lambda run: run.created_at, reverse=True):
+ point_count = points_per_run.get(run.run_id, 0)
+ status, error, error_code, _ = derive_run_status(
+ run, live.get(run.run_id, {}), valid_points_per_run.get(run.run_id, 0)
+ )
+ model_runs.append(
+ WorkingMemoryCalibrationModelRun(
+ run_id=run.run_id,
+ status=status,
+ error=error,
+ error_code=error_code,
+ created_at=run.created_at,
+ point_count=point_count,
+ attempt_id=run.attempt_id,
+ attempt_steps=run.attempt_steps,
+ held_back=held_back.get(run.run_id),
+ )
+ )
+ return summary.model_copy(update={"lines": lines, "excluded_windows": excluded, "runs": model_runs})
+
+ # endregion
+
# region Reset and export
@staticmethod
def _remove(
- file: CalibrationStoreFile, run_ids: set[str], model_key: Optional[str] = None, *, remember: bool = True
+ file: CalibrationStoreFile,
+ run_ids: set[str],
+ model_key: Optional[str] = None,
+ *,
+ reasons: Optional[Mapping[str, Optional[CalibrationHoldBack]]],
) -> tuple[bool, WorkingMemoryCalibrationResetResult]:
- """Remove the runs `run_ids` with their points, and with `model_key` every point attributed to that model
- (`measured_models`). `remember` keeps the removed runs' ids, so that a repeat of the request that started one
- cannot start it again."""
+ """Remove the runs `run_ids` with their points, and with `model_key` every point the summary attributes to
+ that model (`measured_models`). With `reasons` (`_hold_reasons` of this `file`), for a reset: keep the removed
+ runs' ids, so that a repeat of the request that started one cannot start it again, and note what the reset
+ removed of each attempt (`_note_removed_steps`). A creation that queued nothing passes None and removes its run
+ without either."""
models = run_models(file)
- if remember:
- file.removed_run_ids.extend(
- run.run_id for run in file.runs if run.run_id in run_ids and _is_keyed(run.run_id)
- )
+ removed = [run for run in file.runs if run.run_id in run_ids]
+ if reasons is not None:
+ file.removed_run_ids.extend(run.run_id for run in removed if _is_keyed(run.run_id))
runs = [run for run in file.runs if run.run_id not in run_ids]
points = [
point
@@ -918,41 +1916,82 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
runs_removed=len(file.runs) - len(runs), points_removed=len(file.points) - len(points)
)
file.runs, file.points = runs, points
+ if reasons is not None:
+ _note_removed_steps(file, removed, reasons)
_prune_envs(file)
return result.runs_removed > 0 or result.points_removed > 0, result
+ def _forget(self, runs: Iterable[CalibrationRun]) -> None:
+ """Drop what this process keeps of runs a store change removed: the file that held each, and the outcomes of
+ their items, which nothing reads once the runs are gone. Called under `_fits_lock`, which the change ran under
+ too: nothing that judged the file as it was before the removal (`_canceled_runs`) can put an outcome back."""
+ for run in runs:
+ self._run_files.pop(run.run_id, None)
+ for item_id in set(run.queue_item_ids) | set(run.observed):
+ self._item_outcomes.pop((run.run_id, item_id), None)
+
+ def _hold_reasons(self, file: CalibrationStoreFile) -> dict[str, Optional[CalibrationHoldBack]]:
+ """Per stored run of `file`, why its windows are held back now (`_held_back`; None where they are not). Read by
+ a reset inside its change of the file, under `_fits_lock` (`_canceled_runs`) and the file's lock, which the
+ queue's retries take too, before they commit (`retries_starting`): none slips in between. The queue is read
+ under that lock; the queue takes it only outside its transactions."""
+ held_back = self._held_back(file)
+ return {run.run_id: held_back.get(run.run_id) for run in file.runs}
+
def reset_run(self, run_id: str) -> WorkingMemoryCalibrationResetResult:
- return self._remove_run(run_id, remember=True)
+ return self._remove_run(run_id, reset=True)
- def _remove_run(self, run_id: str, *, remember: bool) -> WorkingMemoryCalibrationResetResult:
+ def _remove_run(self, run_id: str, *, reset: bool) -> WorkingMemoryCalibrationResetResult:
found = self._find_run(run_id)
if found is None:
raise CalibrationRunNotFoundError(run_id)
- result = self._store.change(found[0], lambda file: self._remove(file, {run_id}, remember=remember))
- self._run_files.pop(run_id, None)
+
+ removed: list[CalibrationRun] = []
+
+ def remove(file: CalibrationStoreFile) -> tuple[bool, WorkingMemoryCalibrationResetResult]:
+ removed.extend(run for run in file.runs if run.run_id == run_id)
+ return self._remove(file, {run_id}, reasons=self._hold_reasons(file) if reset else None)
+
+ with self._fits_lock:
+ result = self._store.change(found[0], remove)
+ self._forget(removed)
+ self._run_files.pop(run_id, None)
+ self._try_refresh_user_fits("after a reset")
return result or WorkingMemoryCalibrationResetResult(runs_removed=0, points_removed=0)
def reset_model(self, model_key: str, device_class_id: Optional[str] = None) -> WorkingMemoryCalibrationResetResult:
class_id = self._current_device_class_id(device_class_id)
+ removed: list[CalibrationRun] = []
def remove(file: CalibrationStoreFile) -> tuple[bool, WorkingMemoryCalibrationResetResult]:
+ reasons = self._hold_reasons(file)
# Written with the removal or not at all: a node that read the older epoch drops its points of the model.
file.model_reset_epochs[model_key] = file.model_reset_epochs.get(model_key, 0) + 1
- run_ids = {run.run_id for run in file.runs if run.model_key == model_key}
- return True, self._remove(file, run_ids, model_key)[1]
+ removed.extend(run for run in file.runs if run.model_key == model_key)
+ return True, self._remove(file, {run.run_id for run in removed}, model_key, reasons=reasons)[1]
- result = self._store.change(class_id, remove)
+ with self._fits_lock:
+ result = self._store.change(class_id, remove)
+ self._forget(removed)
+ self._try_refresh_user_fits("after a reset")
return result or WorkingMemoryCalibrationResetResult(runs_removed=0, points_removed=0)
def reset_all(self, device_class_id: Optional[str] = None) -> WorkingMemoryCalibrationResetResult:
+ class_id = self._current_device_class_id(device_class_id)
+ removed: list[CalibrationRun] = []
+
def remove(file: CalibrationStoreFile) -> tuple[bool, WorkingMemoryCalibrationResetResult]:
result = WorkingMemoryCalibrationResetResult(runs_removed=len(file.runs), points_removed=len(file.points))
changed = bool(file.runs or file.points or file.envs)
- file.removed_run_ids.extend(run.run_id for run in file.runs if _is_keyed(run.run_id))
- file.runs, file.points, file.envs = [], [], []
+ removed.extend(file.runs)
+ self._remove(file, {run.run_id for run in file.runs}, reasons=self._hold_reasons(file))
+ file.points, file.envs = [], []
return changed, result
- result = self._store.change(self._current_device_class_id(device_class_id), remove)
+ with self._fits_lock:
+ result = self._store.change(class_id, remove)
+ self._forget(removed)
+ self._try_refresh_user_fits("after a reset")
return result or WorkingMemoryCalibrationResetResult(runs_removed=0, points_removed=0)
def export(self, device_class_id: Optional[str] = None) -> Optional[bytes]:
diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.py
new file mode 100644
index 0000000000..b6a4062608
--- /dev/null
+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.py
@@ -0,0 +1,451 @@
+"""User lines from a calibration store file, which models its windows count for, and what the windows of one model's
+lines measured.
+
+The fitting and resolution rules are the backend's (`backend/working_memory/user_fit.py`); this module picks the
+windows a fit uses: those of one environment whose hard facts are the current ones, valid, fit-eligible and not
+fragmented (`exclusions`).
+"""
+
+import json
+from collections import Counter
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass
+from types import MappingProxyType
+from typing import Final, Optional
+
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
+ CalibrationEnvironment,
+ CalibrationHoldBack,
+ CalibrationLineState,
+ CalibrationPoint,
+ CalibrationRun,
+ CalibrationSizeExclusion,
+ CalibrationStoreFile,
+ WorkingMemoryCalibrationLineContributor,
+ WorkingMemoryCalibrationLineSize,
+ WorkingMemoryCalibrationModelLine,
+ WorkingMemoryCalibrationPixelRange,
+)
+from invokeai.backend.model_manager.taxonomy import SubModelType
+from invokeai.backend.working_memory import fragmentation, user_fit
+from invokeai.backend.working_memory.coefficients import shipped_coefficients
+from invokeai.backend.working_memory.fingerprint import Environment
+from invokeai.backend.working_memory.fit import EntryKey, fits_a_line, line_of
+from invokeai.backend.working_memory.platform import Platform
+from invokeai.backend.working_memory.spec import EstimatorSpec
+from invokeai.backend.working_memory.user_fit import UserFit, UserLine
+
+
+def fit_label(device_class_id: str, env_id: str) -> str:
+ return f"user:{device_class_id}:{env_id}"
+
+
+def _measures_a_line(point: CalibrationPoint) -> bool:
+ """Whether a window measured a line: valid, a positive demand, and features a line admits."""
+ return point.valid and point.demand_bytes is not None and point.demand_bytes > 0 and fits_a_line(point.features)
+
+
+def _suffix(point: CalibrationPoint) -> str:
+ """The ``<operation>_<dtype>`` of the line a window measured."""
+ found = line_of(point.features)
+ assert found is not None, "a window that measured a line names it"
+ return found[0]
+
+
+def _attempts(file: CalibrationStoreFile) -> dict[str, str]:
+ """Per run id, the attempt its windows are judged with: its owner's `attempt_id` (two owners' attempts never share
+ windows, whatever their ids), or the run itself without one."""
+ return {
+ run.run_id: f"{run.user_id}\x00{run.attempt_id}" if run.attempt_id is not None else run.run_id
+ for run in file.runs
+ }
+
+
+HeldBack = Mapping[str, CalibrationHoldBack]
+"""Why each run whose windows no fit takes is held back (`CalibrationHoldBack`), by run id; the service derives it
+from the queue and the attempts' runs."""
+
+_NONE_HELD_BACK: Final[HeldBack] = MappingProxyType({})
+
+
+def exclusions(
+ file: CalibrationStoreFile, held_back: HeldBack = _NONE_HELD_BACK
+) -> dict[int, CalibrationSizeExclusion]:
+ """Why each window that measured a line does not count toward its fit, by position in `file.points`; a window
+ that measured a line and is absent counts.
+
+ - aborted_attempt: a window of a run `held_back` names so: its attempt was stopped, cleared or cut short.
+ - partial_residency: valid but not fit-eligible, its model not fully on the device.
+ - fragmented: the fit-eligible windows of one measurement -- one attempt (an owner's `attempt_id`, else the run)
+ at one environment, estimator, version and features, in the order they ran -- are what `fragmentation.fragmented`
+ flags: they grew around a flat allocation, or their largest window is a ratio outlier against the smaller
+ sizes of the same line in the environment that count, from any attempt. The measurement drops out whole: its
+ windows ran back to back on one allocator state. Another attempt's windows of the same size ran on another and
+ are judged on their own, so a recalibration can bring a size back and a later fragmented attempt drops no clean
+ one. Windows of runs still running (`held_back`) are judged, but set no reference for larger sizes, as they
+ join no user line yet.
+ """
+ points = file.points
+ attempt_of = _attempts(file)
+ excluded: dict[int, CalibrationSizeExclusion] = {}
+ groups: dict[tuple[str, str, int, str, str], list[int]] = {}
+ for index, point in enumerate(points):
+ if not _measures_a_line(point):
+ continue
+ if held_back.get(point.run_id) == "aborted_attempt":
+ excluded[index] = "aborted_attempt"
+ continue
+ if not point.fit_eligible:
+ excluded[index] = "partial_residency"
+ continue
+ features = json.dumps(point.features, sort_keys=True, separators=(",", ":"))
+ attempt = attempt_of.get(point.run_id, point.run_id)
+ groups.setdefault((point.env_id, point.estimator, point.version, features, attempt), []).append(index)
+
+ members = list(groups.values())
+ measurements = []
+ for (env_id, estimator, version, _, _), indices in groups.items():
+ windows = [points[index] for index in indices]
+ measurements.append(
+ fragmentation.Measurement(
+ line=(env_id, estimator, version, _suffix(windows[0])),
+ pixels=_pixels(windows[0]),
+ demand=[window.demand_bytes or 0 for window in windows],
+ reserved=[window.reserved.delta if window.reserved else None for window in windows],
+ allocated=[window.allocated.delta if window.allocated else None for window in windows],
+ reference=not any(window.run_id in held_back for window in windows),
+ )
+ )
+ for indices, flagged in zip(members, fragmentation.fragmented(measurements), strict=True):
+ if flagged:
+ excluded.update(dict.fromkeys(indices, "fragmented"))
+ return excluded
+
+
+def _pixels(point: CalibrationPoint) -> int:
+ found = line_of(point.features)
+ assert found is not None, "a window that measured a line names it"
+ return found[1]
+
+
+def counted_windows(file: CalibrationStoreFile, held_back: HeldBack = _NONE_HELD_BACK) -> list[CalibrationPoint]:
+ """The windows that count toward a fit: they measured a line, and `exclusions` names no reason against them.
+ Those of runs still running count, though no fit takes them yet."""
+ excluded = exclusions(file, held_back)
+ return [point for index, point in enumerate(file.points) if _measures_a_line(point) and index not in excluded]
+
+
+def recorded_outside_torch_bytes(file: CalibrationStoreFile, env_id: str) -> Optional[int]:
+ """The most the measuring process held outside torch's allocator when a valid window of environment `env_id`
+ opened: the driver's figure for the process less torch's reserve, at the window's baseline. None without such a
+ window, or where the driver had no figure for the process (`torch-only`, and XPU's device-wide reading)."""
+ found = [
+ point.driver.baseline - point.reserved.baseline
+ for point in file.points
+ if point.env_id == env_id and point.valid and point.driver is not None and point.reserved is not None
+ ]
+ return max(found, default=None)
+
+
+def user_fit_of(
+ file: CalibrationStoreFile, env_id: str, platform: Platform, *, held_back: HeldBack = _NONE_HELD_BACK
+) -> tuple[Optional[UserFit], Mapping[user_fit.LineKey, str]]:
+ """The user fit of the file's counted windows (`counted_windows`) taken under environment `env_id`, measured on
+ `platform`, or None when they fit no line; and why the lines they measure but cannot fit cannot be. The windows of
+ the runs `held_back` names take no part: those of runs still running join once their attempt finished, those of
+ an attempt that ended early never."""
+ points = [
+ user_fit.UserPoint(point.estimator, point.version, point.features, point.demand_bytes or 0)
+ for point in counted_windows(file, held_back)
+ if point.env_id == env_id and point.run_id not in held_back
+ ]
+ lines, problems = user_fit.fit_user_lines(points, platform)
+ if not lines:
+ return None, problems
+ return UserFit(label=fit_label(file.device_class.id, env_id), platform=platform, lines=lines), problems
+
+
+def _changed(old: Mapping[str, Optional[str]], new: Mapping[str, Optional[str]]) -> list[str]:
+ return sorted(key for key in set(old) | set(new) if old.get(key) != new.get(key))
+
+
+_SUBMODEL_TYPES: Final = frozenset(submodel.value for submodel in SubModelType)
+
+
+def measured_models(point: CalibrationPoint, run_models: Mapping[str, str]) -> frozenset[str]:
+ """The models a window is attributed to: the model its run calibrated (`run_models`, by run id), and the model it
+ measured, where a submodel's window (`<key>:vae`) counts for its model. The summary shows a model's windows by
+ this, and resetting the model removes exactly these."""
+ head, separator, tail = point.model_key.rpartition(":")
+ measured = head if separator and tail in _SUBMODEL_TYPES else point.model_key
+ run_model = run_models.get(point.run_id)
+ return frozenset({measured} if run_model is None else {measured, run_model})
+
+
+def run_models(file: CalibrationStoreFile) -> dict[str, str]:
+ return {run.run_id: run.model_key for run in file.runs}
+
+
+@dataclass(frozen=True)
+class _EnvFit:
+ env: Optional[CalibrationEnvironment]
+ platform: Optional[Platform]
+ fit: Optional[UserFit]
+ problems: Mapping[user_fit.LineKey, str]
+
+
+LineId = tuple[str, str, int, str]
+"""A summary line: environment id, estimator, version and ``<operation>_<dtype>``."""
+
+
+def model_lines(
+ file: CalibrationStoreFile,
+ model_key: str,
+ current_env: Optional[Environment],
+ platform_of: Callable[[CalibrationEnvironment], Optional[Platform]],
+ specs: Mapping[str, EstimatorSpec],
+ priced_on: Iterable[tuple[str, str]],
+ name_of: Callable[[str], Optional[str]],
+ held_back: HeldBack = _NONE_HELD_BACK,
+) -> tuple[list[WorkingMemoryCalibrationModelLine], int]:
+ """Per environment and line, what the windows that feed it measured, with the shipped and the user estimate at
+ each size; and how many of the model's own windows fit no line.
+
+ The lines are those the model's own windows (`measured_models`) measured, and, in `current_env`, each line of
+ `priced_on` (estimator, ``<operation>_<dtype>``: what the model's operations price on) that other models' windows
+ measured. A line is fed by every model's counted windows (`exclusions`) of its environment that join the same user
+ line, as estimates read it: those whose estimator resolves to the same carrying entry on the environment's
+ platform. Its sizes also show, as not counted, the sizes only excluded windows measured.
+
+ The sizes, window counts and contributors show every such window, those of runs still running (`held_back`)
+ included, so a running calibration shows what it measured so far; the windows of an aborted attempt show as not
+ counted. The user line, its range, the user estimates and the state are what estimates use: the fit without
+ the windows of either.
+
+ The state compares the environment with `current_env` (None: no GPU of the file's class generates here): the same
+ hard facts use the line, stale when the soft facts of the newest finished run that fed it differ from the current
+ ones. A run stored without soft facts stands for the environment's, those first recorded with it. Older windows of
+ the same hard environment keep feeding the line whatever their soft facts: soft facts do not change what a window
+ measured enough to drop it.
+ """
+ envs = {env.id: env for env in file.envs}
+ runs = {run.run_id: run for run in file.runs}
+ models = run_models(file)
+ reasons = exclusions(file, held_back)
+ # By identity: the windows below are the file's own objects.
+ reason_of: dict[int, CalibrationSizeExclusion] = {
+ id(file.points[index]): reason for index, reason in reasons.items()
+ }
+ excluded = 0
+ own: dict[LineId, list[CalibrationPoint]] = {}
+ measured_by_env: dict[str, list[CalibrationPoint]] = {}
+ for point in file.points:
+ measured = _measures_a_line(point)
+ if measured:
+ measured_by_env.setdefault(point.env_id, []).append(point)
+ if model_key not in measured_models(point, models):
+ continue
+ if not measured or id(point) in reason_of:
+ excluded += 1
+ if measured:
+ own.setdefault((point.env_id, point.estimator, point.version, _suffix(point)), []).append(point)
+
+ def counts(point: CalibrationPoint) -> bool:
+ return id(point) not in reason_of
+
+ env_fits: dict[str, _EnvFit] = {}
+
+ def env_fit(env_id: str) -> _EnvFit:
+ if env_id not in env_fits:
+ env = envs.get(env_id)
+ platform = platform_of(env) if env is not None else None
+ fit, problems = (
+ user_fit_of(file, env_id, platform, held_back=held_back) if platform is not None else (None, {})
+ )
+ env_fits[env_id] = _EnvFit(env, platform, fit, problems)
+ return env_fits[env_id]
+
+ def carrier_of(estimator: str, version: int, platform: Optional[Platform]) -> Optional[EntryKey]:
+ """The entry whose user line a window of this estimator version joins; None where it is not priced here."""
+ spec = specs.get(estimator)
+ if spec is None or spec.version != version or platform is None:
+ return None
+ return user_fit.carrier_key(estimator, version, platform)
+
+ def feeding(line_id: LineId) -> list[CalibrationPoint]:
+ """The windows of the line's environment that measured its user line, counted or not; without a carrying
+ entry, those of the same estimator version."""
+ env_id, estimator, version, suffix = line_id
+ platform = env_fit(env_id).platform
+ carrier = carrier_of(estimator, version, platform)
+ found = []
+ for point in measured_by_env.get(env_id, []):
+ if _suffix(point) != suffix:
+ continue
+ if carrier is None:
+ same = (point.estimator, point.version) == (estimator, version)
+ else:
+ same = carrier_of(point.estimator, point.version, platform) == carrier
+ if same:
+ found.append(point)
+ return found
+
+ line_ids = set(own)
+ if current_env is not None:
+ for estimator, suffix in priced_on:
+ spec = specs.get(estimator)
+ if spec is not None:
+ line_ids.add((current_env.id, estimator, spec.version, suffix))
+
+ names: dict[str, Optional[str]] = {}
+ lines: list[WorkingMemoryCalibrationModelLine] = []
+ for line_id in sorted(line_ids):
+ env_id, estimator, version, suffix = line_id
+ measured = feeding(line_id)
+ if not measured:
+ # A line the model prices on that no window measured in this environment.
+ continue
+ points = [point for point in measured if counts(point)]
+ own_points = [point for point in own.get(line_id, []) if counts(point)]
+ found_fit = env_fit(env_id)
+ env, platform, fit = found_fit.env, found_fit.platform, found_fit.fit
+ spec = specs.get(estimator)
+ priced = spec is not None and spec.version == version
+ carrier = carrier_of(estimator, version, platform)
+ line: Optional[UserLine] = None
+ if fit is not None and carrier is not None:
+ line = fit.lines.get((carrier, suffix))
+
+ changed: list[str] = []
+ problem: Optional[str] = None
+ state: CalibrationLineState
+ if env is None or current_env is None:
+ state, problem = "unusable", "No generation device of this class is present."
+ elif env.id != current_env.id:
+ state, changed = "unusable", _changed(env.hard, current_env.hard)
+ elif not priced:
+ state = "unusable"
+ problem = f"Measured with {estimator} version {version}, which this version does not price with."
+ elif line is None:
+ state = "insufficient"
+ known = found_fit.problems.get((carrier, suffix)) if carrier is not None else None
+ if not points and all(reason_of.get(id(point)) == "aborted_attempt" for point in measured):
+ problem = (
+ "A stopped or interrupted calibration measured this line, and its measurements were discarded. "
+ "Calibrate again to measure it."
+ )
+ elif not points:
+ problem = "None of this line's windows count: see each size's excluded_reason."
+ elif any(held_back.get(point.run_id) == "running" for point in points):
+ problem = "A calibration run is still measuring this line; its windows count once it finished."
+ if known:
+ problem += f" So far: {known}"
+ else:
+ problem = known or "The shipped data has no such line for this estimator on this platform."
+ else:
+ finished = [point for point in points if point.run_id not in held_back]
+ changed = _changed(_newest_soft(finished, runs, env), current_env.soft)
+ state = "stale" if changed else "in_use"
+
+ windows: Counter[str] = Counter()
+ for point in points:
+ windows.update(measured_models(point, models))
+ for key in windows:
+ if key not in names:
+ names[key] = name_of(key)
+ measured_by = [
+ WorkingMemoryCalibrationLineContributor(model_key=key, name=names[key], windows=count)
+ for key, count in windows.items()
+ ]
+ measured_by.sort(
+ key=lambda contributor: (contributor.name is None, contributor.name or "", contributor.model_key)
+ )
+
+ lines.append(
+ WorkingMemoryCalibrationModelLine(
+ estimator=estimator,
+ version=version,
+ line=suffix,
+ carrier=carrier[0] if carrier else None,
+ env_id=env_id,
+ state=state,
+ changed_facts=changed,
+ problem=problem,
+ measured_range=(
+ WorkingMemoryCalibrationPixelRange(min_pixels=line.x_min, max_pixels=line.x_max) if line else None
+ ),
+ slope_bytes_per_pixel=line.k if line else None,
+ base_bytes=line.b if line else None,
+ sizes=_sizes(measured, reason_of, estimator, specs if priced else {}, platform, fit if line else None),
+ own_windows=len(own_points),
+ measured_by=measured_by,
+ )
+ )
+ return lines, excluded
+
+
+def _newest_soft(
+ points: Iterable[CalibrationPoint], runs: Mapping[str, CalibrationRun], env: CalibrationEnvironment
+) -> Mapping[str, Optional[str]]:
+ """The soft facts of the newest run among those that measured `points`; the environment's when it recorded none.
+ `runs` is in the file's order, which is the order they were created in: it decides a tie of the clock."""
+ order = {run_id: index for index, run_id in enumerate(runs)}
+ fed = {point.run_id for point in points if point.run_id in runs}
+ newest = max((runs[run_id] for run_id in fed), key=lambda run: (run.created_at, order[run.run_id]), default=None)
+ return newest.soft if newest is not None and newest.soft is not None else env.soft
+
+
+def _sizes(
+ points: Iterable[CalibrationPoint],
+ reason_of: Mapping[int, CalibrationSizeExclusion],
+ estimator: str,
+ specs: Mapping[str, EstimatorSpec],
+ platform: Optional[Platform],
+ fit: Optional[UserFit],
+) -> list[WorkingMemoryCalibrationLineSize]:
+ """Per measured size, the windows and their largest demand, and the shipped and the user estimate there.
+
+ A size with counted windows shows those; a size whose windows all are excluded (`reason_of`, by window identity)
+ shows them as not counted: aborted_attempt where that is the only reason, else fragmented where any of them is.
+ The estimates price the largest window of the line's
+ own estimator among those shown, or, where only other estimators that share the line measured the size, the largest
+ window with its own estimator: their features are their own."""
+ by_size: dict[tuple[int, int], list[CalibrationPoint]] = {}
+ for point in points:
+ by_size.setdefault((int(point.features["width"]), int(point.features["height"])), []).append(point) # type: ignore[arg-type]
+ sizes = []
+ for (width, height), measured in sorted(by_size.items(), key=lambda item: (item[0][0] * item[0][1], item[0])):
+ group = [point for point in measured if id(point) not in reason_of]
+ counted = bool(group)
+ excluded_reason: Optional[CalibrationSizeExclusion] = None
+ if not counted:
+ group = measured
+ found = {reason_of[id(point)] for point in measured}
+ if found == {"aborted_attempt"}:
+ excluded_reason = "aborted_attempt"
+ else:
+ excluded_reason = "fragmented" if "fragmented" in found else "partial_residency"
+ largest = max(group, key=lambda point: point.demand_bytes or 0)
+ mine = [point for point in group if point.estimator == estimator]
+ priced = max(mine, key=lambda point: point.demand_bytes or 0) if mine else largest
+ spec = specs.get(priced.estimator) if estimator in specs else None
+ shipped_bytes = user_bytes = None
+ if spec is not None and spec.version == priced.version and platform is not None:
+ shipped = shipped_coefficients(spec, platform)
+ shipped_bytes = spec.evaluate(priced.features, shipped).reservation_bytes
+ if fit is not None:
+ user_bytes = user_fit.resolve(spec, priced.features, shipped, fit).reservation_bytes
+ sizes.append(
+ WorkingMemoryCalibrationLineSize(
+ width=width,
+ height=height,
+ pixels=width * height,
+ windows=len(group),
+ measured_bytes=largest.demand_bytes or 0,
+ counted=counted,
+ excluded_reason=excluded_reason,
+ shipped_bytes=shipped_bytes,
+ user_bytes=user_bytes,
+ )
+ )
+ return sizes
diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py
new file mode 100644
index 0000000000..38b5e4b6f5
--- /dev/null
+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_plan.py
@@ -0,0 +1,730 @@
+"""The cases a client runs to calibrate one model's working memory, and which other models that calibration moves.
+
+Covered: the decode of main models whose decode node prices with one of the five AutoencoderKL estimators of
+`backend/util/vae_working_memory.py` (`DECODE_LINES`), and standalone VAEs of those bases, calibrated by generating
+with a compatible installed main model. Each case is a two-step text-to-image generation, which runs the whole
+pipeline and ends in an untiled decode; image-to-image would add an encode, which v1 does not plan.
+"""
+
+import math
+from collections.abc import Callable, Mapping, Sequence
+from dataclasses import dataclass
+from functools import partial
+from typing import Any, Final, Optional
+
+from invokeai.app.invocations.flux2.flux2_klein_model_loader import KLEIN_TO_QWEN3_VARIANT
+from invokeai.app.invocations.model import is_self_contained_sdnq_flux1_pipeline, is_self_contained_sdnq_pipeline
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
+ WorkingMemoryCalibrationCase,
+ WorkingMemoryCalibrationDeviceClassRef,
+ WorkingMemoryCalibrationPlan,
+ WorkingMemoryCalibrationRepetitions,
+ WorkingMemoryCalibrationSharedModel,
+)
+from invokeai.backend.architectures import accepts_vae
+from invokeai.backend.model_manager.taxonomy import (
+ BaseModelType,
+ Flux2VariantType,
+ FluxVariantType,
+ MistralVariantType,
+ ModelType,
+ ModelVariantType,
+ Qwen3VariantType,
+)
+from invokeai.backend.util.vae_working_memory import VAE_PRETILE_VRAM_FRACTION
+from invokeai.backend.working_memory import user_fit
+from invokeai.backend.working_memory.fingerprint import DeviceClass
+from invokeai.backend.working_memory.fit import MIN_AREA_RATIO, EntryKey
+from invokeai.backend.working_memory.platform import Platform
+from invokeai.backend.working_memory.probe import calibration_reservation
+from invokeai.backend.working_memory.spec import EstimatorSpec
+
+ModelConfig = Any
+"""An installed model's config. Read by attribute: `key`, `name`, `base`, `type`, and where present `variant` and
+`cpu_only`."""
+
+ReservationFunction = Callable[[str, int, int, str], int]
+"""The reservation an untiled decode of (estimator, height, width, dtype) gets on the calibration device."""
+
+
+@dataclass(frozen=True)
+class DecodeLines:
+ estimator: str
+ dtypes: tuple[str, ...] = ()
+ """The dtypes the decode runs in, where they are fixed. Where the node casts the VAE (`vaePrecision`), each is a
+ case. Empty: the VAE's loader decides (`decode_dtypes`)."""
+ precision_setting: bool = False
+
+
+@dataclass(frozen=True)
+class VaeDtypes:
+ """What the VAE loaders choose on the calibration device, with dtypes named as the lines are (`fp16`, `bf16`,
+ `fp32`). The service reads them through the loaders' own rules, so the plan sizes the decode that runs."""
+
+ standalone_flux: str
+ """A standalone FLUX.1 or FLUX.2 VAE, and the FLUX.1 VAE Z-Image decodes with: the configured dtype, except fp16
+ (`TorchDevice.dtype_avoiding_float16`). A configured fp32 stays fp32."""
+ z_image_pipeline: str
+ """The VAE of a Z-Image Diffusers pipeline: `TorchDevice.choose_bfloat16_safe_dtype`."""
+ sdnq_quantized_vae: Callable[[Any], bool]
+ """Whether the VAE folder of a FLUX.1 SDNQ pipeline holds SDNQ weights, as `FluxSDNQDiffusersModel._load_vae`
+ tells (`is_sdnq_folder`)."""
+
+
+FLUX2_PIPELINE_VAE_DTYPE: Final = "bf16"
+"""The VAE of a FLUX.2 Diffusers pipeline, which `Flux2DiffusersModel` loads in bf16 whatever the configured dtype."""
+
+SDNQ_PIPELINE_VAE_DTYPE: Final = "fp32"
+"""The VAE of a self-contained SDNQ pipeline, which `Flux2SDNQCheckpointModel._load_vae`,
+`ZImageSDNQCheckpointModel._load_vae` and, for a VAE folder of plain weights, `FluxSDNQDiffusersModel._load_vae` load
+through `from_pretrained` without a `torch_dtype`: fp32, whatever the weights on disk are."""
+
+SDNQ_QUANTIZED_VAE_DTYPE: Final = "bf16"
+"""A FLUX.1 SDNQ pipeline's SDNQ-quantized VAE, which `FluxSDNQDiffusersModel._load_sdnq_vae` dequantizes at bf16."""
+
+_SD = DecodeLines("vae.sd", ("fp16", "fp32"), precision_setting=True)
+_FLUX = DecodeLines("vae.flux")
+_FLUX2 = DecodeLines("vae.flux2")
+
+DECODE_LINES: Final[Mapping[BaseModelType, DecodeLines]] = {
+ BaseModelType.StableDiffusion1: _SD,
+ BaseModelType.StableDiffusion2: _SD,
+ BaseModelType.StableDiffusionXL: _SD,
+ BaseModelType.StableDiffusionXLRefiner: _SD,
+ # The SD3 VAE runs in the configured precision (`_sd3_dtype`).
+ BaseModelType.StableDiffusion3: DecodeLines("vae.sd3"),
+ # Z-Image decodes with a FLUX.1 VAE.
+ BaseModelType.Flux: _FLUX,
+ BaseModelType.ZImage: _FLUX,
+ BaseModelType.Flux2: _FLUX2,
+ # Decodes with the FLUX.2 VAE; shares its lines, but generates from structured prompts the plan does not write.
+ BaseModelType.Ideogram4: _FLUX2,
+ # The CogView4 loader forces bf16.
+ BaseModelType.CogView4: DecodeLines("vae.cogview4", ("bf16",)),
+}
+"""Per base, the estimator its decode node prices with and, where fixed, the dtypes it runs in."""
+
+FORCE_TILED_BASES: Final = frozenset(
+ {
+ BaseModelType.StableDiffusion1,
+ BaseModelType.StableDiffusion2,
+ BaseModelType.StableDiffusionXL,
+ BaseModelType.StableDiffusionXLRefiner,
+ BaseModelType.Flux,
+ BaseModelType.ZImage,
+ BaseModelType.Flux2,
+ }
+)
+"""Bases whose decode node tiles every decode under `force_tiled_decode` (`latents_to_image`, `flux_vae_decode`,
+`z_image_latents_to_image`, `flux2_vae_decode`). The SD3, CogView4 and Ideogram 4 nodes ignore the setting."""
+
+_OWN_VAE_BASES: Final = frozenset({BaseModelType.Flux2, BaseModelType.ZImage})
+"""Bases whose Diffusers and self-contained SDNQ pipelines decode with their own VAE when Generate's `vae` slot is
+empty. A FLUX.1 Diffusers pipeline does not: Generate requires a standalone VAE for it."""
+
+PLANNABLE_BASES: Final = frozenset(
+ {
+ BaseModelType.StableDiffusion1,
+ BaseModelType.StableDiffusion2,
+ BaseModelType.StableDiffusionXL,
+ BaseModelType.StableDiffusion3,
+ BaseModelType.Flux,
+ BaseModelType.Flux2,
+ BaseModelType.ZImage,
+ BaseModelType.CogView4,
+ }
+)
+"""Bases whose main models a text-to-image case can calibrate. The SDXL refiner generates from no text, and Ideogram 4
+from structured prompts only."""
+
+VAE_SLOT_BASES: Final = frozenset(
+ {BaseModelType.Flux, BaseModelType.Flux2, BaseModelType.StableDiffusion3, BaseModelType.ZImage}
+)
+"""Bases whose Generate widget has a `vae` component slot. The SD bases pick a VAE through a setting a case cannot
+override, and CogView4 has none: their standalone VAEs are calibrated through a main model's own VAE, which prices on
+the same lines."""
+
+NOT_TEXT_TO_IMAGE_VARIANTS: Final = frozenset(
+ {ModelVariantType.Inpaint.value, ModelVariantType.Depth.value, FluxVariantType.DevFill.value}
+)
+
+CASE_STEPS: Final = 2
+CASE_SEED: Final = 1
+CASE_PROMPT: Final = "a mountain lake at dawn, detailed photograph"
+REPETITIONS: Final = WorkingMemoryCalibrationRepetitions(warm_up=1, measured=2)
+
+AREA_FRACTIONS: Final = (0.25, 0.5, 1.0)
+SIDE_MULTIPLE: Final = 64
+"""A multiple of every covered base's dimension grid (8, 16 or 32)."""
+MAX_SIDE: Final = 4096
+"""The largest width or height Generate accepts; no covered architecture declares a smaller limit."""
+MIN_LARGEST_SIDE: Final = 512
+VAE_WEIGHTS_ALLOWANCE_BYTES: Final = 2**30
+"""What the VAE's own weights take on the device while it decodes: under 1 GiB for every covered VAE."""
+
+SECONDS_MODEL_LOAD: Final = 30
+SECONDS_PER_RUN: Final = 3
+SECONDS_PER_MEGAPIXEL_STEP: Final = 1.0
+SECONDS_PER_MEGAPIXEL_DECODE: Final = 1.0
+
+ENCODE_NOT_COVERED: Final = (
+ "encode: text-to-image runs no encode, so image-to-image and inpainting encodes keep the shipped values"
+)
+
+
+def sd3_dtype(precision: str) -> str:
+ """The dtype the SD3 VAE runs in under the `precision` setting: `auto` is fp16 on a GPU."""
+ return {"bfloat16": "bf16", "float32": "fp32"}.get(precision, "fp16")
+
+
+def _value(field: object) -> str:
+ return str(getattr(field, "value", field))
+
+
+def ships_its_vae(model: ModelConfig) -> bool:
+ """Whether a main model decodes with its own VAE while Generate's `vae` slot is empty, as Generate
+ (`isBundledMainForBase`) and the model loader nodes treat it: a FLUX.2 or Z-Image Diffusers pipeline, or a
+ self-contained SDNQ pipeline (`is_self_contained_sdnq_pipeline`; for FLUX.1 `is_self_contained_sdnq_flux1_pipeline`,
+ which also needs the T5 pair)."""
+ if not _is_main(model):
+ return False
+ if model.base == BaseModelType.Flux:
+ return is_self_contained_sdnq_flux1_pipeline(model)
+ if model.base not in _OWN_VAE_BASES:
+ return False
+ return _value(getattr(model, "format", None)) == "diffusers" or is_self_contained_sdnq_pipeline(model)
+
+
+def _ignores_vae_pick(model: ModelConfig) -> bool:
+ """Whether Generate drops a `vae` pick for the main model: a self-contained FLUX.1 SDNQ pipeline always decodes
+ with its own VAE (`buildFLUXGraph` sends none). The FLUX.2 and Z-Image model loader nodes take a picked VAE first."""
+ return model.base == BaseModelType.Flux and ships_its_vae(model)
+
+
+DEFAULT_VAE_BASES: Final = frozenset(
+ {
+ BaseModelType.StableDiffusion1,
+ BaseModelType.StableDiffusion2,
+ BaseModelType.StableDiffusionXL,
+ BaseModelType.StableDiffusion3,
+ BaseModelType.Flux,
+ BaseModelType.Flux2,
+ BaseModelType.ZImage,
+ }
+)
+"""Plannable bases whose Generate graph decodes with the `vae` setting, which selecting a model fills with the VAE its
+default settings name. The CogView4 graph sends no VAE."""
+
+
+def default_vae(model: ModelConfig, models: Sequence[ModelConfig]) -> Optional[ModelConfig]:
+ """The installed VAE a main model decodes with by its default settings (`default_settings.vae`), as Generate applies
+ them when the model is selected (`getModelDefaultVae`): one the model accepts; a key naming no such VAE leaves the
+ `vae` setting empty. It fills the `vae` slot, so the model loader nodes take it over a pipeline's own VAE. None
+ where the graph sends no VAE (`DEFAULT_VAE_BASES`, `_ignores_vae_pick`)."""
+ if not _is_main(model) or model.base not in DEFAULT_VAE_BASES or _ignores_vae_pick(model):
+ return None
+ key = getattr(getattr(model, "default_settings", None), "vae", None)
+ if not key:
+ return None
+ return next((vae for vae in models if vae.key == key and _is_vae(vae) and _accepts(model, vae)), None)
+
+
+_KLEIN_QWEN3: Final = {variant.value: encoder.value for variant, encoder in KLEIN_TO_QWEN3_VARIANT.items()}
+"""The Qwen3 encoder variant each FLUX.2 Klein variant takes."""
+
+_QWEN3_NAMES: Final = {Qwen3VariantType.Qwen3_4B.value: "Qwen3 4B", Qwen3VariantType.Qwen3_8B.value: "Qwen3 8B"}
+"""How a reason names the Qwen3 encoder a Klein variant takes."""
+
+
+def _fits_as_source(main: ModelConfig, source: ModelConfig) -> bool:
+ """Whether a FLUX.2 pipeline is a component source Generate prefers for `main` (`isFlux2DiffusersSourceForModel`):
+ [dev] for [dev], else one whose Qwen3 encoder matches the Klein variant's (`KLEIN_TO_QWEN3_VARIANT`)."""
+ if _variant(main) == Flux2VariantType.Dev.value:
+ return _variant(source) == Flux2VariantType.Dev.value
+ required = _KLEIN_QWEN3.get(_variant(main) or "")
+ return required is None or _KLEIN_QWEN3.get(_variant(source) or "") == required
+
+
+def _flux2_pipelines(models: Sequence[ModelConfig]) -> list[ModelConfig]:
+ """The installed FLUX.2 pipelines Generate offers as component sources, in `models`' order."""
+ return [model for model in models if model.base == BaseModelType.Flux2 and ships_its_vae(model)]
+
+
+def _has_standalone_encoder(main: ModelConfig, models: Sequence[ModelConfig]) -> bool:
+ """Whether a standalone text encoder Generate can fill in for a FLUX.2 main model is installed: a Mistral encoder
+ other than the Ministral 3B for [dev] (`isFlux2MistralEncoder`), else a Qwen3 encoder other than the 0.6B, of the
+ size the Klein variant takes where it names one (`isFlux2Qwen3EncoderForModel`)."""
+ if _variant(main) == Flux2VariantType.Dev.value:
+ return any(
+ model.type == ModelType.MistralEncoder and _variant(model) != MistralVariantType.Ministral3B.value
+ for model in models
+ )
+ required = _KLEIN_QWEN3.get(_variant(main) or "")
+ return any(
+ model.type == ModelType.Qwen3Encoder
+ and _variant(model) != Qwen3VariantType.Qwen3_06B.value
+ and (required is None or _variant(model) == required)
+ for model in models
+ )
+
+
+def _standalone_encoder_name(main: ModelConfig) -> str:
+ """The standalone encoder `_has_standalone_encoder` looks for, as a reason names it."""
+ if _variant(main) == Flux2VariantType.Dev.value:
+ return "Mistral"
+ return _QWEN3_NAMES.get(_KLEIN_QWEN3.get(_variant(main) or "", ""), "Qwen3")
+
+
+def _lacks_text_encoder(main: ModelConfig, models: Sequence[ModelConfig]) -> bool:
+ """Whether Generate cannot compile a FLUX.2 main model's graph for want of a text encoder: the model is no pipeline
+ of its own, no installed pipeline fits it as a component source, and no standalone encoder for it is installed.
+ A pipeline that does not fit gives only its VAE (`getFlux2DiffusersComponentSource`; the model loader node takes
+ a source's encoder only from a fitting one)."""
+ if main.base != BaseModelType.Flux2 or not _is_main(main) or ships_its_vae(main):
+ return False
+ if any(_fits_as_source(main, source) for source in _flux2_pipelines(models)):
+ return False
+ return not _has_standalone_encoder(main, models)
+
+
+def vae_source(model: ModelConfig, models: Sequence[ModelConfig]) -> Optional[ModelConfig]:
+ """The pipeline whose own VAE decodes a main model's generations while its `vae` slot is empty: the model itself
+ (`ships_its_vae`), or for another FLUX.2 model the component source Generate then picks on its own and its graph
+ keeps, whose VAE the FLUX.2 model loader node takes: the first fitting installed FLUX.2 pipeline, else the first
+ one (`getAutoFlux2ComponentSourceModel`), which the graph keeps only beside a standalone text encoder
+ (`getFlux2DiffusersComponentSource`). Generate lists the models in the order the server does, which is `models`'
+ order. None: a standalone VAE decodes, the model's default one included (`default_vae`), or, for a FLUX.2 model
+ without an encoder, no graph compiles (`_lacks_text_encoder`)."""
+ if default_vae(model, models) is not None:
+ return None
+ if ships_its_vae(model):
+ return model
+ if not _is_main(model) or model.base != BaseModelType.Flux2:
+ return None
+ sources = _flux2_pipelines(models)
+ fitting = next((source for source in sources if _fits_as_source(model, source)), None)
+ if fitting is not None:
+ return fitting
+ return sources[0] if sources and _has_standalone_encoder(model, models) else None
+
+
+def own_vae_dtype(pipeline: ModelConfig, vae: VaeDtypes) -> str:
+ """The dtype a pipeline's own VAE loads in (`ships_its_vae`), as its loader yields it."""
+ if _value(getattr(pipeline, "format", None)) == "diffusers":
+ return vae.z_image_pipeline if pipeline.base == BaseModelType.ZImage else FLUX2_PIPELINE_VAE_DTYPE
+ if pipeline.base == BaseModelType.Flux and vae.sdnq_quantized_vae(pipeline):
+ return SDNQ_QUANTIZED_VAE_DTYPE
+ return SDNQ_PIPELINE_VAE_DTYPE
+
+
+def decode_dtypes(model: ModelConfig, precision: str, vae: VaeDtypes, models: Sequence[ModelConfig]) -> tuple[str, ...]:
+ """The dtypes the decode of `model` (a main model or a VAE of a covered base, among the installed `models`) runs
+ in: fixed per base, the `precision` setting for SD3, else the dtype the VAE that decodes loads in, a standalone one
+ or a pipeline's own (`vae_source`)."""
+ lines = DECODE_LINES[model.base]
+ if lines.dtypes:
+ return lines.dtypes
+ if model.base == BaseModelType.StableDiffusion3:
+ return (sd3_dtype(precision),)
+ source = vae_source(model, models)
+ return (vae.standalone_flux if source is None else own_vae_dtype(source, vae),)
+
+
+def _variant(config: ModelConfig) -> Optional[str]:
+ variant = getattr(config, "variant", None)
+ return None if variant is None else _value(variant)
+
+
+def _runs_on_gpu(vae: ModelConfig) -> bool:
+ return getattr(vae, "cpu_only", None) is not True
+
+
+def _accepts(main: ModelConfig, vae: ModelConfig) -> bool:
+ """Whether the main model can decode with the VAE, by the rule its model loader node and Generate's VAE picker
+ read (`accepts_vae`): base, latent channels where they matter, and the main model's variant."""
+ return accepts_vae(main.base, vae.base, getattr(vae, "latent_channels", None), getattr(main, "variant", None))
+
+
+def _is_main(config: ModelConfig) -> bool:
+ return bool(config.type == ModelType.Main)
+
+
+def _is_vae(config: ModelConfig) -> bool:
+ return bool(config.type == ModelType.VAE)
+
+
+def _plannable_main(config: ModelConfig) -> bool:
+ return _is_main(config) and config.base in PLANNABLE_BASES and _variant(config) not in NOT_TEXT_TO_IMAGE_VARIANTS
+
+
+def decode_budget(device_class: DeviceClass, capacity_bytes: Optional[int]) -> int:
+ """The largest calibration reservation a case may take: within the share of the card a decode may claim before the
+ node tiles it up front (`VAE_PRETILE_VRAM_FRACTION`), and within `capacity_bytes`, what the model cache can give on
+ the device; each less the VAE's own weights, which must stay fully resident beside it. Nothing else does: a
+ calibration lock first moves every other unlocked model out (`LoadedModelWithoutConfig.model_on_device`). Past the
+ capacity the cache loads the VAE partly (`partial_residency`), and such a window fits no line. On a device that
+ shares system memory (MPS, an integrated XPU) the capacity follows the RAM the host has available, which can be far
+ below the share of the device's total. `capacity_bytes` None: no reading, and the share of the card alone bounds
+ it."""
+ ceiling = int(VAE_PRETILE_VRAM_FRACTION * device_class.total_mib * 2**20)
+ if capacity_bytes is not None:
+ ceiling = min(ceiling, capacity_bytes)
+ return ceiling - VAE_WEIGHTS_ALLOWANCE_BYTES
+
+
+def case_sides(reservation: Callable[[int], int], budget_bytes: int, floor_bytes: int = 0) -> list[int]:
+ """The square sides of the three cases: about `AREA_FRACTIONS` of the largest area that decodes untiled here.
+
+ The largest area is the largest square, in steps of `SIDE_MULTIPLE` and at most `MAX_SIDE`, whose calibration
+ reservation (the estimate plus calibration headroom, `probe.calibration_reservation`, and never below
+ `floor_bytes`, `device_working_mem_gb`, as the lock reserves it) fits `budget_bytes` (`decode_budget`). A larger
+ decode would be tiled or partly loaded, and neither fits a line. Each fraction of that area is rounded down to a
+ square side that is a multiple of `SIDE_MULTIPLE`; repeated sides are dropped. Returns no sides when the largest is
+ below `MIN_LARGEST_SIDE` or the sides do not span two sizes `MIN_AREA_RATIO` apart.
+ """
+ largest = 0
+ for side in range(SIDE_MULTIPLE, MAX_SIDE + 1, SIDE_MULTIPLE):
+ if max(calibration_reservation(reservation(side)), floor_bytes) > budget_bytes:
+ break
+ largest = side
+ if largest < MIN_LARGEST_SIDE:
+ return []
+ sides: list[int] = []
+ for fraction in AREA_FRACTIONS:
+ side = max(SIDE_MULTIPLE, int(math.sqrt(fraction) * largest) // SIDE_MULTIPLE * SIDE_MULTIPLE)
+ if side not in sides:
+ sides.append(side)
+ if sides[-1] ** 2 < MIN_AREA_RATIO * sides[0] ** 2:
+ return []
+ return sides
+
+
+def _square(reservation: ReservationFunction, estimator: str, dtype: str, side: int) -> int:
+ return reservation(estimator, side, side, dtype)
+
+
+def decode_lines_of(
+ model: ModelConfig, precision: str, vae: VaeDtypes, models: Sequence[ModelConfig]
+) -> list[tuple[str, str]]:
+ """The (estimator, ``decode_<dtype>``) lines a model's decode prices on: a main model or a GPU VAE of a base in
+ `DECODE_LINES`; none for any other model."""
+ if getattr(model, "base", None) not in DECODE_LINES:
+ return []
+ if not (_is_main(model) or (_is_vae(model) and _runs_on_gpu(model))):
+ return []
+ estimator = DECODE_LINES[model.base].estimator
+ return [(estimator, f"decode_{dtype}") for dtype in decode_dtypes(model, precision, vae, models)]
+
+
+def estimated_seconds(cases: Sequence[WorkingMemoryCalibrationCase]) -> int:
+ """A rough order of magnitude: one model load, then per run a fixed cost and a cost per megapixel for each step
+ and for the decode. Not measured; real times vary several-fold with the GPU and the model."""
+ runs = REPETITIONS.warm_up + REPETITIONS.measured
+ seconds: float = SECONDS_MODEL_LOAD
+ for case in cases:
+ megapixels = case.width * case.height / 1e6
+ per_run = SECONDS_PER_RUN + megapixels * (
+ case.steps * SECONDS_PER_MEGAPIXEL_STEP + SECONDS_PER_MEGAPIXEL_DECODE
+ )
+ seconds += runs * per_run
+ return math.ceil(seconds)
+
+
+def _lines(
+ model: ModelConfig,
+ precision: str,
+ vae: VaeDtypes,
+ models: Sequence[ModelConfig],
+ platform: Platform,
+ specs: Mapping[str, EstimatorSpec],
+) -> set[tuple[EntryKey, str]]:
+ """The lines a model's decode prices with on `platform`."""
+ estimator = DECODE_LINES[model.base].estimator
+ spec = specs.get(estimator)
+ carrier = user_fit.carrier_key(estimator, spec.version, platform) if spec is not None else None
+ if carrier is None:
+ return set()
+ return {(carrier, f"decode_{dtype}") for dtype in decode_dtypes(model, precision, vae, models)}
+
+
+def shared_with(
+ target: ModelConfig,
+ models: Sequence[ModelConfig],
+ precision: str,
+ vae: VaeDtypes,
+ platform: Platform,
+ specs: Mapping[str, EstimatorSpec],
+) -> list[WorkingMemoryCalibrationSharedModel]:
+ """The other installed main models and GPU VAEs of a covered base whose decode prices with a line the target's
+ does, on this platform: a line is the shipped entry that carries the values (one estimator may borrow another's)
+ and the operation and dtype."""
+ mine = _lines(target, precision, vae, models, platform, specs)
+ shared = []
+ for model in models:
+ if model.key == target.key or model.base not in DECODE_LINES:
+ continue
+ if not (_is_main(model) or (_is_vae(model) and _runs_on_gpu(model))):
+ continue
+ common = sorted(suffix for _, suffix in mine & _lines(model, precision, vae, models, platform, specs))
+ if common:
+ shared.append(
+ WorkingMemoryCalibrationSharedModel(
+ key=model.key, name=model.name, base=_value(model.base), type=_value(model.type), lines=common
+ )
+ )
+ return sorted(shared, key=lambda model: (model.name, model.key))
+
+
+_STANDALONE_VAE_BASES: Final = frozenset({BaseModelType.Flux, BaseModelType.Flux2, BaseModelType.ZImage})
+"""Bases whose Generate requires a `vae` pick, and fills one, unless a pipeline's own VAE decodes (`vae_source`)."""
+
+
+def _accepted_vaes(main: ModelConfig, models: Sequence[ModelConfig]) -> list[ModelConfig]:
+ return [model for model in models if _is_vae(model) and _accepts(main, model)]
+
+
+def _needs_gpu_vae(main: ModelConfig, models: Sequence[ModelConfig]) -> bool:
+ """Whether a main model decodes with a standalone VAE Generate fills in, and none it accepts runs on the GPU: a
+ decode on the CPU opens no calibration window, and without any VAE the graph does not compile."""
+ if main.base not in _STANDALONE_VAE_BASES or vae_source(main, models) is not None:
+ return False
+ return not any(_runs_on_gpu(vae) for vae in _accepted_vaes(main, models))
+
+
+def _cpu_default_vae(main: ModelConfig, models: Sequence[ModelConfig]) -> Optional[ModelConfig]:
+ """The main model's default VAE (`default_vae`), where it runs on the CPU."""
+ vae = default_vae(main, models)
+ return vae if vae is not None and not _runs_on_gpu(vae) else None
+
+
+def _can_pick_gpu_vae(main: ModelConfig, models: Sequence[ModelConfig]) -> bool:
+ """Whether a case can pick a VAE for the main model that runs on the GPU: its base has a `vae` slot, and a VAE it
+ accepts runs on the GPU."""
+ return main.base in VAE_SLOT_BASES and any(_runs_on_gpu(vae) for vae in _accepted_vaes(main, models))
+
+
+def _decodes_on_the_gpu(main: ModelConfig, models: Sequence[ModelConfig]) -> bool:
+ """Whether a case of the main model can decode on the GPU as far as its default VAE goes: it has none on the CPU, or
+ a case can pick one on the GPU instead (`_gpu_vae_pick`)."""
+ return _cpu_default_vae(main, models) is None or _can_pick_gpu_vae(main, models)
+
+
+def _gpu_vae_pick(main: ModelConfig, models: Sequence[ModelConfig]) -> dict[str, str]:
+ """A `vae` pick where the main model's default VAE runs on the CPU, or where Generate's own fill could land on a VAE
+ that does: the first GPU VAE the main model accepts. None needed where the default VAE runs on the GPU, where every
+ accepted VAE does, where the base has no VAE slot, or where a pipeline's own VAE decodes (`vae_source`), so Generate
+ fills none."""
+ if main.base not in VAE_SLOT_BASES or vae_source(main, models) is not None:
+ return {}
+ default = default_vae(main, models)
+ accepted = _accepted_vaes(main, models)
+ if default is not None:
+ if _runs_on_gpu(default):
+ return {}
+ elif all(_runs_on_gpu(vae) for vae in accepted):
+ return {}
+ gpu = sorted((vae for vae in accepted if _runs_on_gpu(vae)), key=lambda vae: (vae.name, vae.key))
+ return {"vae": gpu[0].key} if gpu else {}
+
+
+def _unsupported(
+ target: ModelConfig, reason: str, device: Optional[DeviceClass], estimators: list[str]
+) -> WorkingMemoryCalibrationPlan:
+ return WorkingMemoryCalibrationPlan(
+ model_key=target.key,
+ supported=False,
+ reason=reason,
+ device_class=WorkingMemoryCalibrationDeviceClassRef(id=device.id, name=device.name) if device else None,
+ calibrated_through=None,
+ estimators=estimators,
+ cases=[],
+ repetitions=REPETITIONS,
+ estimated_seconds=None,
+ shared_with=[],
+ not_covered=[ENCODE_NOT_COVERED] if estimators else [],
+ )
+
+
+def build_plan(
+ target: ModelConfig,
+ models: Sequence[ModelConfig],
+ *,
+ device_class: Optional[DeviceClass],
+ unavailable: Optional[str],
+ platform: Optional[Platform],
+ precision: str,
+ vae_dtypes: VaeDtypes,
+ reservation: ReservationFunction,
+ specs: Mapping[str, EstimatorSpec],
+ capacity_bytes: Optional[int] = None,
+ working_memory_floor_bytes: int = 0,
+ force_tiled_decode: bool = False,
+) -> WorkingMemoryCalibrationPlan:
+ """The plan for calibrating `target`, among the installed `models`, on the GPU of `device_class`.
+
+ `unavailable` says why this machine cannot calibrate (no GPU, several generation devices); `device_class` and
+ `platform` are then None. `reservation` prices an untiled decode on the calibration device; `precision` is the
+ `precision` setting; `vae_dtypes` are the dtypes the VAE loaders choose on the device, so each case sizes the
+ decode in the dtype it runs in; `capacity_bytes` is what the cache can give on the device (`decode_budget`), and
+ `working_memory_floor_bytes` the least working memory a lock reserves there (`device_working_mem_gb`);
+ `force_tiled_decode` is the setting, under which the decode nodes of `FORCE_TILED_BASES` run no untiled decode.
+ """
+ covered = target.base in DECODE_LINES and (_is_main(target) or _is_vae(target))
+ estimators = [DECODE_LINES[target.base].estimator] if covered else []
+ if not covered:
+ kind = f"{_value(target.base)} {_value(target.type)}"
+ return _unsupported(
+ target,
+ f"Calibration covers the decode of SD1, SD2, SDXL, SD3, FLUX.1, FLUX.2, Z-Image and CogView4 main models "
+ f"and their VAEs; this is a {kind} model.",
+ device_class,
+ estimators,
+ )
+
+ main = target
+ if _is_vae(target):
+ if not _runs_on_gpu(target):
+ return _unsupported(
+ target,
+ "This VAE runs on the CPU (cpu_only); calibration measures GPU memory.",
+ device_class,
+ estimators,
+ )
+ candidates = sorted(
+ (
+ model
+ for model in models
+ if _plannable_main(model) and _accepts(model, target) and not _ignores_vae_pick(model)
+ ),
+ key=lambda model: (model.name, model.key),
+ )
+ if not candidates:
+ return _unsupported(
+ target,
+ "A VAE is calibrated by generating with a main model that decodes with it, and no compatible main "
+ "model that takes a VAE pick is installed.",
+ device_class,
+ estimators,
+ )
+ # One whose graph compiles and decodes on the GPU, where there is one; otherwise the first says what it lacks.
+ main = next(
+ (
+ model
+ for model in candidates
+ if not _lacks_text_encoder(model, models) and _decodes_on_the_gpu(model, models)
+ ),
+ candidates[0],
+ )
+ elif target.base not in PLANNABLE_BASES:
+ return _unsupported(
+ target,
+ "This model shares its decode with others but cannot generate from a plain text prompt; calibrate one of "
+ "the models listed as sharing it.",
+ device_class,
+ estimators,
+ )
+ elif _variant(target) in NOT_TEXT_TO_IMAGE_VARIANTS:
+ return _unsupported(
+ target, f"The {_variant(target)} variant does not generate from text alone.", device_class, estimators
+ )
+
+ if unavailable is not None or device_class is None or platform is None:
+ return _unsupported(target, unavailable or "This machine has no GPU to calibrate.", None, estimators)
+
+ if force_tiled_decode and main.base in FORCE_TILED_BASES:
+ # Running the cases untiled would override the setting for these items only, and measure decodes none of this
+ # server's generations runs: no estimate would read the fit.
+ return _unsupported(
+ target,
+ "force_tiled_decode is on, so every decode of this model runs tiled: a calibration measures no untiled "
+ "decode, and no estimate would read one. Set force_tiled_decode: false in invokeai.yaml and restart "
+ "InvokeAI to calibrate.",
+ device_class,
+ estimators,
+ )
+ if _lacks_text_encoder(main, models):
+ encoder = _standalone_encoder_name(main)
+ return _unsupported(
+ target,
+ f"{main.name} has no text encoder Generate can use, so no case compiles: Generate takes it from a FLUX.2 "
+ f"pipeline whose encoder fits the model or from a standalone {encoder} encoder, and a pipeline that does "
+ f"not fit gives only its VAE. Install a {encoder} encoder or a fitting FLUX.2 pipeline.",
+ device_class,
+ estimators,
+ )
+ if not _decodes_on_the_gpu(main, models):
+ cpu_vae = _cpu_default_vae(main, models)
+ assert cpu_vae is not None
+ instead = (
+ "no compatible VAE that runs on the GPU is installed to pick instead"
+ if main.base in VAE_SLOT_BASES
+ else "a calibration cannot pick another VAE for this model"
+ )
+ return _unsupported(
+ target,
+ f"{main.name} decodes with its default VAE, {cpu_vae.name}, which runs on the CPU (cpu_only): a decode on "
+ f"the CPU measures no GPU memory, and {instead}. Clear cpu_only on {cpu_vae.name}, or set another default "
+ f"VAE for {main.name}.",
+ device_class,
+ estimators,
+ )
+ if not _is_vae(target) and _needs_gpu_vae(main, models):
+ return _unsupported(
+ target,
+ f"{main.name} decodes with a standalone VAE, and no compatible VAE that runs on the GPU is installed: a "
+ "decode on the CPU measures no GPU memory. Install a compatible VAE, or clear cpu_only on one.",
+ device_class,
+ estimators,
+ )
+
+ if _is_vae(target) and main.base in VAE_SLOT_BASES:
+ components = {"vae": target.key}
+ else:
+ components = _gpu_vae_pick(main, models)
+
+ lines = DECODE_LINES[target.base]
+ budget = decode_budget(device_class, capacity_bytes)
+ cases: list[WorkingMemoryCalibrationCase] = []
+ # A standalone VAE target decodes as itself; a main model with a pipeline's own VAE, or what fills its slot.
+ decoding = target if _is_vae(target) else main
+ for dtype in decode_dtypes(decoding, precision, vae_dtypes, models):
+ sides = case_sides(partial(_square, reservation, lines.estimator, dtype), budget, working_memory_floor_bytes)
+ for side in sides:
+ cases.append(
+ WorkingMemoryCalibrationCase(
+ id=f"{lines.estimator}-decode-{dtype}-{side}x{side}",
+ model_key=main.key,
+ components=components,
+ width=side,
+ height=side,
+ steps=CASE_STEPS,
+ seed=CASE_SEED,
+ positive_prompt=CASE_PROMPT,
+ negative_prompt="",
+ settings={"vaePrecision": dtype} if lines.precision_setting else {},
+ estimator=lines.estimator,
+ line=f"decode_{dtype}",
+ )
+ )
+ if not cases:
+ return _unsupported(
+ target,
+ f"{device_class.name} cannot hold an untiled decode of {MIN_LARGEST_SIDE}x{MIN_LARGEST_SIDE} with "
+ "calibration headroom and the VAE fully loaded, in the memory free on it now.",
+ device_class,
+ estimators,
+ )
+
+ return WorkingMemoryCalibrationPlan(
+ model_key=target.key,
+ supported=True,
+ reason=None,
+ device_class=WorkingMemoryCalibrationDeviceClassRef(id=device_class.id, name=device_class.name),
+ calibrated_through=main.key if main is not target else None,
+ estimators=estimators,
+ cases=cases,
+ repetitions=REPETITIONS,
+ estimated_seconds=estimated_seconds(cases),
+ shared_with=shared_with(target, models, precision, vae_dtypes, platform, specs),
+ not_covered=[ENCODE_NOT_COVERED],
+ )
diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_store.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_store.py
index 1e7d6a8d24..715e6f3965 100644
--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_store.py
+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_store.py
@@ -26,6 +26,7 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibration
CalibrationDeviceClass,
CalibrationStoreError,
CalibrationStoreFile,
+ CalibrationStoreLockTimeoutError,
CalibrationStoreUnusableError,
)
@@ -87,7 +88,7 @@ def _os_lock(handle: IO[bytes]) -> Iterator[None]:
break
except OSError:
if time.monotonic() > deadline:
- raise CalibrationStoreError(f"Timed out waiting for the lock on {handle.name}") from None
+ raise CalibrationStoreLockTimeoutError(f"Timed out waiting for the lock on {handle.name}") from None
time.sleep(LOCK_RETRY_S)
try:
yield
@@ -104,7 +105,7 @@ def _os_lock(handle: IO[bytes]) -> Iterator[None]:
break
except BlockingIOError:
if time.monotonic() > deadline:
- raise CalibrationStoreError(f"Timed out waiting for the lock on {handle.name}") from None
+ raise CalibrationStoreLockTimeoutError(f"Timed out waiting for the lock on {handle.name}") from None
time.sleep(LOCK_RETRY_S)
try:
yield
@@ -201,12 +202,25 @@ class CalibrationStore:
`CalibrationStoreError`.
The run ids share 256 lock files, `creations/<xx>.lock` by the first two hex digits of the id's SHA-256: the
- folder never holds more, so no file is ever removed (removing one could let a process that opened it before the
- removal and one that creates it anew each hold a lock of their own). Unrelated runs on one file wait for each
- other, which costs little: a creation is a short administrator's action. No store file has such a name.
+ folder never holds more besides `attempts_lock`'s, so no file is ever removed (removing one could let a process
+ that opened it before the removal and one that creates it anew each hold a lock of their own). Unrelated runs
+ on one file wait for each other, which costs little: a creation is a short administrator's action. No store
+ file has such a name.
"""
- stripe = hashlib.sha256(run_id.encode("utf-8")).hexdigest()[:2]
- lock_path = self._dir / "creations" / f"{stripe}.lock"
+ with self._creation_file(f"{hashlib.sha256(run_id.encode('utf-8')).hexdigest()[:2]}.lock"):
+ yield
+
+ @contextmanager
+ def attempts_lock(self) -> Iterator[None]:
+ """Hold the OS lock every creation of an attempt's run takes, `creations/attempts.lock`, as `creation_lock`
+ does. A file of its own: such a creation holds it together with its run's creation lock, and on a file they
+ shared the second lock would wait for the first until it timed out."""
+ with self._creation_file("attempts.lock"):
+ yield
+
+ @contextmanager
+ def _creation_file(self, name: str) -> Iterator[None]:
+ lock_path = self._dir / "creations" / name
try:
lock_path.parent.mkdir(parents=True, exist_ok=True)
handle = open(lock_path, "a+b")
diff --git a/invokeai/app/util/torch_cuda_allocator.py b/invokeai/app/util/torch_cuda_allocator.py
index 280f5bbe75..25c23478a7 100644
--- a/invokeai/app/util/torch_cuda_allocator.py
+++ b/invokeai/app/util/torch_cuda_allocator.py
@@ -4,24 +4,26 @@ import logging
import os
import re
import sys
+from collections.abc import Mapping
from pathlib import Path
-# Every variable torch reads its caching-allocator configuration from.
-_ALLOCATOR_CONF_ENV_VARS = ("PYTORCH_ALLOC_CONF", "PYTORCH_CUDA_ALLOC_CONF", "PYTORCH_HIP_ALLOC_CONF")
+ALLOCATOR_CONF_ENV_VARS = ("PYTORCH_ALLOC_CONF", "PYTORCH_CUDA_ALLOC_CONF", "PYTORCH_HIP_ALLOC_CONF")
+"""Every variable torch reads its caching-allocator configuration from."""
ROCM_WINDOWS_ALLOC_CONF = "expandable_segments:True"
-def expandable_segments_enabled() -> bool:
- """Whether the torch caching allocator runs in expandable-segments mode.
+def expandable_segments_enabled(environ: Mapping[str, str] = os.environ) -> bool:
+ """Whether the torch caching allocator runs in expandable-segments mode, by default in this process.
The mode is configured through the allocator env vars before torch import (InvokeAI's own
`pytorch_cuda_alloc_conf` setting is plumbed into PYTORCH_CUDA_ALLOC_CONF the same way), so
parsing them is authoritative for the life of the process. It lives here, beside the variables, because this
- module imports neither torch nor its callers: the model cache and the working-memory platform.
+ module imports neither torch nor its callers: the model cache and the working-memory platform. `environ` is
+ another process's variables, as a working-memory measurement recorded them.
"""
- for var in _ALLOCATOR_CONF_ENV_VARS:
- if "expandable_segments:true" in os.environ.get(var, "").replace(" ", "").lower():
+ for var in ALLOCATOR_CONF_ENV_VARS:
+ if "expandable_segments:true" in environ.get(var, "").replace(" ", "").lower():
return True
return False
@@ -74,7 +76,7 @@ def apply_rocm_windows_allocator_default(logger: logging.Logger) -> None:
Must run before torch is imported. Any allocator variable already in the environment, like an explicit
`pytorch_cuda_alloc_conf` (whose caller skips this default), wins.
"""
- if sys.platform != "win32" or any(os.environ.get(var) for var in _ALLOCATOR_CONF_ENV_VARS):
+ if sys.platform != "win32" or any(os.environ.get(var) for var in ALLOCATOR_CONF_ENV_VARS):
return
if not _installed_torch_is_rocm():
return
diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.py
index e11c945e8b..cdddcbb3ce 100644
--- a/invokeai/backend/model_manager/load/load_base.py
+++ b/invokeai/backend/model_manager/load/load_base.py
@@ -182,7 +182,7 @@ class LoadedModelWithoutConfig:
# invariant turning this loop into a spin.
assert settled, "uncapped continue_lock pass did not settle"
- def _lock_on_device(self, working_mem_bytes: Optional[int]) -> None:
+ def _lock_on_device(self, working_mem_bytes: Optional[int], *, offload_others: bool = False) -> None:
"""Lock the model onto its compute device and repair its required tensors there. Nothing stays locked if this
raises.
@@ -191,6 +191,11 @@ class LoadedModelWithoutConfig:
a co-lock, which moves weights and is kept out of the window's peak; on another thread it voids the window.
The lock is in `probe.locking` from before `armed` is read until it has settled or failed, so a window that
opens on this cache meanwhile is void even if this read missed the scope arming.
+
+ `offload_others`: first move every other unlocked model on the device to RAM whole, within that interval. A
+ calibration lock asks for it (`model_on_device`): the lock itself offloads only the shortfall it predicts and
+ splits the last model it moves, and a split can free a little less than predicted, so the measured model would
+ run partly resident and its window fit no line. Locked models, a window's co-locks among them, stay.
"""
observed = locked = False
probe.locking.append(self._cache)
@@ -198,6 +203,11 @@ class LoadedModelWithoutConfig:
observed = probe.armed
if observed:
probe.lock_started(self._cache, self._cache_record)
+ if offload_others:
+ # The global load lock before the cache's own, as `_lock_paced` takes them: a move to RAM loads state
+ # dicts, which must not overlap a model construction.
+ with MODEL_LOAD_LOCK.read_lock():
+ self._cache.offload_unlocked_models_from_vram(keep_cache_keys=(self._cache_record.key,))
self._lock_paced(working_mem_bytes)
locked = True
self._end_first_use_window()
@@ -234,8 +244,9 @@ class LoadedModelWithoutConfig:
model.
:param working_memory: A working-memory estimate whose `reservation_bytes` is kept available instead; see
`invokeai.backend.working_memory`. Pass this or `working_mem_bytes`, not both. Inside a calibration scope
- (`working_memory.probe`) on a GPU, the lock reserves calibration headroom on top and the probe measures the
- operation from the settled lock until the unlock.
+ (`working_memory.probe`) on a GPU, the lock first moves every other unlocked model on the device to RAM,
+ reserves calibration headroom on top, and the probe measures the operation from the settled lock until the
+ unlock.
"""
if isinstance(working_mem_bytes, WorkingMemoryEstimate):
raise TypeError(
@@ -256,7 +267,7 @@ class LoadedModelWithoutConfig:
working_mem_bytes = probe.calibration_reservation(working_mem_bytes)
message += f"; the calibration lock reserves {working_mem_bytes / 2**20:.0f} MB"
InvokeAILogger.get_logger(__name__).debug(message)
- self._lock_on_device(working_mem_bytes)
+ self._lock_on_device(working_mem_bytes, offload_others=calibration is not None)
window = None
try:
if calibration is not None:
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index 019035afb3..cf9c921a81 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -319,17 +319,8 @@ class ModelLoader(ModelLoaderBase):
return (model_base / config.path).resolve()
def _torch_dtype_avoiding_float16(self) -> torch.dtype:
- """The configured dtype, except float16: bfloat16 where the device has it, float32 otherwise.
-
- For the FLUX autoencoders, which are broken in float16 -- the dtype `precision: auto` picks on
- CUDA and MPS. A float32 or bfloat16 request is kept as it is.
- """
- if self._torch_dtype != torch.float16:
- return self._torch_dtype
- try:
- return torch.empty(0, dtype=torch.bfloat16, device=self._torch_device).dtype
- except TypeError:
- return torch.float32
+ """The configured dtype on this loader's device, except float16 (`TorchDevice.dtype_avoiding_float16`)."""
+ return TorchDevice.dtype_avoiding_float16(self._torch_dtype, self._torch_device)
def _get_execution_device(
self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.py
index 84e9722dd2..d0610b528e 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -2392,9 +2392,9 @@ class ModelCache:
vram_total_available_to_cache = int(self._max_vram_cache_size_gb * GB) - working_mem_bytes
return vram_total_available_to_cache - self._get_vram_in_use() - reserve_vram_bytes
- if self._execution_device.type == "cuda":
- vram_allocated = torch.cuda.memory_allocated(self._execution_device)
- vram_free, _vram_total = TorchDevice.cuda_mem_get_info(self._execution_device)
+ # Shared-memory devices (MPS, Intel integrated GPUs) count free system RAM, not device totals.
+ vram_available_to_process = TorchDevice.memory_available_to_process(self._execution_device)
+ if device_has_dedicated_vram(self._execution_device):
# Blocks the caching allocator holds but is not using are just as available to this
# process as driver-free memory: the allocator reuses them directly, and empty_cache()
# returns whole unoccupied segments to the driver. mem_get_info() alone counts them as
@@ -2404,25 +2404,9 @@ class ModelCache:
# minimum weight set (observed: a fully-evictable multi-GB reserve left a 20 GB
# transformer at 0% residency while the allocator happily reused the "missing" memory
# for activations). Credit the reclaimable reserve, excluding intra-segment
- # fragmentation slack that a large contiguous allocation could not use.
- vram_available_to_process = vram_free + vram_allocated + self._get_reclaimable_allocator_bytes()
- elif self._execution_device.type == "xpu" and device_has_dedicated_vram(self._execution_device):
- vram_allocated = torch.xpu.memory_allocated(self._execution_device)
- vram_free, _vram_total = TorchDevice.xpu_mem_get_info(self._execution_device)
- vram_available_to_process = vram_free + vram_allocated + self._get_reclaimable_allocator_bytes()
- elif self._execution_device.type in ("mps", "xpu"):
- # Shared-memory devices: MPS, and Intel integrated GPUs, whose reported "VRAM" is
- # system RAM. Budget against actual free system memory instead of device totals.
- # TODO(ryand): Is it accurate that MPS shares memory with the CPU?
- vram_reserved = (
- torch.mps.driver_allocated_memory()
- if self._execution_device.type == "mps"
- else torch.xpu.memory_reserved(self._execution_device)
- )
- vram_free = psutil.virtual_memory().available
- vram_available_to_process = vram_free + vram_reserved
- else:
- raise ValueError(f"Unsupported execution device: {self._execution_device.type}")
+ # fragmentation slack that a large contiguous allocation could not use. A shared
+ # device's figure already counts the backend's whole reserve.
+ vram_available_to_process += self._get_reclaimable_allocator_bytes()
vram_total_available_to_cache = vram_available_to_process - working_mem_bytes
vram_cur_available_to_cache = vram_total_available_to_cache - self._get_vram_in_use()
@@ -2475,6 +2459,23 @@ class ModelCache:
"""
return self._get_vram_available(None, honor_cap=False)
+ def calibration_capacity(self) -> int:
+ """What the measured lock of a working-memory calibration can get on the execution device, its working memory
+ and the model it locks together: `_get_vram_available` without a working-memory reserve, which the calibration
+ sizes itself, as it stands once the calibration's pre-lock offload (`offload_unlocked_models_from_vram`) ran.
+
+ On a device with dedicated VRAM that offload moves every other unlocked model out, so what the cache holds now
+ counts as available. On one whose memory is system RAM (MPS, an integrated GPU) it moves nothing, so what is
+ allocated now stays subtracted, as the lock subtracts it. Within `max_vram_cache_size_gb` (the lock budgets
+ against the cap; the device must still hold it), less `reserve_vram_gb`. Without the allocator's reclaimable
+ credit: a plan does not count on blocks the offload's `empty_cache` returns only when it runs.
+ """
+ live = 0 if device_has_dedicated_vram(self._execution_device) else self._get_vram_in_use()
+ available = TorchDevice.memory_available_to_process(self._execution_device) - live
+ if self._max_vram_cache_size_gb is not None:
+ available = min(available, int(self._max_vram_cache_size_gb * GB) - live)
+ return available - int(self._reserve_vram_gb * GB)
+
def _get_vram_in_use(self) -> int:
"""Get the amount of VRAM currently in use by the cache."""
if self._execution_device.type == "cuda":
@@ -3189,6 +3190,23 @@ class ModelCache:
keep = set(keep_model_keys)
return self._offload_entries_from_vram(lambda key: key.split(":", 1)[0] not in keep)
+ @synchronized
+ def offload_unlocked_models_from_vram(self, keep_cache_keys: Collection[str] = ()) -> int:
+ """Move every unlocked entry but those in `keep_cache_keys` from VRAM to RAM whole, keeping it cached.
+
+ `keep_cache_keys` are exact cache keys: keeping a submodel (`<model key>:vae`) keeps none of its siblings, unlike
+ `offload_models_from_vram_except`. Each entry leaves whole, where `lock()` moves out only the shortfall it
+ predicts and so splits the last model it reaches. A working-memory calibration calls this before its measured
+ lock (`LoadedModelWithoutConfig.model_on_device`), so that lock has nothing to split.
+
+ Returns the number of VRAM bytes freed.
+ """
+ if not device_has_dedicated_vram(self._execution_device):
+ # CPU, MPS, integrated GPUs: their "VRAM" is system RAM, so moving models out frees nothing.
+ return 0
+ keep = set(keep_cache_keys)
+ return self._offload_entries_from_vram(lambda key: key not in keep)
+
def _offload_entries_from_vram(self, select: Callable[[str], bool]) -> int:
bytes_freed = 0
for key, entry in list(self._cached_models.items()):
diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.py
index 894b980c26..1706c12aa0 100644
--- a/invokeai/backend/util/devices.py
+++ b/invokeai/backend/util/devices.py
@@ -4,6 +4,7 @@ from collections import Counter, defaultdict
from functools import wraps
from typing import Dict, Literal, Optional, Protocol, Union
+import psutil
import torch
from deprecated import deprecated
@@ -586,6 +587,29 @@ class TorchDevice:
free = min(free, max(budget - (total - free), 0))
return free, total
+ @classmethod
+ def memory_available_to_process(cls, device: torch.device) -> int:
+ """What this process can hold on a GPU `device`, what it holds there included.
+
+ On a device with its own memory (`device_has_dedicated_vram`): what the driver has free plus what torch has
+ allocated. On one whose "VRAM" is system RAM (MPS, an integrated XPU): the system's available RAM plus what the
+ backend holds for this process (`torch.mps.driver_allocated_memory`, `torch.xpu.memory_reserved`), since the
+ device totals say nothing about what the host still has free. The model cache budgets from it
+ (`ModelCache._get_vram_available`, which adds the caching allocator's reclaimable blocks on a dedicated
+ device), and a working-memory calibration plan sizes its cases from it. Raises ValueError for a device that is
+ not a GPU.
+ """
+ if device.type == "cuda":
+ free, _ = cls.cuda_mem_get_info(device)
+ return free + torch.cuda.memory_allocated(device)
+ if device.type == "xpu" and device_has_dedicated_vram(device):
+ free, _ = cls.xpu_mem_get_info(device)
+ return free + torch.xpu.memory_allocated(device)
+ if device.type in ("mps", "xpu"):
+ held = torch.mps.driver_allocated_memory() if device.type == "mps" else torch.xpu.memory_reserved(device)
+ return int(psutil.virtual_memory().available) + int(held)
+ raise ValueError(f"Unsupported execution device: {device.type}")
+
@classmethod
def _to_dtype(cls, precision_name: TorchPrecisionNames) -> torch.dtype:
return NAME_TO_PRECISION[precision_name]
@@ -625,6 +649,22 @@ class TorchDevice:
return torch.float32
return torch.bfloat16
+ @classmethod
+ def dtype_avoiding_float16(cls, dtype: torch.dtype, device: torch.device) -> torch.dtype:
+ """`dtype`, except float16: bfloat16 where `device` has it, float32 otherwise.
+
+ The dtype of the autoencoders that are broken or unstable in float16 -- the dtype
+ `precision: auto` picks on CUDA and MPS: the standalone FLUX.1 and FLUX.2 VAEs and the
+ Qwen-Image-2.1 pipeline's. A float32 or bfloat16 request is kept as it is. The loaders take it
+ from the configured dtype, and a calibration plan sizes its FLUX decodes by it.
+ """
+ if dtype != torch.float16:
+ return dtype
+ try:
+ return torch.empty(0, dtype=torch.bfloat16, device=device).dtype
+ except TypeError:
+ return torch.float32
+
@classmethod
def choose_anima_inference_dtype(cls, device: Optional[torch.device] = None) -> torch.dtype:
"""Choose the inference dtype for Anima models, honoring config.precision.
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index f1b0e841ca..788fbaa39a 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -150,7 +150,7 @@ def _convolution_coefficients(*dtypes: str) -> frozenset[str]:
)
-def _dtype_name(dtype: torch.dtype) -> str:
+def dtype_name(dtype: torch.dtype) -> str:
name = _DTYPE_NAMES.get(dtype)
if name is None:
raise ValueError(f"No VAE working-memory coefficients are measured for {dtype}.")
@@ -326,7 +326,7 @@ def estimate_vae_working_memory_sd15_sdxl(
"height": height,
"width": width,
"tile": tile_size,
- "dtype": _dtype_name(run_dtype),
+ "dtype": dtype_name(run_dtype),
"vae_class": "AutoencoderKL" if isinstance(vae, AutoencoderKL) else "AutoencoderTiny",
"upcast_weight_bytes": _upcast_weight_bytes(vae, run_dtype),
}
@@ -356,7 +356,7 @@ def _single_pass_features(
"operation": operation,
"height": height,
"width": width,
- "dtype": _dtype_name(dtype),
+ "dtype": dtype_name(dtype),
"score_matrix_bytes": _vae_mid_block_score_matrix_bytes(height, width, dtype, device=device),
}
@@ -396,7 +396,7 @@ def estimate_vae_working_memory_cogview4(
"operation": operation,
"height": latent_scale_factor_for_operation * image_tensor.shape[-2],
"width": latent_scale_factor_for_operation * image_tensor.shape[-1],
- "dtype": _dtype_name(_compute_dtype(vae)),
+ "dtype": dtype_name(_compute_dtype(vae)),
}
return _estimate(VAE_COGVIEW4_SPEC, features, device)
@@ -544,7 +544,7 @@ def estimate_vae_working_memory_flux(
"operation": operation,
"height": out_h,
"width": out_w,
- "dtype": _dtype_name(dtype),
+ "dtype": dtype_name(dtype),
"tile": tile,
"score_matrix_bytes": _vae_mid_block_score_matrix_bytes(score_h, score_w, dtype, device=device),
}
@@ -668,7 +668,7 @@ def estimate_vae_working_memory_flux2(
"width": out_w,
"tile": tile,
"batch_size": batch_size,
- "dtype": _dtype_name(dtype),
+ "dtype": dtype_name(dtype),
"score_matrix_bytes": sdpa_score_matrix_bytes(
device=device,
dtype=dtype,
@@ -1201,3 +1201,31 @@ def estimate_vae_working_memory_sd3(
"""
device = device if device is not None else TorchDevice.choose_torch_device()
return _estimate(VAE_SD3_SPEC, _single_pass_features(operation, image_tensor, vae, device), device)
+
+
+def estimate_untiled_vae_decode(
+ estimator: str, height: int, width: int, dtype: str, device: torch.device
+) -> WorkingMemoryEstimate:
+ """The estimate an untiled single-image decode of `height` x `width` output pixels in `dtype` gets from the decode
+ node that prices with `estimator`, on `device`: the features each estimator builds from its VAE, without one.
+
+ For planning sizes before anything is loaded (a calibration plan). The SD1/SDXL VAE is priced as one already in
+ `dtype`, so without the growth of an in-place cast, which a first fp32 decode after an fp16 one adds on top.
+ """
+ torch_dtype = {name: candidate for candidate, name in _DTYPE_NAMES.items()}.get(dtype)
+ if torch_dtype is None:
+ raise ValueError(f"No VAE working-memory coefficients are measured for {dtype}.")
+ features: dict[str, FeatureValue] = {"operation": "decode", "height": height, "width": width, "dtype": dtype}
+ if estimator == VAE_COGVIEW4_SPEC.id:
+ return _estimate(VAE_COGVIEW4_SPEC, features, device)
+ features["score_matrix_bytes"] = _vae_mid_block_score_matrix_bytes(height, width, torch_dtype, device=device)
+ if estimator == VAE_SD3_SPEC.id:
+ return _estimate(VAE_SD3_SPEC, features, device)
+ if estimator == VAE_FLUX_SPEC.id:
+ return _estimate(VAE_FLUX_SPEC, features | {"tile": None}, device)
+ if estimator == VAE_FLUX2_SPEC.id:
+ return _estimate(VAE_FLUX2_SPEC, features | {"tile": None, "batch_size": 1}, device)
+ if estimator == VAE_SD_SPEC.id:
+ sd_features = features | {"tile": None, "vae_class": "AutoencoderKL", "upcast_weight_bytes": 0}
+ return _estimate(VAE_SD_SPEC, sd_features, device)
+ raise ValueError(f"No untiled decode is priced by working-memory estimator '{estimator}'.")
diff --git a/invokeai/backend/working_memory/bounds.py b/invokeai/backend/working_memory/bounds.py
new file mode 100644
index 0000000000..48f1975167
--- /dev/null
+++ b/invokeai/backend/working_memory/bounds.py
@@ -0,0 +1,105 @@
+"""How a measured point bounds the estimate for its features.
+
+One rule, read by the data test (`tests/backend/working_memory/test_shipped_coefficients.py`), which holds the shipped
+data to it, and by `scripts/working_memory/build_shipped.py`, which refuses to write data that breaks it:
+
+- Lower bound. The model cache consumes an estimate as ``free >= estimate``, so the estimate must be at least the point.
+ Where only analytic terms decide it (a materialized score matrix), the cache's `device_working_mem_gb` floor counts.
+- Upper bound, for points that hold one (`MeasuredPoint.holds_upper_bound`): where a fitted term decides an in-fit
+ point, the estimate is at most `MAX_OVER_RESERVATION` times the point, its listed `UPPER_BOUND_EXCEPTIONS` ratio, or
+ its tighter `max_ratio`, which applies whichever term decides. A reservation the operation never uses is model
+ weights evicted for nothing.
+"""
+
+from collections.abc import Iterable, Mapping
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Final, Optional
+
+from invokeai.app.services.config.config_default import InvokeAIAppConfig
+from invokeai.backend.working_memory.coefficients import MeasuredPoint, WorkingMemoryData, resolve_coefficients
+from invokeai.backend.working_memory.estimate import WorkingMemoryEstimate
+from invokeai.backend.working_memory.platform import Platform
+
+if TYPE_CHECKING:
+ from invokeai.backend.working_memory.spec import EstimatorSpec
+
+MAX_OVER_RESERVATION: Final = 1.3
+"""How far above a measured point a reservation may sit where a fitted coefficient decides it, unless the point is
+listed in `UPPER_BOUND_EXCEPTIONS` or carries a tighter `max_ratio`."""
+
+WORKING_MEMORY_FLOOR: Final = int(InvokeAIAppConfig.model_fields["device_working_mem_gb"].default * 2**30)
+"""What `ModelCache._working_mem_reserve` floors every reservation at. The field default, not a config instance an
+environment variable could move."""
+
+UPPER_BOUND_EXCEPTIONS: Final[Mapping[str, float]] = MappingProxyType(
+ {
+ "vae.sd-miopen,native,windows-decode-fp16-1280x1280-scores-RX9060XT-demand_peak": 1.33,
+ "vae.sd-miopen,native,windows-encode-fp16-1024x1024-scores-RX9060XT-demand_peak": 1.57,
+ "vae.sd-miopen,native,windows-encode-fp16-1280x1280-scores-RX9060XT-demand_peak": 1.78,
+ "vae.flux-miopen,native,windows-decode-bf16-512x512-scores-RX9060XT-demand_peak": 1.33,
+ "vae.flux2-miopen,native,windows-decode-bf16-512x512-scores-RX9060XT-demand_peak": 1.33,
+ }
+)
+"""In-fit points, by `point_id`, whose envelope sits more than 1.3x above them, with the ratio they are held to
+instead. All are MIOpen with the native allocator on Windows, where the demand is concave in the size: first-run driver
+spikes at small sizes and a second run reserving up to 1.6x the first at large ones, so a line that covers every point
+cannot stay within 1.3x of all of them. Windows ROCm defaults to expandable segments; this is the override's price."""
+
+
+def point_id(point: MeasuredPoint) -> str:
+ """A readable id of a point: estimator, platform, operation, dtype, size, tile, batch, prompt tokens, a
+ materialized score matrix, card and method. The platform, operation and dtype show where the point names them: an
+ estimator keyed by no platform trait records none, and one whose features name no operation or dtype (the
+ MOSS-Image denoise) none of those."""
+ features = point.features
+ platform = ",".join(point.platform.values())
+ head = [point.estimator, *([platform] if platform else [])]
+ head += [str(features[name]) for name in ("operation", "dtype") if name in features]
+ shape = f"{features.get('height')}x{features.get('width')}"
+ tile = f"-tile{features['tile']}" if features.get("tile") is not None else ""
+ batch = f"-b{features['batch_size']}" if features.get("batch_size", 1) != 1 else ""
+ text = f"-text{features['text_tokens']}" if "text_tokens" in features else ""
+ scores = "-scores" if features.get("score_matrix_bytes") else ""
+ out_of_fit = "-outfit" if not point.in_fit else ""
+ card = point.device.split(" (")[0].replace(" ", "")
+ return f"{'-'.join(head)}-{shape}{tile}{batch}{text}{scores}{out_of_fit}-{card}-{point.method}"
+
+
+_ANY_PLATFORM: Final = Platform("cudnn", "native", "linux")
+"""Where a point of an estimator keyed by no platform trait is evaluated. Its one entry resolves alike on every
+platform, so any will do; this one is measured."""
+
+
+def _platform_of(point: MeasuredPoint, spec: "EstimatorSpec") -> Platform:
+ """The platform a point is evaluated on. One that names no OS measured what holds on every OS. One of an estimator
+ keyed by no platform trait names nothing (`_ANY_PLATFORM`)."""
+ if not spec.platform_keys:
+ return _ANY_PLATFORM
+ return Platform(**({"os": "other"} | point.platform)) # type: ignore[arg-type]
+
+
+def evaluate_point(
+ point: MeasuredPoint, spec: "EstimatorSpec", data: Iterable[WorkingMemoryData]
+) -> WorkingMemoryEstimate:
+ """The estimate for the point's features, priced with the coefficients `data` gives its platform."""
+ return spec.evaluate(point.features, resolve_coefficients(data, spec, _platform_of(point, spec), origin="data"))
+
+
+def fitted_decides(estimate: WorkingMemoryEstimate) -> bool:
+ return any(term.included and term.coefficient is not None for term in estimate.terms)
+
+
+def bound_violation(point: MeasuredPoint, estimate: WorkingMemoryEstimate) -> Optional[str]:
+ """Why `estimate` breaks a bound `point` sets for it, or None."""
+ fitted = fitted_decides(estimate)
+ reserved = estimate.reservation_bytes if fitted else max(estimate.reservation_bytes, WORKING_MEMORY_FLOOR)
+ if reserved < point.measured_bytes:
+ return f"reserves {reserved / 2**30:.3f} GiB for a measured {point.measured_bytes / 2**30:.3f} GiB"
+ # An out-of-fit point checks another term, and a lower-bound-only point is no cold first run: neither caps.
+ if point.holds_upper_bound and (point.max_ratio is not None or (fitted and point.in_fit)):
+ default = UPPER_BOUND_EXCEPTIONS.get(point_id(point), MAX_OVER_RESERVATION)
+ max_ratio = point.max_ratio if point.max_ratio is not None else default
+ ratio = estimate.reservation_bytes / point.measured_bytes
+ if ratio > max_ratio:
+ return f"reserves {ratio:.2f}x the measured peak, over {max_ratio}x"
+ return None
diff --git a/invokeai/backend/working_memory/coefficients.py b/invokeai/backend/working_memory/coefficients.py
index 93de1c84a7..0321702dbc 100644
--- a/invokeai/backend/working_memory/coefficients.py
+++ b/invokeai/backend/working_memory/coefficients.py
@@ -14,7 +14,7 @@ from dataclasses import asdict, dataclass
from importlib.resources import files
from importlib.resources.abc import Traversable
from types import MappingProxyType
-from typing import TYPE_CHECKING, Literal, Self
+from typing import TYPE_CHECKING, Final, Literal, Self
from pydantic import BaseModel, ConfigDict, ValidationError, model_validator
@@ -69,17 +69,21 @@ class CoefficientEntry(_DataModel):
return self
+LOWER_BOUND_ONLY_METHODS: Final = frozenset({"probe_demand"})
+"""Point methods that bound an estimate from below only (see `MeasuredPoint.holds_upper_bound`)."""
+
+
class MeasuredPoint(_DataModel):
"""One measured operation. The estimate for its features must be at least `measured_bytes`, and where a fitted
- term decides an in-fit point, at most 1.3 times that (or `max_ratio`). Measured with the model's weights already in
- place, so `measured_bytes` is the operation's working memory alone."""
+ term decides an in-fit point that `holds_upper_bound`, at most 1.3 times that (or `max_ratio`). Measured with the
+ model's weights already in place, so `measured_bytes` is the operation's working memory alone."""
estimator: str
version: int
platform: dict[str, str]
features: dict[str, FeatureValue]
measured_bytes: int
- method: Literal["reserved_peak", "driver_peak", "demand_peak", "device_peak"]
+ method: Literal["reserved_peak", "driver_peak", "demand_peak", "probe_demand", "device_peak"]
"""How `measured_bytes` was read, each as a peak over its value just before the operation:
- ``reserved_peak``: the caching allocator's reserved bytes, one fresh process per point. Reserved rather than
@@ -89,9 +93,14 @@ class MeasuredPoint(_DataModel):
- ``demand_peak``: the largest of the driver-level, the reserved and the allocated peak, the larger of two runs,
one fresh process per point. The driver-level figure is what reserved misses: on HIP the first operation of a
process maps ~300 MiB beyond ``max_memory_reserved``.
- - ``device_peak``: the drop in the driver's free memory (`torch.cuda.mem_get_info`, polled during the operation),
- the larger over the forwards measured. It counts the allocator's reserve and whatever is allocated around it, so
- it is at least the reserved peak."""
+ - ``device_peak``: the drop in the driver's free memory (`torch.cuda.mem_get_info`, polled during the operation)
+ below its value just before it, the larger over the forwards measured. It counts the allocator's reserve and
+ whatever is allocated around it, so it is at least the reserved peak.
+ - ``probe_demand``: the working-memory probe's ``demand_bytes`` (`probe.MeasuredWindow`), the largest over the
+ valid, fit-eligible windows of calibration runs in a running server, warm-ups included.
+ `scripts/working_memory/build_shipped.py` builds these points from calibration store exports. A lower bound
+ only: a warm window in a running server can read well below the cold first run after a server start, which is
+ the worst case the reservation must cover, so it may raise a line but never caps one."""
device: str
provenance: str
max_ratio: float | None = None
@@ -102,6 +111,17 @@ class MeasuredPoint(_DataModel):
math attention kernel forced, whose score matrix shares the forward with the convolutions. The fit leaves it out,
and it gets the lower bound only."""
+ @model_validator(mode="after")
+ def _max_ratio_needs_an_upper_bound(self) -> Self:
+ if self.max_ratio is not None and not self.holds_upper_bound:
+ raise ValueError(f"a {self.method} point bounds its estimate from below only; it takes no max_ratio")
+ return self
+
+ @property
+ def holds_upper_bound(self) -> bool:
+ """Whether the point also bounds its estimate from above: a fresh-process peak, not a `probe_demand` window."""
+ return self.method not in LOWER_BOUND_ONLY_METHODS
+
class WorkingMemoryData(_DataModel):
"""One file under `data/`."""
diff --git a/invokeai/backend/working_memory/counters.py b/invokeai/backend/working_memory/counters.py
index 75c4514c46..3d7d7e5f02 100644
--- a/invokeai/backend/working_memory/counters.py
+++ b/invokeai/backend/working_memory/counters.py
@@ -168,27 +168,49 @@ def fdinfo_vram_bytes(pdev: str) -> Optional[int]:
return total
+def driver_method(backend: Optional[Backend], platform_name: Optional[str] = None) -> Method:
+ """The reader a `backend` device's driver figure comes from on the OS `platform_name` (a ``sys.platform`` value,
+ this process's by default), ``torch-only`` where there is none. A reading that fails falls back to ``torch-only``
+ too."""
+ platform_name = sys.platform if platform_name is None else platform_name
+ if backend in ("cuda", "hip") and platform_name == "win32":
+ return "windows-d3dkmt"
+ if backend == "cuda" and platform_name.startswith("linux"):
+ return "nvml"
+ if backend == "hip" and platform_name.startswith("linux"):
+ return "fdinfo"
+ if backend == "mps":
+ return "mps-driver"
+ if backend == "xpu":
+ return "xpu-sysman"
+ return "torch-only"
+
+
+def method_verified(backend: Backend, platform_name: Optional[str] = None) -> bool:
+ """Whether the windows of a `backend` device on this OS read a driver figure verified on real hardware."""
+ return (driver_method(backend, platform_name), backend) in VERIFIED_METHODS
+
+
def _driver_reading(device: torch.device) -> tuple[Optional[int], Optional[int], Optional[int], Method]:
"""``(driver, paged, device_used, method)`` for `device` on this platform."""
backend = backend_for(device)
driver: Optional[int] = None
paged: Optional[int] = None
device_used: Optional[int] = None
- method: Method = "torch-only"
+ method = driver_method(backend)
try:
- if backend in ("cuda", "hip") and sys.platform == "win32":
- driver, paged, method = wddm.process_local_usage(device), wddm.process_paged_bytes(device), "windows-d3dkmt"
- elif backend == "cuda" and sys.platform.startswith("linux"):
- driver, method = nvml.process_used_memory(device), "nvml"
- elif backend == "hip" and sys.platform.startswith("linux"):
+ if method == "windows-d3dkmt":
+ driver, paged = wddm.process_local_usage(device), wddm.process_paged_bytes(device)
+ elif method == "nvml":
+ driver = nvml.process_used_memory(device)
+ elif method == "fdinfo":
index = device.index if device.index is not None else torch.cuda.current_device()
- driver, method = fdinfo_vram_bytes(pci_address(index)), "fdinfo"
- elif backend == "mps":
- driver, method = int(torch.mps.driver_allocated_memory()), "mps-driver"
- elif backend == "xpu":
+ driver = fdinfo_vram_bytes(pci_address(index))
+ elif method == "mps-driver":
+ driver = int(torch.mps.driver_allocated_memory())
+ elif method == "xpu-sysman":
info = xpu_memory_info(device)
device_used = None if info is None else info[1] - info[0]
- method = "xpu-sysman"
except Exception:
InvokeAILogger.get_logger(__name__).debug(f"Driver memory reading for {device} failed", exc_info=True)
return None, None, None, "torch-only"
diff --git a/invokeai/backend/working_memory/fit.py b/invokeai/backend/working_memory/fit.py
index 25708c52c8..b1fd34a038 100644
--- a/invokeai/backend/working_memory/fit.py
+++ b/invokeai/backend/working_memory/fit.py
@@ -7,19 +7,26 @@ size. Each carried pair is the upper envelope of the points it is resolved for (
the estimator borrows -- when it is a single-sample, untiled operation of that pair (`in_fit` unless measured out of
regime) with no weight growth. Tiled points bound their estimates but fit nothing: the tile term reuses the untiled
pair. Nor does a point whose VAE an in-place cast grew (`upcast_weight_bytes`): its demand includes the growth, which
-the estimate prices as a term of its own.
+the estimate prices as a term of its own. A point that bounds its estimate from below only
+(`MeasuredPoint.holds_upper_bound`, a `probe_demand` window) is covered by the line and can raise it, but takes no part
+in choosing it: the fresh-process points cap a line. A line is fitted only once its fresh-process points alone span
+two sizes `MIN_AREA_RATIO` apart (`fitted_pair`); until then it stays a stand-in, which the other points bound from
+below.
`tests/backend/working_memory/test_shipped_coefficients.py` holds every carried value on such a line that is not a
declared stand-in to `fitted_values` of the shipped points, so a new point that moves a fit fails there with the value
to ship. A value on no pixel line is hand-set, which `hand_set_values` allows only for an estimator keyed by no platform
trait: the MOSS-Image denoise's `k_token`, bytes per attended token with no base. Its points still decide and bound it
there; this module fits pixel lines only.
+
+A user's own calibration fits the same lines from its windows (`user_pair`, read by `user_fit.py`), with
+`USER_MARGIN`, the same margin.
"""
import math
from collections.abc import Iterable, Mapping, Sequence
from fractions import Fraction
-from typing import TYPE_CHECKING, Final
+from typing import TYPE_CHECKING, Final, NamedTuple, Optional
from invokeai.backend.working_memory.coefficients import CoefficientEntry, MeasuredPoint, WorkingMemoryData, find_entry
@@ -30,6 +37,10 @@ SHIPPED_MARGIN: Final = Fraction(1, 20)
"""What the shipped slope and intercept add over the envelope of their points: 5%, for the runs and cards the points
do not cover."""
+USER_MARGIN: Final = SHIPPED_MARGIN
+"""What a user calibration's slope and intercept add over the envelope of its points: the shipped margin. A user line
+measures the card it prices, and the windows that would inflate it (fragmented, partly resident) never join it."""
+
MIN_AREA_RATIO: Final = 2
"""How far apart the sizes a line is fitted on must lie, as a ratio of pixel counts: closer points pin the intercept
no better than their noise."""
@@ -44,20 +55,36 @@ def entry_key(entry: CoefficientEntry | MeasuredPoint) -> EntryKey:
return (entry.estimator, entry.version, tuple(sorted(entry.platform.items())))
-def upper_envelope(points: Sequence[tuple[int, int]]) -> tuple[Fraction, Fraction]:
+class FitPoint(NamedTuple):
+ pixels: int
+ bytes: int
+ caps: bool
+ """Whether the point takes part in choosing the line (`MeasuredPoint.holds_upper_bound`); every point is covered."""
+
+
+def spans(sizes: Iterable[int]) -> bool:
+ """Whether the pixel counts include two at least `MIN_AREA_RATIO` apart: enough to fit a line on."""
+ distinct = sorted(set(sizes))
+ return len(distinct) >= 2 and distinct[-1] >= MIN_AREA_RATIO * distinct[0]
+
+
+def upper_envelope(
+ points: Sequence[tuple[int, int]], capping: Optional[Sequence[tuple[int, int]]] = None
+) -> tuple[Fraction, Fraction]:
"""The line ``y = k * x + b`` on or above every ``(x, y)`` point, with ``b >= 0``, that over-reserves least.
The candidates are the edges of the upper convex hull of the points and the origin: each such line lies on or
above every point, and the origin keeps its intercept non-negative. Of those, the one whose largest ratio to the
highest reading of a size is smallest wins, the steeper one on a tie, since it is the more conservative past the
largest point. Only the highest reading counts: a lower one at a measured size is covered whatever the line, and
- rating against it would tilt the line though no point lies above it. Raises unless the points span two sizes at
- least `MIN_AREA_RATIO` apart.
+ rating against it would tilt the line though no point lies above it. With `capping`, a subset of the points, only
+ its readings rate the edges: the others are covered but cap nothing. Without any, all points rate them. Raises
+ unless the points span two sizes at least `MIN_AREA_RATIO` apart.
"""
if not points or any(x <= 0 or y <= 0 for x, y in points):
raise ValueError(f"an envelope needs points with positive sizes and bytes, got {list(points)}")
sizes = sorted({x for x, _ in points})
- if len(sizes) < 2 or sizes[-1] < MIN_AREA_RATIO * sizes[0]:
+ if not spans(sizes):
raise ValueError(
f"an envelope needs two sizes at least {MIN_AREA_RATIO}x apart in pixels, got {sizes}; measure more sizes"
)
@@ -73,27 +100,69 @@ def upper_envelope(points: Sequence[tuple[int, int]]) -> tuple[Fraction, Fractio
hull.pop()
hull.append(point)
+ rated = {x: max(y for px, y in capping if px == x) for x in sorted({x for x, _ in capping})} if capping else highest
best: tuple[Fraction, Fraction, Fraction] | None = None
for (x0, y0), (x1, y1) in zip(hull, hull[1:], strict=False):
k = Fraction(y1 - y0, x1 - x0)
b = y0 - k * x0
if k < 0:
continue
- worst = max((k * x + b) / y for x, y in highest.items())
+ worst = max((k * x + b) / y for x, y in rated.items())
if best is None or (worst, -k) < (best[0], -best[1]):
best = (worst, k, b)
assert best is not None, "the edge from the origin always rises"
return best[1], best[2]
-def shipped_pair(points: Sequence[tuple[int, int]]) -> tuple[int, int]:
+def shipped_pair(
+ points: Sequence[tuple[int, int]], capping: Optional[Sequence[tuple[int, int]]] = None
+) -> tuple[int, int]:
"""The slope and intercept to ship for these points: the envelope plus `SHIPPED_MARGIN`, the slope rounded up to
a whole byte per pixel and the intercept to a whole MiB."""
- k, b = upper_envelope(points)
+ k, b = upper_envelope(points, capping)
margin = 1 + SHIPPED_MARGIN
return math.ceil(k * margin), math.ceil(b * margin / _MIB) * _MIB
+def user_pair(points: Sequence[tuple[int, int]]) -> tuple[int, int]:
+ """The slope and intercept a user calibration's points give a line: the envelope plus `USER_MARGIN`, the slope
+ rounded up to a whole byte per pixel and the intercept to a whole MiB.
+
+ Every user point is a `probe_demand` window, so no point caps the line and all of them rate its edges (the
+ fallback of `upper_envelope`). Raises like `upper_envelope` unless the points span two sizes `MIN_AREA_RATIO`
+ apart."""
+ k, b = upper_envelope(points)
+ margin = 1 + USER_MARGIN
+ return math.ceil(k * margin), math.ceil(b * margin / _MIB) * _MIB
+
+
+def line_of(features: Mapping[str, object]) -> Optional[tuple[str, int]]:
+ """The convolution line an operation of these features is priced on, ``<operation>_<dtype>``, and its size in
+ output pixels; None for features that name no such line."""
+ operation, dtype = features.get("operation"), features.get("dtype")
+ height, width = features.get("height"), features.get("width")
+ if not isinstance(operation, str) or not isinstance(dtype, str):
+ return None
+ if not isinstance(height, int) or not isinstance(width, int):
+ return None
+ return f"{operation}_{dtype}", height * width
+
+
+def fits_a_line(features: Mapping[str, object]) -> bool:
+ """Whether a point of these features can join its line's fit: an untiled single-sample operation of an
+ AutoencoderKL whose VAE no in-place cast grew. Tiled points reuse the untiled line, the cast's growth is a term of
+ its own, and the lines are the AutoencoderKL convolutions': the SD estimator also prices the tiny autoencoder
+ (`vae_class` AutoencoderTiny) on them, a different network whose windows say nothing about those lines.
+ Estimators that name no `vae_class` price an AutoencoderKL only."""
+ return (
+ features.get("tile") is None
+ and features.get("batch_size", 1) == 1
+ and not features.get("upcast_weight_bytes", 0)
+ and features.get("vae_class", "AutoencoderKL") == "AutoencoderKL"
+ and line_of(features) is not None
+ )
+
+
def _pairs(entry: CoefficientEntry) -> set[str]:
"""The `<operation>_<dtype>` suffixes an entry carries both halves of a convolution line for."""
names = set(entry.values or {})
@@ -110,29 +179,24 @@ def hand_set_values(entry: CoefficientEntry, spec: "EstimatorSpec") -> set[str]:
return set(entry.values or {}) - lines
-def fit_points(data: Iterable[WorkingMemoryData]) -> Mapping[tuple[EntryKey, str], list[tuple[int, int]]]:
- """Per carried entry and line, the ``(pixels, bytes)`` points that line is fitted on.
+def fit_points(data: Iterable[WorkingMemoryData]) -> Mapping[tuple[EntryKey, str], list[FitPoint]]:
+ """Per carried entry and line, the points that line is fitted on.
A point belongs to the entry its own estimator's entry resolves to on its platform, one `values_from` hop, and to
the line its operation and dtype name. Lines no point measures are absent.
"""
files = list(data)
entries = [entry for file in files for entry in file.coefficients]
- groups: dict[tuple[EntryKey, str], list[tuple[int, int]]] = {}
+ groups: dict[tuple[EntryKey, str], list[FitPoint]] = {}
for point in (point for file in files for point in file.points):
- features = point.features
- if (
- not point.in_fit
- or features.get("tile") is not None
- or features.get("batch_size", 1) != 1
- or features.get("upcast_weight_bytes", 0)
- ):
+ found = line_of(point.features)
+ if not point.in_fit or found is None or not fits_a_line(point.features):
continue
owner = carrier_of(entries, point)
- suffix = f"{features.get('operation')}_{features.get('dtype')}"
+ suffix, pixels = found
if suffix in _pairs(owner):
- pixels = int(features["height"]) * int(features["width"]) # type: ignore[arg-type]
- groups.setdefault((entry_key(owner), suffix), []).append((pixels, point.measured_bytes))
+ line = groups.setdefault((entry_key(owner), suffix), [])
+ line.append(FitPoint(pixels, point.measured_bytes, point.holds_upper_bound))
return groups
@@ -147,7 +211,7 @@ def carrier_of(entries: Sequence[CoefficientEntry], point: MeasuredPoint) -> Coe
def fitted_values(data: Iterable[WorkingMemoryData]) -> Mapping[EntryKey, Mapping[str, int]]:
- """Per entry that carries values, what `shipped_pair` gives each line it does not declare a stand-in.
+ """Per entry that carries values, what `fitted_pair` gives each line it does not declare a stand-in.
Raises, naming the entry and line, where the points cannot fit that line.
"""
@@ -160,8 +224,31 @@ def fitted_values(data: Iterable[WorkingMemoryData]) -> Mapping[EntryKey, Mappin
if {f"k_{suffix}", f"b_{suffix}"} <= set(entry.stand_ins):
continue
try:
- k, b = shipped_pair(groups.get((key, suffix), []))
+ k, b = fitted_pair(groups.get((key, suffix), []))
except ValueError as e:
raise ValueError(f"{entry.estimator} on {entry.platform}, {suffix}: {e}") from e
fitted.setdefault(key, {}).update({f"k_{suffix}": k, f"b_{suffix}": b})
return fitted
+
+
+def capping_spans(line: Sequence[FitPoint]) -> bool:
+ """Whether a line's fresh-process points alone span the sizes a fit needs, as only then is it fitted. Warm
+ windows, or one fresh size with warm windows at others, could pin it below what a cold first run needs."""
+ return spans(point.pixels for point in line if point.caps)
+
+
+def fitted_pair(line: Sequence[FitPoint]) -> tuple[int, int]:
+ """The pair to ship for a line (`shipped_pair`): the coefficient-wise larger of its fit on all its points, rated on the
+ fresh-process ones, and its fit on the fresh-process points alone. A probe point above the hull can drop a fresh
+ vertex and so lower one half of the line; the larger of the two keeps both at the fresh-process fit at least.
+
+ Raises unless the fresh-process points span (`capping_spans`)."""
+ capping = [(p.pixels, p.bytes) for p in line if p.caps]
+ if not capping_spans(line):
+ raise ValueError(
+ f"its fresh-process points measure {sorted({x for x, _ in capping})} pixels, not two sizes at least "
+ f"{MIN_AREA_RATIO}x apart; keep it a stand-in until they do"
+ )
+ k_all, b_all = shipped_pair([(p.pixels, p.bytes) for p in line], capping)
+ k_fresh, b_fresh = shipped_pair(capping)
+ return max(k_all, k_fresh), max(b_all, b_fresh)
diff --git a/invokeai/backend/working_memory/fragmentation.py b/invokeai/backend/working_memory/fragmentation.py
new file mode 100644
index 0000000000..c9a4b20dc0
--- /dev/null
+++ b/invokeai/backend/working_memory/fragmentation.py
@@ -0,0 +1,106 @@
+"""When a measured window's demand is the allocator's fragmentation rather than the operation's.
+
+A long-running server's caching allocator grows its reserve around the same tensors: reserved bytes climb while the
+allocated bytes, what the operation really holds, stay put. A window taken then measures the allocator's history, and a
+line fitted on it over-reserves every later operation. One rule, `fragmented`, read by
+`scripts/working_memory/build_shipped.py`, which flags such points for review, and by the user fit
+(`app/services/working_memory_calibration/`), which leaves them out. It judges measurements: the fit-eligible windows
+of one operation at one size from one attempt (a calibration attempt, or one run without one), in the order they ran.
+Windows of one attempt at one size ran back to back on one allocator state; another attempt's ran on another, before
+or after offloads and other work, so each attempt is judged on its own and a recalibration can bring a size back.
+
+- `grew_around_flat_allocation`: across a measurement's windows, reserved grew by `FRAGMENTATION_GROWTH` from the
+ first window to the largest while allocated stayed within `ALLOCATED_FLAT`.
+- `ratio_outlier`: a measurement's largest window has a reserved-to-allocated ratio `RATIO_OUTLIER` above the median of
+ the same line's smaller measurements that are not flagged, from any attempt: the ratio is the operation's on the
+ card, which no attempt owns. This catches a size whose every window ran fragmented, so that it shows no growth of its
+ own; a single window, too. Measured on an RX 9060 XT (fp32 SDXL decode): 1216px measured 1.47 against 1.10 at 576px
+ and 832px, its one fit-eligible window 1.33 times their median, while the fp16 sizes of the same run stayed within
+ 1.06 of theirs.
+"""
+
+from collections.abc import Hashable, Sequence
+from dataclasses import dataclass
+from statistics import median
+from typing import Final, Optional
+
+FRAGMENTATION_GROWTH: Final = 1.10
+"""Reserved growth from a measurement's first window to its largest that, with flat allocated bytes, flags
+fragmentation."""
+
+ALLOCATED_FLAT: Final = 0.02
+"""How far allocated bytes may spread across a measurement's windows and still count as flat."""
+
+RATIO_OUTLIER: Final = 1.2
+"""How far a size's reserved-to-allocated ratio may exceed the median of the same line's smaller sizes before it
+counts as fragmentation."""
+
+
+@dataclass(frozen=True)
+class Measurement:
+ """The fit-eligible windows of one operation at one size from one attempt, in the order they ran."""
+
+ line: Hashable
+ """What its sizes are compared within: one line (operation and dtype) of one estimator version on one card and
+ platform or environment."""
+ pixels: int
+ demand: Sequence[int]
+ reserved: Sequence[Optional[int]]
+ """Each window's reserved delta."""
+ allocated: Sequence[Optional[int]]
+ reference: bool = True
+ """Whether larger sizes may be compared with it; a measurement still being taken is judged, but sets no standard."""
+
+
+def fragmented(measurements: Sequence[Measurement]) -> list[bool]:
+ """Per measurement, whether its windows measured fragmentation: `grew_around_flat_allocation`, or a
+ `ratio_outlier` of its largest window against the smaller measurements of its line that are not flagged and may
+ be a `reference`."""
+ flags = [
+ grew_around_flat_allocation(measurement.demand, measurement.reserved, measurement.allocated)
+ for measurement in measurements
+ ]
+ lines: dict[Hashable, list[int]] = {}
+ for index, measurement in enumerate(measurements):
+ if not flags[index]:
+ lines.setdefault(measurement.line, []).append(index)
+ for members in lines.values():
+ kept: list[tuple[int, float]] = []
+ for index in sorted(members, key=lambda index: measurements[index].pixels):
+ measurement = measurements[index]
+ largest = list(measurement.demand).index(max(measurement.demand))
+ ratio = reserved_ratio(measurement.reserved[largest], measurement.allocated[largest])
+ if ratio_outlier(ratio, [kept_ratio for pixels, kept_ratio in kept if pixels < measurement.pixels]):
+ flags[index] = True
+ elif ratio is not None and measurement.reference:
+ kept.append((measurement.pixels, ratio))
+ return flags
+
+
+def grew_around_flat_allocation(
+ demand: Sequence[int], reserved: Sequence[Optional[int]], allocated: Sequence[Optional[int]]
+) -> bool:
+ """Whether the windows of one measurement, in the order they ran, show reserved growing by `FRAGMENTATION_GROWTH`
+ from the first window to the one of the largest demand while allocated stayed flat. False when that largest
+ window is the first, or a counter is missing."""
+ largest = list(demand).index(max(demand))
+ first, peak = reserved[0], reserved[largest]
+ if largest == 0 or first is None or peak is None or None in allocated:
+ return False
+ flat = [value for value in allocated if value is not None]
+ return peak >= FRAGMENTATION_GROWTH * first and max(flat) <= (1 + ALLOCATED_FLAT) * min(flat)
+
+
+def reserved_ratio(reserved: Optional[int], allocated: Optional[int]) -> Optional[float]:
+ """Reserved over allocated bytes of one window; None where either is missing or allocated is not positive."""
+ if reserved is None or allocated is None or allocated <= 0:
+ return None
+ return reserved / allocated
+
+
+def ratio_outlier(ratio: Optional[float], smaller: Sequence[float]) -> bool:
+ """Whether a size's `ratio` is `RATIO_OUTLIER` times the median ratio of the same line's `smaller` sizes; False
+ without a ratio or a smaller size to compare with."""
+ if ratio is None or not smaller:
+ return False
+ return ratio >= RATIO_OUTLIER * median(smaller)
diff --git a/invokeai/backend/working_memory/platform.py b/invokeai/backend/working_memory/platform.py
index 8ceafbd962..6cab1793e0 100644
--- a/invokeai/backend/working_memory/platform.py
+++ b/invokeai/backend/working_memory/platform.py
@@ -1,10 +1,13 @@
+import os
import sys
+from collections.abc import Mapping
from dataclasses import astuple, dataclass, replace
-from typing import Final, Literal
+from typing import Final, Literal, Optional, cast, get_args
import torch
-from invokeai.app.util.torch_cuda_allocator import expandable_segments_enabled
+from invokeai.app.util.torch_cuda_allocator import ALLOCATOR_CONF_ENV_VARS, expandable_segments_enabled
+from invokeai.backend.working_memory.counters import Backend, backend_for
ConvBackend = Literal["cudnn", "miopen", "mps", "xpu", "cpu"]
Allocator = Literal["native", "cudaMallocAsync", "expandable"]
@@ -66,39 +69,66 @@ def priced_as(platform: Platform) -> Platform:
return replace(platform, allocator="native")
+_CONV_BACKENDS: Final[Mapping[Optional[Backend], ConvBackend]] = {
+ "cuda": "cudnn",
+ "hip": "miopen",
+ "mps": "mps",
+ "xpu": "xpu",
+ None: "cpu",
+}
+"""The convolution backend of each GPU backend. A HIP build reports its GPUs as ``cuda`` devices, so the torch build --
+not the device string -- separates MIOpen from cuDNN, and a `cpu_only` model on a ROCm build is not on MIOpen. Any
+device type other than CUDA, MPS and XPU runs torch's CPU kernels, or none at all, and is priced as the CPU."""
+
+
+def _allocator(backend: Optional[Backend], allocator_backend: Optional[str], environ: Mapping[str, str]) -> Allocator:
+ """The caching allocator of a `backend` device under torch's allocator backend and these allocator variables:
+ `native` for anything but a CUDA/HIP GPU. The driver's pool ignores expandable segments, so torch's backend
+ decides first; expandable segments are a mode of the native allocator."""
+ if backend not in ("cuda", "hip"):
+ return "native"
+ if allocator_backend == "cudaMallocAsync":
+ return "cudaMallocAsync"
+ return "expandable" if expandable_segments_enabled(environ) else "native"
+
+
def _allocator_for(device: torch.device) -> Allocator:
- """The caching allocator an operation on `device` allocates through: `native` for anything but a CUDA/HIP GPU.
+ """The caching allocator an operation on `device` allocates through.
- The backend is fixed before torch initializes CUDA, so torch's answer holds for the process; it is asked first,
- because the driver's pool ignores expandable segments. Expandable segments are a mode of the native allocator, read
+ The backend is fixed before torch initializes CUDA, so torch's answer holds for the process. The variables are read
from the environment the model cache reads them from. A ``cuda`` device on a build without one (a test pinning the
device) has no backend to ask.
"""
- if device.type != "cuda":
- return "native"
- if torch.cuda.is_available() and torch.cuda.get_allocator_backend() == "cudaMallocAsync":
- return "cudaMallocAsync"
- return "expandable" if expandable_segments_enabled() else "native"
+ backend = backend_for(device)
+ allocator_backend = (
+ torch.cuda.get_allocator_backend() if backend in ("cuda", "hip") and torch.cuda.is_available() else None
+ )
+ return _allocator(backend, allocator_backend, os.environ)
def _host_os() -> OperatingSystem:
+ """The operating system this process runs on, as platforms name it."""
if sys.platform == "win32":
return "windows"
return "linux" if sys.platform.startswith("linux") else "other"
def platform_for(device: torch.device) -> Platform:
- """The platform an operation on `device` runs on.
+ """The platform an operation on `device` runs on."""
+ return Platform(_CONV_BACKENDS[backend_for(device)], _allocator_for(device), _host_os())
+
- A HIP build reports ``device.type == "cuda"``, so the torch build -- not the device string -- is what separates
- MIOpen from cuDNN, and a `cpu_only` model on a ROCm build is not on MIOpen. Any device type other than CUDA, MPS and
- XPU runs torch's CPU kernels, or none at all, and is priced as the CPU.
+def platform_for_environment(backend: Backend, hard: Mapping[str, str]) -> Platform:
+ """The platform `platform_for` gives a `backend` device in the environment whose hard facts are `hard`
+ (`fingerprint.environment_for`), as a calibration store records them: torch's allocator backend, the allocator
+ variables and the OS. Raises ValueError when they lack a fact the platform needs.
"""
- allocator, os = _allocator_for(device), _host_os()
- if device.type == "cuda":
- return Platform("miopen" if torch.version.hip is not None else "cudnn", allocator, os)
- if device.type == "mps":
- return Platform("mps", allocator, os)
- if device.type == "xpu":
- return Platform("xpu", allocator, os)
- return Platform("cpu", allocator, os)
+ os_name = hard.get("os")
+ if os_name not in get_args(OperatingSystem):
+ raise ValueError(f"The environment records no operating system the platform knows: os={os_name!r}.")
+ allocator_backend = hard.get("allocator_backend")
+ if backend in ("cuda", "hip") and allocator_backend is None:
+ raise ValueError(f"The environment of a {backend} device records no allocator_backend.")
+ environ = {var: hard.get(f"env.{var}", "") for var in ALLOCATOR_CONF_ENV_VARS}
+ allocator = _allocator(backend, allocator_backend, environ)
+ return Platform(_CONV_BACKENDS[backend], allocator, cast(OperatingSystem, os_name))
diff --git a/invokeai/backend/working_memory/spec.py b/invokeai/backend/working_memory/spec.py
index 7dd4513032..715332c09a 100644
--- a/invokeai/backend/working_memory/spec.py
+++ b/invokeai/backend/working_memory/spec.py
@@ -6,6 +6,7 @@ from typing import Final
import torch
+from invokeai.backend.working_memory import user_fit
from invokeai.backend.working_memory.coefficients import ResolvedCoefficients, shipped_coefficients
from invokeai.backend.working_memory.estimate import FeatureValue, WorkingMemoryEstimate, WorkingMemoryTerm
from invokeai.backend.working_memory.platform import platform_for
@@ -37,8 +38,14 @@ class EstimatorSpec:
terms: TermsFunction = field(compare=False, repr=False)
def estimate(self, features: Mapping[str, FeatureValue], device: torch.device) -> WorkingMemoryEstimate:
- """The estimate for an operation on `device`, priced with the shipped coefficients of the platform it runs on."""
- return self.evaluate(features, shipped_coefficients(self, platform_for(device)))
+ """The estimate for an operation on `device`, priced with the shipped coefficients of the platform it runs on,
+ and with the user's own line where a calibration of this device measured it (`user_fit.resolve`)."""
+ platform = platform_for(device)
+ shipped = shipped_coefficients(self, platform)
+ fit = user_fit.user_fit_for(self, platform, device)
+ if fit is None:
+ return self.evaluate(features, shipped)
+ return user_fit.resolve(self, features, shipped, fit)
def evaluate(
self, features: Mapping[str, FeatureValue], coefficients: ResolvedCoefficients
diff --git a/invokeai/backend/working_memory/user_fit.py b/invokeai/backend/working_memory/user_fit.py
new file mode 100644
index 0000000000..83e2107a53
--- /dev/null
+++ b/invokeai/backend/working_memory/user_fit.py
@@ -0,0 +1,213 @@
+"""A user's own calibration, fitted per line and read by estimates in place of the shipped values where it measured.
+
+The app keeps a device class's calibration windows (`app/services/working_memory_calibration/`); this module owns the
+rule that turns them into lines and the rule by which an estimate uses them. Lines are those of `fit.py`: a window
+joins the line its estimator resolves to on the platform it ran on -- the lender's, where the estimator borrows its
+values -- so a calibration of one model's decode moves every estimator that prices with the same line.
+
+An estimate reads a user line through the provider seam: the app registers one (`set_user_fit_provider`) that answers
+from memory, and `EstimatorSpec.estimate` asks it per estimate. Without a provider, or when it has no fit for the
+device, the estimate is the shipped one, bit for bit. With one, `resolve` applies the user line where it was measured:
+
+- at or below the largest size the line measured (`UserLine.x_max`), the user line replaces the shipped one;
+- above it, the larger of the user and the shipped estimate, since nothing measured says how the line continues.
+"""
+
+import functools
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import asdict, dataclass, field, replace
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Final, Optional
+
+import torch
+
+from invokeai.backend.util.logging import InvokeAILogger
+from invokeai.backend.working_memory.coefficients import ResolvedCoefficients, find_entry, shipped_data
+from invokeai.backend.working_memory.estimate import FeatureValue, WorkingMemoryEstimate
+from invokeai.backend.working_memory.fit import EntryKey, entry_key, fits_a_line, line_of, user_pair
+from invokeai.backend.working_memory.platform import Platform, priced_as
+
+if TYPE_CHECKING:
+ from invokeai.backend.working_memory.spec import EstimatorSpec
+
+LineKey = tuple[EntryKey, str]
+"""A line: the entry that carries its values, and its ``<operation>_<dtype>`` suffix."""
+
+
+@dataclass(frozen=True)
+class UserPoint:
+ """One calibration window as a fit reads it."""
+
+ estimator: str
+ version: int
+ features: Mapping[str, FeatureValue]
+ demand_bytes: int
+
+
+@dataclass(frozen=True)
+class UserLine:
+ """A line fitted on a user's windows (`fit.user_pair`), and the sizes it was fitted on."""
+
+ k: int
+ """Bytes per output pixel."""
+ b: int
+ """Bytes whatever the size."""
+ x_min: int
+ """The smallest size measured, in output pixels."""
+ x_max: int
+ """The largest size measured, in output pixels."""
+ points: int
+
+
+@dataclass(frozen=True)
+class UserFit:
+ """A device class's user lines in one environment, on the platform they were measured on."""
+
+ label: str
+ """Names the fit in an estimate's `source`, e.g. ``user:<device class id>:<environment id>``."""
+ platform: Platform
+ lines: Mapping[LineKey, UserLine]
+ _by_spec: dict[tuple[str, int], Mapping[str, UserLine]] = field(
+ default_factory=dict, init=False, repr=False, compare=False
+ )
+
+ def lines_for(self, spec: "EstimatorSpec") -> Mapping[str, UserLine]:
+ """The user lines `spec` prices with on this fit's platform, by suffix. Resolved once per spec."""
+ key = (spec.id, spec.version)
+ found = self._by_spec.get(key)
+ if found is None:
+ carrier = carrier_key(spec.id, spec.version, self.platform)
+ found = MappingProxyType({suffix: line for (entry, suffix), line in self.lines.items() if entry == carrier})
+ self._by_spec[key] = found
+ return found
+
+
+def carrier_key(estimator: str, version: int, platform: Platform) -> Optional[EntryKey]:
+ """The shipped entry whose values `estimator` `version` prices with on `platform`: its own, or the one it borrows
+ from. None where the shipped data has no entry for it."""
+ full = {key: str(value) for key, value in asdict(priced_as(platform)).items()}
+ entries = [entry for file in shipped_data().values() for entry in file.coefficients]
+ where = f"{estimator} on {full}"
+ try:
+ entry = find_entry(entries, estimator, version, full, where)
+ if entry.values_from is not None:
+ entry = find_entry(entries, entry.values_from.estimator, entry.values_from.version, full, where)
+ except LookupError:
+ return None
+ return entry_key(entry)
+
+
+def _carried_lines(key: EntryKey) -> frozenset[str]:
+ entries = [entry for file in shipped_data().values() for entry in file.coefficients]
+ for entry in entries:
+ if entry_key(entry) == key and entry.values is not None:
+ names = set(entry.values)
+ return frozenset(name[2:] for name in names if name.startswith("k_") and f"b_{name[2:]}" in names)
+ return frozenset()
+
+
+def fit_user_lines(
+ points: Iterable[UserPoint], platform: Platform
+) -> tuple[Mapping[LineKey, UserLine], Mapping[LineKey, str]]:
+ """The user lines `points`, measured on `platform`, fit; and, per line they measure but cannot fit, why.
+
+ A point joins a line where `fit.fits_a_line` admits its features, its estimator version has shipped values on
+ the platform, the entry carrying them has the line, and it demanded more than nothing. Each line is
+ `fit.user_pair` of its points: two sizes at least `fit.MIN_AREA_RATIO` apart, or no line.
+ """
+ groups: dict[LineKey, list[tuple[int, int]]] = {}
+ for point in points:
+ found = line_of(point.features)
+ if found is None or point.demand_bytes <= 0 or not fits_a_line(point.features):
+ continue
+ carrier = carrier_key(point.estimator, point.version, platform)
+ suffix, pixels = found
+ if carrier is None or suffix not in _carried_lines(carrier):
+ continue
+ groups.setdefault((carrier, suffix), []).append((pixels, point.demand_bytes))
+
+ lines: dict[LineKey, UserLine] = {}
+ problems: dict[LineKey, str] = {}
+ for key, measured in groups.items():
+ try:
+ k, b = user_pair(measured)
+ except ValueError as e:
+ problems[key] = str(e)
+ continue
+ sizes = [pixels for pixels, _ in measured]
+ lines[key] = UserLine(k=k, b=b, x_min=min(sizes), x_max=max(sizes), points=len(measured))
+ return MappingProxyType(lines), MappingProxyType(problems)
+
+
+def resolve(
+ spec: "EstimatorSpec",
+ features: Mapping[str, FeatureValue],
+ shipped: ResolvedCoefficients,
+ fit: UserFit,
+) -> WorkingMemoryEstimate:
+ """The estimate for `features` with `fit`'s line in place of the shipped one, where `fit` has the line.
+
+ The line and its size are read as `fit.py` reads a point's (`line_of`): the output's pixels, also for a tiled
+ operation, whose image is at least its tile, so a tiled operation past the measured sizes takes the larger
+ estimate. At or below `UserLine.x_max` the user line decides; above, the larger estimate wins, the shipped one on
+ a tie. `source` names the user fit and the line wherever the user line decides.
+ """
+ found = line_of(features)
+ line = fit.lines_for(spec).get(found[0]) if found is not None else None
+ if found is None or line is None:
+ return spec.evaluate(features, shipped)
+ suffix, pixels = found
+ values = MappingProxyType({**shipped.values, f"k_{suffix}": line.k, f"b_{suffix}": line.b})
+ within = pixels <= line.x_max
+ where = "within its measured sizes" if within else "above its measured sizes, over shipped"
+ user = spec.evaluate(
+ features, ResolvedCoefficients(values=values, source=f"{fit.label} ({suffix} {where}) + {shipped.source}")
+ )
+ if within:
+ return user
+ shipped_estimate = spec.evaluate(features, shipped)
+ if user.reservation_bytes > shipped_estimate.reservation_bytes:
+ return user
+ return replace(shipped_estimate, source=f"{shipped.source} (over {fit.label} {suffix}, above its measured sizes)")
+
+
+UserFitProvider = Callable[["EstimatorSpec", Platform, torch.device], Optional[UserFit]]
+"""Answers, from memory, the user fit an estimate of `spec` on `device` reads, or None. Called per estimate, so it
+reads no file and touches no device."""
+
+_provider: Optional[UserFitProvider] = None
+_logged_failure: bool = False
+
+_LOGGER: Final = InvokeAILogger.get_logger(__name__)
+
+
+def set_user_fit_provider(provider: UserFitProvider) -> None:
+ """Make `provider` the one estimates ask. The app's calibration service registers it when it starts."""
+ global _provider
+ _provider = provider
+
+
+def clear_user_fit_provider(provider: UserFitProvider) -> None:
+ """Stop asking `provider`, if it is the registered one: a service that stops must not unregister its successor."""
+ global _provider
+ if _provider is provider:
+ _provider = None
+
+
+def user_fit_for(spec: "EstimatorSpec", platform: Platform, device: torch.device) -> Optional[UserFit]:
+ """The registered provider's answer, None without one. A provider that raises leaves the estimate shipped: an
+ estimate must not fail over a calibration."""
+ global _logged_failure
+ provider = _provider
+ if provider is None:
+ return None
+ try:
+ return provider(spec, platform, device)
+ except Exception:
+ if not _logged_failure:
+ _logged_failure = True
+ _LOGGER.warning(
+ "The working-memory user fit could not be read; estimates use the shipped values.", exc_info=True
+ )
+ return None
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index f4128cd361..5cde707873 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -5757,7 +5757,7 @@
"post": {
"tags": ["model_manager"],
"summary": "Calibrate Model Working Memory",
- "description": "Start a working-memory calibration run: enqueue the batch with every node uncached and measure each node's\nmodel operations on the generation device. Needs exactly one generation device, and it must be a GPU. The queue\ntakes all of the batch's items or none.\n\nOnce the items are queued, a request without an `idempotency_key` succeeds even when the store fails for a passing\nreason (an unwritable root, a lock timeout) to record them: they run all the same, and the status finds them by\ntheir origin. With a key, that failure is a 503 although the items are queued. A run removed meanwhile (404) or an\nunusable store file (409) fails the request with or without a key; its queued items then fail when they start.\n\nWith a key, repeating the request (also after a lost response) records the queued items and returns the run; it\nenqueues nothing new. The items come from the queue's enqueue receipt for the key while it exists, otherwise from\nthe queue items that carry the run's origin and those the runner saw. Once a reset removed the run, a repeat is\nrefused (404). Acknowledge the key through the queue's enqueue_batch/acknowledge route once the response\narrived.",
+ "description": "Start a working-memory calibration run: enqueue the batch with every node uncached, its images intermediates\non no board (never in the gallery; clearing intermediates removes them), and measure each node's model operations\non the generation device. Needs exactly one generation device, and it must be a GPU. The queue\ntakes all of the batch's items or none.\n\nOnce the items are queued, a request without an `idempotency_key` succeeds even when the store fails for a passing\nreason (an unwritable root, a lock timeout) to record them: they run all the same, and the status finds them by\ntheir origin. With a key, that failure is a 503 although the items are queued. A run removed meanwhile (404) or an\nunusable store file (409) fails the request with or without a key; its queued items then fail when they start.\n\nWith a key, repeating the request (also after a lost response) records the queued items and returns the run; it\nenqueues nothing new. The items come from the queue's enqueue receipt for the key while it exists, otherwise from\nthe queue items that carry the run's origin and those the runner saw. Once a reset removed the run, a repeat is\nrefused (404). Acknowledge the key through the queue's enqueue_batch/acknowledge route once the response\narrived.",
"operationId": "calibrate_model_working_memory",
"security": [
{
@@ -5803,10 +5803,10 @@
"description": "The model could not be found; the run was removed while it was being created, whose items are queued then and fail when they start; or a reset removed the run the idempotency key started"
},
"409": {
- "description": "This machine cannot calibrate now (no GPU, or several generation devices), the device class's store file is unusable and kept as it is (possibly after the items were queued, which then fail when they start), the queue has no room for all of the run's items (it then takes none), or the idempotency key was used for another request"
+ "description": "This machine cannot calibrate now (no GPU, or several generation devices), the device class's store file is unusable and kept as it is (possibly after the items were queued, which then fail when they start), the queue has no room for all of the run's items (it then takes none), the idempotency key was used for another request, or attempt_steps differs from that of the attempt's runs already stored (or of the run a repeated request names). Three of them carry a code, as `{\"code\": ..., \"message\": ...}` in `detail`: `calibration_running`, another calibration attempt still runs on this GPU, or another owner's attempt is between its steps and was active in the last two minutes (an owner's new attempt replaces its own attempt that stopped between steps); `calibration_interleaved`, a later step of an attempt after another calibration ran on this GPU since the attempt began; `model_changed`, a model the graph names changed or was removed since the graph was compiled (its record differs from the graph's identifier or its graph_models entry), or since an earlier step of the attempt"
},
"422": {
- "description": "The graph cannot be measured as a calibration run"
+ "description": "The graph cannot be measured as a calibration run, graph_models does not state exactly the graph's models, or attempt_id and attempt_steps were not sent together"
},
"429": {
"description": "Too many unacknowledged idempotency keys; acknowledge or wait, then retry"
@@ -5845,11 +5845,138 @@
]
}
},
+ "/api/v2/models/i/{key}/working_memory/plan": {
+ "get": {
+ "tags": ["model_manager"],
+ "summary": "Get Model Working Memory Calibration Plan",
+ "description": "The text-to-image cases that calibrate the model's decode on this machine's GPU, how often each runs, which\nother installed models the calibration also moves, or why the model cannot be calibrated here (`supported`).",
+ "operationId": "get_model_working_memory_calibration_plan",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "key",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "Key of the model to calibrate",
+ "title": "Key"
+ },
+ "description": "Key of the model to calibrate"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationPlan"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "The model could not be found"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/v2/models/i/{key}/working_memory/summary": {
+ "get": {
+ "tags": ["model_manager"],
+ "summary": "Get Model Working Memory Calibration Summary",
+ "description": "What the calibration windows of the model's lines measured on one device class, per estimator line and\nenvironment: the sizes, the largest demand, the shipped and the user estimate, whether the user line is in use,\nstale or unusable, and which models measured it, also for a line the model's decode shares with other models'\nmeasurements; and the model's runs.",
+ "operationId": "get_model_working_memory_calibration_summary",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "key",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "Key of the model whose measurements to summarise",
+ "title": "Key"
+ },
+ "description": "Key of the model whose measurements to summarise"
+ },
+ {
+ "name": "device_class_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string",
+ "pattern": "^[0-9a-f]{16}$"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The device class to act on; the current generation device's by default",
+ "title": "Device Class Id"
+ },
+ "description": "The device class to act on; the current generation device's by default"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationModelSummary"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "The model could not be found"
+ },
+ "409": {
+ "description": "No device_class_id was given and there is no current one"
+ },
+ "503": {
+ "description": "The calibration store cannot be read or written (unwritable root, lock timeout)"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/v2/models/working_memory/runs/{run_id}": {
"delete": {
"tags": ["model_manager"],
"summary": "Delete Working Memory Calibration Run",
- "description": "Remove a calibration run and its measurements. Its queue items that have not run yet fail when they start.",
+ "description": "Remove a calibration run and its measurements. Its queue items that have not run yet fail when they start.\n\nA removed run of an attempt still counts toward the attempt's runs (`attempt_steps`), so the rest of a finished\nattempt is judged as before. Removing a run while its attempt runs, or after it was stopped (a canceled item),\nstops the attempt for good: none of its measurements count.",
"operationId": "delete_working_memory_calibration_run",
"security": [
{
@@ -5906,7 +6033,7 @@
"delete": {
"tags": ["model_manager"],
"summary": "Reset Model Working Memory Calibration",
- "description": "Remove a model's calibration runs with all their measurements, and every measurement of the model taken in\nother runs (a VAE measured inside a transformer's run, say), from one device class.",
+ "description": "Remove a model's calibration runs with all their measurements, and every measurement of the model taken in\nother runs (a VAE measured inside a transformer's run, say), from one device class. Removed runs of an attempt\nstill count toward its runs; an attempt that was running is stopped for good, its later steps included.",
"operationId": "reset_model_working_memory_calibration",
"security": [
{
@@ -5979,7 +6106,7 @@
"delete": {
"tags": ["model_manager"],
"summary": "Reset Working Memory Calibration",
- "description": "Remove every calibration run and measurement of one device class.",
+ "description": "Remove every calibration run and measurement of one device class. An attempt that was running is stopped\nfor good: its later steps never count either.",
"operationId": "reset_working_memory_calibration",
"security": [
{
@@ -13809,7 +13936,7 @@
"put": {
"tags": ["queue"],
"summary": "Retry Items By Id",
- "description": "Retries the given queue items. Users can only retry their own items unless they are an admin.",
+ "description": "Retries the given queue items. Users can only retry their own items unless they are an admin.\n\nA calibration item's retry is recorded in the calibration store as it commits. When that store cannot be written,\nthe request retries nothing, also its items that are no calibration's (503); retry again once it can.",
"operationId": "retry_items_by_id",
"security": [
{
@@ -13855,6 +13982,9 @@
}
}
},
+ "503": {
+ "description": "The items include a working-memory calibration's, and its store cannot be written now (unwritable root, lock timeout): no item is retried, the request's other items included"
+ },
"422": {
"description": "Validation Error",
"content": {
@@ -25342,6 +25472,52 @@
"title": "CalculateImageTilesOutput",
"type": "object"
},
+ "CalibrationCompiledModel": {
+ "properties": {
+ "base": {
+ "type": "string",
+ "title": "Base"
+ },
+ "type": {
+ "type": "string",
+ "title": "Type"
+ },
+ "format": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Format",
+ "description": "The model's format; null for a record without one"
+ },
+ "variant": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Variant",
+ "description": "The model's variant; null for a record without one"
+ },
+ "hash": {
+ "type": "string",
+ "title": "Hash",
+ "description": "The model's hash, as the graph's identifier names it"
+ }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "required": ["base", "type", "format", "variant", "hash"],
+ "title": "CalibrationCompiledModel",
+ "description": "A model a calibration request's graph names, as the record the client compiled the graph against has it. Every\nfact is required: format and variant are null for a record without one, the rest is never null."
+ },
"CalibrationDeviceClass": {
"properties": {
"id": {
@@ -120083,6 +120259,94 @@
],
"title": "WorkflowWithoutID"
},
+ "WorkingMemoryCalibrationCase": {
+ "properties": {
+ "id": {
+ "type": "string",
+ "title": "Id",
+ "description": "Unique within the plan; becomes the graph id"
+ },
+ "mode": {
+ "type": "string",
+ "const": "txt2img",
+ "title": "Mode",
+ "default": "txt2img"
+ },
+ "model_key": {
+ "type": "string",
+ "title": "Model Key",
+ "description": "The main model the case generates with"
+ },
+ "components": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "type": "object",
+ "title": "Components",
+ "description": "Component picks by Generate slot key; `vae` when a standalone VAE is calibrated or a GPU VAE must be picked over one that runs on the CPU"
+ },
+ "width": {
+ "type": "integer",
+ "title": "Width"
+ },
+ "height": {
+ "type": "integer",
+ "title": "Height"
+ },
+ "steps": {
+ "type": "integer",
+ "title": "Steps",
+ "description": "The fewest steps that still run the whole pipeline"
+ },
+ "seed": {
+ "type": "integer",
+ "title": "Seed"
+ },
+ "positive_prompt": {
+ "type": "string",
+ "title": "Positive Prompt"
+ },
+ "negative_prompt": {
+ "type": "string",
+ "title": "Negative Prompt"
+ },
+ "settings": {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "type": "object",
+ "title": "Settings",
+ "description": "Generate settings overrides: `vaePrecision` (fp16 or fp32) where the decode node casts the VAE"
+ },
+ "estimator": {
+ "type": "string",
+ "title": "Estimator",
+ "description": "The working-memory estimator of the operation the case measures"
+ },
+ "line": {
+ "type": "string",
+ "title": "Line",
+ "description": "The estimator line the case measures, `<operation>_<dtype>`"
+ }
+ },
+ "type": "object",
+ "required": [
+ "id",
+ "model_key",
+ "components",
+ "width",
+ "height",
+ "steps",
+ "seed",
+ "positive_prompt",
+ "negative_prompt",
+ "settings",
+ "estimator",
+ "line"
+ ],
+ "title": "WorkingMemoryCalibrationCase",
+ "description": "One generation a calibration plan runs, in the fields of the client's graph-export case (mode txt2img)."
+ },
"WorkingMemoryCalibrationDeviceClass": {
"properties": {
"device_class_id": {
@@ -120120,6 +120384,30 @@
"type": "boolean",
"title": "Is Current"
},
+ "measurement_method": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Measurement Method",
+ "description": "Where a window on a GPU of this class here reads its driver figure (`counters.Method`): torch-only when this platform has no driver reader; null when no generation device of this class is present"
+ },
+ "measurement_verified": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Measurement Verified",
+ "description": "Whether that method was checked against real hardware on this backend (`counters.VERIFIED_METHODS`); null when no generation device of this class is present"
+ },
"runs": {
"items": {
"$ref": "#/components/schemas/WorkingMemoryCalibrationRunSummary"
@@ -120149,12 +120437,29 @@
"usable",
"problem",
"is_current",
+ "measurement_method",
+ "measurement_verified",
"runs",
"point_counts",
"envs"
],
"title": "WorkingMemoryCalibrationDeviceClass"
},
+ "WorkingMemoryCalibrationDeviceClassRef": {
+ "properties": {
+ "id": {
+ "type": "string",
+ "title": "Id"
+ },
+ "name": {
+ "type": "string",
+ "title": "Name"
+ }
+ },
+ "type": "object",
+ "required": ["id", "name"],
+ "title": "WorkingMemoryCalibrationDeviceClassRef"
+ },
"WorkingMemoryCalibrationEnvironment": {
"properties": {
"id": {
@@ -120204,7 +120509,7 @@
}
],
"title": "Soft Matches Current",
- "description": "Whether the current environment has the same soft facts; null off the current device class"
+ "description": "Whether the current environment has the soft facts first recorded with this environment (`soft`); a later run's own soft facts are not compared here. Null off the current device class"
},
"point_count": {
"type": "integer",
@@ -120215,6 +120520,565 @@
"required": ["id", "hard", "soft", "hard_matches_current", "soft_matches_current", "point_count"],
"title": "WorkingMemoryCalibrationEnvironment"
},
+ "WorkingMemoryCalibrationLineContributor": {
+ "properties": {
+ "model_key": {
+ "type": "string",
+ "title": "Model Key"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Name",
+ "description": "The model's name; null when it is no longer installed"
+ },
+ "windows": {
+ "type": "integer",
+ "title": "Windows",
+ "description": "Its counted windows on the line: valid, fit-eligible and not fragmented"
+ }
+ },
+ "type": "object",
+ "required": ["model_key", "name", "windows"],
+ "title": "WorkingMemoryCalibrationLineContributor",
+ "description": "A model whose windows feed a line: the model a run calibrated, or the model a window measured."
+ },
+ "WorkingMemoryCalibrationLineSize": {
+ "properties": {
+ "width": {
+ "type": "integer",
+ "title": "Width"
+ },
+ "height": {
+ "type": "integer",
+ "title": "Height"
+ },
+ "pixels": {
+ "type": "integer",
+ "title": "Pixels"
+ },
+ "windows": {
+ "type": "integer",
+ "title": "Windows",
+ "description": "Counted: the windows at this size that feed the line, valid, fit-eligible and not fragmented, of every model in the environment; those of a calibration run still running are counted, and join the fit once it finished. Not counted: the valid windows measured at this size"
+ },
+ "measured_bytes": {
+ "type": "integer",
+ "title": "Measured Bytes",
+ "description": "The largest demand of those windows"
+ },
+ "counted": {
+ "type": "boolean",
+ "title": "Counted",
+ "description": "Whether windows of this size feed the user line"
+ },
+ "excluded_reason": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": ["fragmented", "partial_residency", "aborted_attempt"]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Excluded Reason",
+ "description": "Why a size is not counted: fragmented, its windows measured the allocator's fragmentation (`backend/working_memory/fragmentation.py`); partial_residency, the model was not fully on the device; aborted_attempt, its windows come from aborted attempts (Stop, a queue clear, a failed submission, a model changed after the calibration was planned), which never feed a line. Null for a counted size"
+ },
+ "shipped_bytes": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Shipped Bytes",
+ "description": "The shipped estimate at this size, priced with the line's estimator where one of its windows measured the size, otherwise with that of the largest window; null when the platform of the environment is unknown"
+ },
+ "user_bytes": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "User Bytes",
+ "description": "The estimate with the user line applied, as estimates read it (without the windows of runs still running); null without a user line"
+ }
+ },
+ "type": "object",
+ "required": [
+ "width",
+ "height",
+ "pixels",
+ "windows",
+ "measured_bytes",
+ "counted",
+ "excluded_reason",
+ "shipped_bytes",
+ "user_bytes"
+ ],
+ "title": "WorkingMemoryCalibrationLineSize"
+ },
+ "WorkingMemoryCalibrationModelLine": {
+ "properties": {
+ "estimator": {
+ "type": "string",
+ "title": "Estimator"
+ },
+ "version": {
+ "type": "integer",
+ "title": "Version"
+ },
+ "line": {
+ "type": "string",
+ "title": "Line",
+ "description": "`<operation>_<dtype>`"
+ },
+ "carrier": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Carrier",
+ "description": "The estimator whose shipped entry carries the line on this platform"
+ },
+ "env_id": {
+ "type": "string",
+ "title": "Env Id"
+ },
+ "state": {
+ "type": "string",
+ "enum": ["in_use", "stale", "unusable", "insufficient"],
+ "title": "State",
+ "description": "in_use: the user line applies; stale: it applies, but the soft facts of the newest finished run that contributed a window differ from the current ones; unusable: hard facts differ from the current environment (or no GPU of this class generates here), so shipped values apply; insufficient: the windows of finished, complete attempts cannot fit a line (yet); `problem` says why"
+ },
+ "changed_facts": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Changed Facts",
+ "description": "The soft facts that changed (stale) or the hard facts that differ (unusable)"
+ },
+ "problem": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Problem",
+ "description": "Why no line could be fitted, when it could not"
+ },
+ "measured_range": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationPixelRange"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The sizes the user line was fitted on, over every model's windows of the line from finished runs"
+ },
+ "slope_bytes_per_pixel": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Slope Bytes Per Pixel"
+ },
+ "base_bytes": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Base Bytes"
+ },
+ "sizes": {
+ "items": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationLineSize"
+ },
+ "type": "array",
+ "title": "Sizes"
+ },
+ "own_windows": {
+ "type": "integer",
+ "title": "Own Windows",
+ "description": "The model's own windows that feed the line; 0 when only other models' do"
+ },
+ "measured_by": {
+ "items": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationLineContributor"
+ },
+ "type": "array",
+ "title": "Measured By",
+ "description": "Every model whose windows feed the line, this one included when it has any; by name, then key"
+ }
+ },
+ "type": "object",
+ "required": [
+ "estimator",
+ "version",
+ "line",
+ "carrier",
+ "env_id",
+ "state",
+ "changed_facts",
+ "problem",
+ "measured_range",
+ "slope_bytes_per_pixel",
+ "base_bytes",
+ "sizes",
+ "own_windows",
+ "measured_by"
+ ],
+ "title": "WorkingMemoryCalibrationModelLine",
+ "description": "One estimator line in one environment: one the model's windows measured, or, in the current environment, one\nthe model's decode prices on that other models' windows measured."
+ },
+ "WorkingMemoryCalibrationModelRun": {
+ "properties": {
+ "run_id": {
+ "type": "string",
+ "title": "Run Id"
+ },
+ "status": {
+ "type": "string",
+ "enum": ["running", "completed", "failed", "partial", "canceled"],
+ "title": "Status"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error"
+ },
+ "error_code": {
+ "anyOf": [
+ {
+ "type": "string",
+ "const": "model_changed"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error Code",
+ "description": "Why the failed item failed, where a client acts on it (`CalibrationErrorCode`): model_changed, a model its graph names changed or was removed after the calibration was planned. Null otherwise"
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Created At"
+ },
+ "point_count": {
+ "type": "integer",
+ "title": "Point Count"
+ },
+ "attempt_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Attempt Id",
+ "description": "The client's attempt the run belongs to; null when none was sent"
+ },
+ "attempt_steps": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Attempt Steps",
+ "description": "How many runs the run's attempt planned; null without an attempt, and for a run stored before it was sent"
+ },
+ "held_back": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": ["running", "aborted_attempt"]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Held Back",
+ "description": "Why no window of the run feeds a fit: running, it or a run of its attempt is still in the queue, and its windows join once all have finished; aborted_attempt, its attempt was aborted, and its windows never feed one: an item of it ended canceled (Stop, a queue clear) or failed because a model changed after the calibration was planned (model_changed), another calibration ran on the GPU between its runs, the attempt ended before it queued all attempt_steps runs (Stop, a failed submission), or a reset removed a run of it while it ran. Null when its windows are judged like any finished run's"
+ }
+ },
+ "type": "object",
+ "required": [
+ "run_id",
+ "status",
+ "error",
+ "error_code",
+ "created_at",
+ "point_count",
+ "attempt_id",
+ "attempt_steps",
+ "held_back"
+ ],
+ "title": "WorkingMemoryCalibrationModelRun"
+ },
+ "WorkingMemoryCalibrationModelSummary": {
+ "properties": {
+ "model_key": {
+ "type": "string",
+ "title": "Model Key"
+ },
+ "device_class_id": {
+ "type": "string",
+ "title": "Device Class Id"
+ },
+ "usable": {
+ "type": "boolean",
+ "title": "Usable"
+ },
+ "problem": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Problem",
+ "description": "Why the store file is unusable"
+ },
+ "current_env_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Current Env Id",
+ "description": "Null when no generation device of this class is present"
+ },
+ "measurement_method": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Measurement Method",
+ "description": "Where a window on a GPU of this class here reads its driver figure (`counters.Method`): torch-only when this platform has no driver reader; null when no generation device of this class is present"
+ },
+ "measurement_verified": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Measurement Verified",
+ "description": "Whether that method was checked against real hardware on this backend (`counters.VERIFIED_METHODS`); null when no generation device of this class is present"
+ },
+ "lines": {
+ "items": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationModelLine"
+ },
+ "type": "array",
+ "title": "Lines"
+ },
+ "excluded_windows": {
+ "type": "integer",
+ "title": "Excluded Windows",
+ "description": "The model's windows that feed no line: invalid, not fit-eligible, fragmented, of an aborted attempt, tiled, batched, upcast, a VAE outside the AutoencoderKL family, or no demand. The valid ones among them still show as sizes that are not counted"
+ },
+ "runs": {
+ "items": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationModelRun"
+ },
+ "type": "array",
+ "title": "Runs"
+ }
+ },
+ "type": "object",
+ "required": [
+ "model_key",
+ "device_class_id",
+ "usable",
+ "problem",
+ "current_env_id",
+ "measurement_method",
+ "measurement_verified",
+ "lines",
+ "excluded_windows",
+ "runs"
+ ],
+ "title": "WorkingMemoryCalibrationModelSummary",
+ "description": "What one model's calibration runs measured on one device class, and what estimates make of it."
+ },
+ "WorkingMemoryCalibrationPixelRange": {
+ "properties": {
+ "min_pixels": {
+ "type": "integer",
+ "title": "Min Pixels"
+ },
+ "max_pixels": {
+ "type": "integer",
+ "title": "Max Pixels"
+ }
+ },
+ "type": "object",
+ "required": ["min_pixels", "max_pixels"],
+ "title": "WorkingMemoryCalibrationPixelRange"
+ },
+ "WorkingMemoryCalibrationPlan": {
+ "properties": {
+ "model_key": {
+ "type": "string",
+ "title": "Model Key"
+ },
+ "supported": {
+ "type": "boolean",
+ "title": "Supported"
+ },
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Reason",
+ "description": "Why the model cannot be calibrated here, when it cannot"
+ },
+ "device_class": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationDeviceClassRef"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The class of the GPU the cases run on; null without exactly one GPU generation device"
+ },
+ "calibrated_through": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Calibrated Through",
+ "description": "For a standalone VAE, the installed main model the cases generate with"
+ },
+ "estimators": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Estimators",
+ "description": "The working-memory estimators of the model's covered operations"
+ },
+ "cases": {
+ "items": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationCase"
+ },
+ "type": "array",
+ "title": "Cases"
+ },
+ "repetitions": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationRepetitions"
+ },
+ "estimated_seconds": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Estimated Seconds",
+ "description": "A rough order of magnitude for all cases and repetitions, model load included; not a measurement"
+ },
+ "shared_with": {
+ "items": {
+ "$ref": "#/components/schemas/WorkingMemoryCalibrationSharedModel"
+ },
+ "type": "array",
+ "title": "Shared With",
+ "description": "Other installed models whose operations price with the same lines on this GPU, so a calibration changes their estimates too"
+ },
+ "not_covered": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Not Covered",
+ "description": "Operations of the model a calibration does not measure, and why"
+ }
+ },
+ "type": "object",
+ "required": [
+ "model_key",
+ "supported",
+ "reason",
+ "device_class",
+ "calibrated_through",
+ "estimators",
+ "cases",
+ "repetitions",
+ "estimated_seconds",
+ "shared_with",
+ "not_covered"
+ ],
+ "title": "WorkingMemoryCalibrationPlan",
+ "description": "What calibrating one model on this machine's GPU runs, or why it cannot."
+ },
"WorkingMemoryCalibrationPointCount": {
"properties": {
"estimator": {
@@ -120242,12 +121106,36 @@
"required": ["estimator", "version", "valid", "fit_eligible", "count"],
"title": "WorkingMemoryCalibrationPointCount"
},
+ "WorkingMemoryCalibrationRepetitions": {
+ "properties": {
+ "warm_up": {
+ "type": "integer",
+ "title": "Warm Up",
+ "description": "Runs of each case before the measured ones; their windows count too"
+ },
+ "measured": {
+ "type": "integer",
+ "title": "Measured"
+ }
+ },
+ "type": "object",
+ "required": ["warm_up", "measured"],
+ "title": "WorkingMemoryCalibrationRepetitions"
+ },
"WorkingMemoryCalibrationRequest": {
"properties": {
"graph": {
"$ref": "#/components/schemas/Graph",
"description": "The graph to measure"
},
+ "graph_models": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/CalibrationCompiledModel"
+ },
+ "type": "object",
+ "title": "Graph Models",
+ "description": "Per model key, every model the graph names (in a node's field, inside one, or in a mapping that reads as a model identifier), as the client compiled the graph against its record. Exactly the graph's models are named (422 otherwise). The run's creation compares each with the model's record now, and refuses the run with 409 `model_changed` when any differs, so send the records the graph was compiled from, never ones read again before posting. The run records them, and admission compares them again when its item starts."
+ },
"data": {
"anyOf": [
{
@@ -120279,13 +121167,42 @@
],
"title": "Idempotency Key",
"description": "A caller-owned retry key. Repeating the request with it returns the run it created and enqueues nothing new; once a reset removed that run, the repeat is refused. Reusing the key for another request (another model, graph or batch data) is rejected while the queue keeps the key's enqueue receipt."
+ },
+ "attempt_id": {
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 64,
+ "minLength": 1,
+ "pattern": "^[A-Za-z0-9_.:-]+$"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Attempt Id",
+ "description": "A client-generated id of the calibration attempt the run belongs to (1-64 letters, digits, '_', '-', '.', ':'), so a client that enqueues one run per step can group them. Sent together with attempt_steps, never alone (422). No window of an attempt feeds an estimate until it queued attempt_steps runs and every one has finished; a run a reset removed still counts as queued, without its measurements. An aborted attempt never feeds one: an item of it ended canceled (Stop, a queue clear) or failed because a model changed after the calibration was planned (error_code model_changed), it ended before it queued all its runs (Stop, a failed submission), another calibration ran on the GPU between its runs, or a reset removed a run of it while it ran. An item that failed ends that step, not the attempt. The run id derives from the idempotency_key, the request and the attempt, so an idempotency_key names one run: repeating the request under the same attempt returns that run, and reusing the key under another attempt is refused with 409 while the queue keeps the key's receipt. Make each key unique per run of an attempt."
+ },
+ "attempt_steps": {
+ "anyOf": [
+ {
+ "type": "integer",
+ "maximum": 256.0,
+ "minimum": 1.0
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Attempt Steps",
+ "description": "How many runs the attempt (attempt_id) queues, 1-256. Sent together with attempt_id, never alone (422), and the same by every run of the attempt: a run that sends another number than the attempt's runs already stored is refused with 409. The attempt's windows feed estimates only once it queued that many runs, those a reset removed since included, and all of them have finished with no item canceled."
}
},
"additionalProperties": false,
"type": "object",
- "required": ["graph"],
+ "required": ["graph", "graph_models"],
"title": "WorkingMemoryCalibrationRequest",
- "description": "The batch a calibration run enqueues, built by the client. The server sets origin, destination, runs and the\ngraph's id, and turns the node cache off."
+ "description": "The batch a calibration run enqueues, built by the client. The server sets origin, destination, runs and the\ngraph's id, turns the node cache off, and makes every node's images intermediates on no board: never in the\ngallery, and removed by clearing intermediates."
},
"WorkingMemoryCalibrationResetResult": {
"properties": {
@@ -120377,6 +121294,19 @@
"title": "Error",
"description": "The error of a failed item, when the run failed"
},
+ "error_code": {
+ "anyOf": [
+ {
+ "type": "string",
+ "const": "model_changed"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Error Code",
+ "description": "Why the failed item failed, where a client acts on it (`CalibrationErrorCode`): model_changed, a model its graph names changed or was removed after the calibration was planned. Null otherwise"
+ },
"item_ids": {
"items": {
"type": "integer"
@@ -120388,6 +121318,30 @@
"point_count": {
"type": "integer",
"title": "Point Count"
+ },
+ "attempt_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Attempt Id",
+ "description": "The client's attempt the run belongs to; null when none was sent"
+ },
+ "attempt_steps": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Attempt Steps",
+ "description": "How many runs the run's attempt planned; null without an attempt, and for a run stored before it was sent"
}
},
"type": "object",
@@ -120400,11 +121354,45 @@
"env_id",
"status",
"error",
+ "error_code",
"item_ids",
- "point_count"
+ "point_count",
+ "attempt_id",
+ "attempt_steps"
],
"title": "WorkingMemoryCalibrationRunSummary"
},
+ "WorkingMemoryCalibrationSharedModel": {
+ "properties": {
+ "key": {
+ "type": "string",
+ "title": "Key"
+ },
+ "name": {
+ "type": "string",
+ "title": "Name"
+ },
+ "base": {
+ "type": "string",
+ "title": "Base"
+ },
+ "type": {
+ "type": "string",
+ "title": "Type"
+ },
+ "lines": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Lines",
+ "description": "The lines it shares with the planned model, `<operation>_<dtype>`"
+ }
+ },
+ "type": "object",
+ "required": ["key", "name", "base", "type", "lines"],
+ "title": "WorkingMemoryCalibrationSharedModel"
+ },
"WorkingMemoryCalibrationStatus": {
"properties": {
"available": {
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 697fd012e4..4737c98a83 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -1206,8 +1206,9 @@ export type paths = {
put?: never;
/**
* Calibrate Model Working Memory
- * @description Start a working-memory calibration run: enqueue the batch with every node uncached and measure each node's
- * model operations on the generation device. Needs exactly one generation device, and it must be a GPU. The queue
+ * @description Start a working-memory calibration run: enqueue the batch with every node uncached, its images intermediates
+ * on no board (never in the gallery; clearing intermediates removes them), and measure each node's model operations
+ * on the generation device. Needs exactly one generation device, and it must be a GPU. The queue
* takes all of the batch's items or none.
*
* Once the items are queued, a request without an `idempotency_key` succeeds even when the store fails for a passing
@@ -1248,6 +1249,50 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v2/models/i/{key}/working_memory/plan": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Model Working Memory Calibration Plan
+ * @description The text-to-image cases that calibrate the model's decode on this machine's GPU, how often each runs, which
+ * other installed models the calibration also moves, or why the model cannot be calibrated here (`supported`).
+ */
+ get: operations["get_model_working_memory_calibration_plan"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v2/models/i/{key}/working_memory/summary": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Model Working Memory Calibration Summary
+ * @description What the calibration windows of the model's lines measured on one device class, per estimator line and
+ * environment: the sizes, the largest demand, the shipped and the user estimate, whether the user line is in use,
+ * stale or unusable, and which models measured it, also for a line the model's decode shares with other models'
+ * measurements; and the model's runs.
+ */
+ get: operations["get_model_working_memory_calibration_summary"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v2/models/working_memory/runs/{run_id}": {
parameters: {
query?: never;
@@ -1261,6 +1306,10 @@ export type paths = {
/**
* Delete Working Memory Calibration Run
* @description Remove a calibration run and its measurements. Its queue items that have not run yet fail when they start.
+ *
+ * A removed run of an attempt still counts toward the attempt's runs (`attempt_steps`), so the rest of a finished
+ * attempt is judged as before. Removing a run while its attempt runs, or after it was stopped (a canceled item),
+ * stops the attempt for good: none of its measurements count.
*/
delete: operations["delete_working_memory_calibration_run"];
options?: never;
@@ -1281,7 +1330,8 @@ export type paths = {
/**
* Reset Model Working Memory Calibration
* @description Remove a model's calibration runs with all their measurements, and every measurement of the model taken in
- * other runs (a VAE measured inside a transformer's run, say), from one device class.
+ * other runs (a VAE measured inside a transformer's run, say), from one device class. Removed runs of an attempt
+ * still count toward its runs; an attempt that was running is stopped for good, its later steps included.
*/
delete: operations["reset_model_working_memory_calibration"];
options?: never;
@@ -1301,7 +1351,8 @@ export type paths = {
post?: never;
/**
* Reset Working Memory Calibration
- * @description Remove every calibration run and measurement of one device class.
+ * @description Remove every calibration run and measurement of one device class. An attempt that was running is stopped
+ * for good: its later steps never count either.
*/
delete: operations["reset_working_memory_calibration"];
options?: never;
@@ -3412,6 +3463,9 @@ export type paths = {
/**
* Retry Items By Id
* @description Retries the given queue items. Users can only retry their own items unless they are an admin.
+ *
+ * A calibration item's retry is recorded in the calibration store as it commits. When that store cannot be written,
+ * the request retries nothing, also its items that are no calibration's (503); retry again once it can.
*/
put: operations["retry_items_by_id"];
post?: never;
@@ -8267,6 +8321,32 @@ export type components = {
*/
type: "calculate_image_tiles_output";
};
+ /**
+ * CalibrationCompiledModel
+ * @description A model a calibration request's graph names, as the record the client compiled the graph against has it. Every
+ * fact is required: format and variant are null for a record without one, the rest is never null.
+ */
+ CalibrationCompiledModel: {
+ /** Base */
+ base: string;
+ /** Type */
+ type: string;
+ /**
+ * Format
+ * @description The model's format; null for a record without one
+ */
+ format: string | null;
+ /**
+ * Variant
+ * @description The model's variant; null for a record without one
+ */
+ variant: string | null;
+ /**
+ * Hash
+ * @description The model's hash, as the graph's identifier names it
+ */
+ hash: string;
+ };
/**
* CalibrationDeviceClass
* @description A `fingerprint.DeviceClass` with its id as a plain field, as it is stored and returned.
@@ -54327,6 +54407,67 @@ export type components = {
[key: string]: components["schemas"]["JsonValue"];
} | null;
};
+ /**
+ * WorkingMemoryCalibrationCase
+ * @description One generation a calibration plan runs, in the fields of the client's graph-export case (mode txt2img).
+ */
+ WorkingMemoryCalibrationCase: {
+ /**
+ * Id
+ * @description Unique within the plan; becomes the graph id
+ */
+ id: string;
+ /**
+ * Mode
+ * @default txt2img
+ * @constant
+ */
+ mode?: "txt2img";
+ /**
+ * Model Key
+ * @description The main model the case generates with
+ */
+ model_key: string;
+ /**
+ * Components
+ * @description Component picks by Generate slot key; `vae` when a standalone VAE is calibrated or a GPU VAE must be picked over one that runs on the CPU
+ */
+ components: {
+ [key: string]: string;
+ };
+ /** Width */
+ width: number;
+ /** Height */
+ height: number;
+ /**
+ * Steps
+ * @description The fewest steps that still run the whole pipeline
+ */
+ steps: number;
+ /** Seed */
+ seed: number;
+ /** Positive Prompt */
+ positive_prompt: string;
+ /** Negative Prompt */
+ negative_prompt: string;
+ /**
+ * Settings
+ * @description Generate settings overrides: `vaePrecision` (fp16 or fp32) where the decode node casts the VAE
+ */
+ settings: {
+ [key: string]: string;
+ };
+ /**
+ * Estimator
+ * @description The working-memory estimator of the operation the case measures
+ */
+ estimator: string;
+ /**
+ * Line
+ * @description The estimator line the case measures, `<operation>_<dtype>`
+ */
+ line: string;
+ };
/** WorkingMemoryCalibrationDeviceClass */
WorkingMemoryCalibrationDeviceClass: {
/** Device Class Id */
@@ -54342,6 +54483,16 @@ export type components = {
problem: string | null;
/** Is Current */
is_current: boolean;
+ /**
+ * Measurement Method
+ * @description Where a window on a GPU of this class here reads its driver figure (`counters.Method`): torch-only when this platform has no driver reader; null when no generation device of this class is present
+ */
+ measurement_method: string | null;
+ /**
+ * Measurement Verified
+ * @description Whether that method was checked against real hardware on this backend (`counters.VERIFIED_METHODS`); null when no generation device of this class is present
+ */
+ measurement_verified: boolean | null;
/** Runs */
runs: components["schemas"]["WorkingMemoryCalibrationRunSummary"][];
/** Point Counts */
@@ -54349,6 +54500,13 @@ export type components = {
/** Envs */
envs: components["schemas"]["WorkingMemoryCalibrationEnvironment"][];
};
+ /** WorkingMemoryCalibrationDeviceClassRef */
+ WorkingMemoryCalibrationDeviceClassRef: {
+ /** Id */
+ id: string;
+ /** Name */
+ name: string;
+ };
/** WorkingMemoryCalibrationEnvironment */
WorkingMemoryCalibrationEnvironment: {
/** Id */
@@ -54368,12 +54526,258 @@ export type components = {
hard_matches_current: boolean | null;
/**
* Soft Matches Current
- * @description Whether the current environment has the same soft facts; null off the current device class
+ * @description Whether the current environment has the soft facts first recorded with this environment (`soft`); a later run's own soft facts are not compared here. Null off the current device class
*/
soft_matches_current: boolean | null;
/** Point Count */
point_count: number;
};
+ /**
+ * WorkingMemoryCalibrationLineContributor
+ * @description A model whose windows feed a line: the model a run calibrated, or the model a window measured.
+ */
+ WorkingMemoryCalibrationLineContributor: {
+ /** Model Key */
+ model_key: string;
+ /**
+ * Name
+ * @description The model's name; null when it is no longer installed
+ */
+ name: string | null;
+ /**
+ * Windows
+ * @description Its counted windows on the line: valid, fit-eligible and not fragmented
+ */
+ windows: number;
+ };
+ /** WorkingMemoryCalibrationLineSize */
+ WorkingMemoryCalibrationLineSize: {
+ /** Width */
+ width: number;
+ /** Height */
+ height: number;
+ /** Pixels */
+ pixels: number;
+ /**
+ * Windows
+ * @description Counted: the windows at this size that feed the line, valid, fit-eligible and not fragmented, of every model in the environment; those of a calibration run still running are counted, and join the fit once it finished. Not counted: the valid windows measured at this size
+ */
+ windows: number;
+ /**
+ * Measured Bytes
+ * @description The largest demand of those windows
+ */
+ measured_bytes: number;
+ /**
+ * Counted
+ * @description Whether windows of this size feed the user line
+ */
+ counted: boolean;
+ /**
+ * Excluded Reason
+ * @description Why a size is not counted: fragmented, its windows measured the allocator's fragmentation (`backend/working_memory/fragmentation.py`); partial_residency, the model was not fully on the device; aborted_attempt, its windows come from aborted attempts (Stop, a queue clear, a failed submission, a model changed after the calibration was planned), which never feed a line. Null for a counted size
+ */
+ excluded_reason: ("fragmented" | "partial_residency" | "aborted_attempt") | null;
+ /**
+ * Shipped Bytes
+ * @description The shipped estimate at this size, priced with the line's estimator where one of its windows measured the size, otherwise with that of the largest window; null when the platform of the environment is unknown
+ */
+ shipped_bytes: number | null;
+ /**
+ * User Bytes
+ * @description The estimate with the user line applied, as estimates read it (without the windows of runs still running); null without a user line
+ */
+ user_bytes: number | null;
+ };
+ /**
+ * WorkingMemoryCalibrationModelLine
+ * @description One estimator line in one environment: one the model's windows measured, or, in the current environment, one
+ * the model's decode prices on that other models' windows measured.
+ */
+ WorkingMemoryCalibrationModelLine: {
+ /** Estimator */
+ estimator: string;
+ /** Version */
+ version: number;
+ /**
+ * Line
+ * @description `<operation>_<dtype>`
+ */
+ line: string;
+ /**
+ * Carrier
+ * @description The estimator whose shipped entry carries the line on this platform
+ */
+ carrier: string | null;
+ /** Env Id */
+ env_id: string;
+ /**
+ * State
+ * @description in_use: the user line applies; stale: it applies, but the soft facts of the newest finished run that contributed a window differ from the current ones; unusable: hard facts differ from the current environment (or no GPU of this class generates here), so shipped values apply; insufficient: the windows of finished, complete attempts cannot fit a line (yet); `problem` says why
+ * @enum {string}
+ */
+ state: "in_use" | "stale" | "unusable" | "insufficient";
+ /**
+ * Changed Facts
+ * @description The soft facts that changed (stale) or the hard facts that differ (unusable)
+ */
+ changed_facts: string[];
+ /**
+ * Problem
+ * @description Why no line could be fitted, when it could not
+ */
+ problem: string | null;
+ /** @description The sizes the user line was fitted on, over every model's windows of the line from finished runs */
+ measured_range: components["schemas"]["WorkingMemoryCalibrationPixelRange"] | null;
+ /** Slope Bytes Per Pixel */
+ slope_bytes_per_pixel: number | null;
+ /** Base Bytes */
+ base_bytes: number | null;
+ /** Sizes */
+ sizes: components["schemas"]["WorkingMemoryCalibrationLineSize"][];
+ /**
+ * Own Windows
+ * @description The model's own windows that feed the line; 0 when only other models' do
+ */
+ own_windows: number;
+ /**
+ * Measured By
+ * @description Every model whose windows feed the line, this one included when it has any; by name, then key
+ */
+ measured_by: components["schemas"]["WorkingMemoryCalibrationLineContributor"][];
+ };
+ /** WorkingMemoryCalibrationModelRun */
+ WorkingMemoryCalibrationModelRun: {
+ /** Run Id */
+ run_id: string;
+ /**
+ * Status
+ * @enum {string}
+ */
+ status: "running" | "completed" | "failed" | "partial" | "canceled";
+ /** Error */
+ error: string | null;
+ /**
+ * Error Code
+ * @description Why the failed item failed, where a client acts on it (`CalibrationErrorCode`): model_changed, a model its graph names changed or was removed after the calibration was planned. Null otherwise
+ */
+ error_code: "model_changed" | null;
+ /**
+ * Created At
+ * Format: date-time
+ */
+ created_at: string;
+ /** Point Count */
+ point_count: number;
+ /**
+ * Attempt Id
+ * @description The client's attempt the run belongs to; null when none was sent
+ */
+ attempt_id: string | null;
+ /**
+ * Attempt Steps
+ * @description How many runs the run's attempt planned; null without an attempt, and for a run stored before it was sent
+ */
+ attempt_steps: number | null;
+ /**
+ * Held Back
+ * @description Why no window of the run feeds a fit: running, it or a run of its attempt is still in the queue, and its windows join once all have finished; aborted_attempt, its attempt was aborted, and its windows never feed one: an item of it ended canceled (Stop, a queue clear) or failed because a model changed after the calibration was planned (model_changed), another calibration ran on the GPU between its runs, the attempt ended before it queued all attempt_steps runs (Stop, a failed submission), or a reset removed a run of it while it ran. Null when its windows are judged like any finished run's
+ */
+ held_back: ("running" | "aborted_attempt") | null;
+ };
+ /**
+ * WorkingMemoryCalibrationModelSummary
+ * @description What one model's calibration runs measured on one device class, and what estimates make of it.
+ */
+ WorkingMemoryCalibrationModelSummary: {
+ /** Model Key */
+ model_key: string;
+ /** Device Class Id */
+ device_class_id: string;
+ /** Usable */
+ usable: boolean;
+ /**
+ * Problem
+ * @description Why the store file is unusable
+ */
+ problem: string | null;
+ /**
+ * Current Env Id
+ * @description Null when no generation device of this class is present
+ */
+ current_env_id: string | null;
+ /**
+ * Measurement Method
+ * @description Where a window on a GPU of this class here reads its driver figure (`counters.Method`): torch-only when this platform has no driver reader; null when no generation device of this class is present
+ */
+ measurement_method: string | null;
+ /**
+ * Measurement Verified
+ * @description Whether that method was checked against real hardware on this backend (`counters.VERIFIED_METHODS`); null when no generation device of this class is present
+ */
+ measurement_verified: boolean | null;
+ /** Lines */
+ lines: components["schemas"]["WorkingMemoryCalibrationModelLine"][];
+ /**
+ * Excluded Windows
+ * @description The model's windows that feed no line: invalid, not fit-eligible, fragmented, of an aborted attempt, tiled, batched, upcast, a VAE outside the AutoencoderKL family, or no demand. The valid ones among them still show as sizes that are not counted
+ */
+ excluded_windows: number;
+ /** Runs */
+ runs: components["schemas"]["WorkingMemoryCalibrationModelRun"][];
+ };
+ /** WorkingMemoryCalibrationPixelRange */
+ WorkingMemoryCalibrationPixelRange: {
+ /** Min Pixels */
+ min_pixels: number;
+ /** Max Pixels */
+ max_pixels: number;
+ };
+ /**
+ * WorkingMemoryCalibrationPlan
+ * @description What calibrating one model on this machine's GPU runs, or why it cannot.
+ */
+ WorkingMemoryCalibrationPlan: {
+ /** Model Key */
+ model_key: string;
+ /** Supported */
+ supported: boolean;
+ /**
+ * Reason
+ * @description Why the model cannot be calibrated here, when it cannot
+ */
+ reason: string | null;
+ /** @description The class of the GPU the cases run on; null without exactly one GPU generation device */
+ device_class: components["schemas"]["WorkingMemoryCalibrationDeviceClassRef"] | null;
+ /**
+ * Calibrated Through
+ * @description For a standalone VAE, the installed main model the cases generate with
+ */
+ calibrated_through: string | null;
+ /**
+ * Estimators
+ * @description The working-memory estimators of the model's covered operations
+ */
+ estimators: string[];
+ /** Cases */
+ cases: components["schemas"]["WorkingMemoryCalibrationCase"][];
+ repetitions: components["schemas"]["WorkingMemoryCalibrationRepetitions"];
+ /**
+ * Estimated Seconds
+ * @description A rough order of magnitude for all cases and repetitions, model load included; not a measurement
+ */
+ estimated_seconds: number | null;
+ /**
+ * Shared With
+ * @description Other installed models whose operations price with the same lines on this GPU, so a calibration changes their estimates too
+ */
+ shared_with: components["schemas"]["WorkingMemoryCalibrationSharedModel"][];
+ /**
+ * Not Covered
+ * @description Operations of the model a calibration does not measure, and why
+ */
+ not_covered: string[];
+ };
/** WorkingMemoryCalibrationPointCount */
WorkingMemoryCalibrationPointCount: {
/** Estimator */
@@ -54387,14 +54791,32 @@ export type components = {
/** Count */
count: number;
};
+ /** WorkingMemoryCalibrationRepetitions */
+ WorkingMemoryCalibrationRepetitions: {
+ /**
+ * Warm Up
+ * @description Runs of each case before the measured ones; their windows count too
+ */
+ warm_up: number;
+ /** Measured */
+ measured: number;
+ };
/**
* WorkingMemoryCalibrationRequest
* @description The batch a calibration run enqueues, built by the client. The server sets origin, destination, runs and the
- * graph's id, and turns the node cache off.
+ * graph's id, turns the node cache off, and makes every node's images intermediates on no board: never in the
+ * gallery, and removed by clearing intermediates.
*/
WorkingMemoryCalibrationRequest: {
/** @description The graph to measure */
graph: components["schemas"]["Graph"];
+ /**
+ * Graph Models
+ * @description Per model key, every model the graph names (in a node's field, inside one, or in a mapping that reads as a model identifier), as the client compiled the graph against its record. Exactly the graph's models are named (422 otherwise). The run's creation compares each with the model's record now, and refuses the run with 409 `model_changed` when any differs, so send the records the graph was compiled from, never ones read again before posting. The run records them, and admission compares them again when its item starts.
+ */
+ graph_models: {
+ [key: string]: components["schemas"]["CalibrationCompiledModel"];
+ };
/**
* Data
* @description The batch data collection
@@ -54405,6 +54827,16 @@ export type components = {
* @description A caller-owned retry key. Repeating the request with it returns the run it created and enqueues nothing new; once a reset removed that run, the repeat is refused. Reusing the key for another request (another model, graph or batch data) is rejected while the queue keeps the key's enqueue receipt.
*/
idempotency_key?: string | null;
+ /**
+ * Attempt Id
+ * @description A client-generated id of the calibration attempt the run belongs to (1-64 letters, digits, '_', '-', '.', ':'), so a client that enqueues one run per step can group them. Sent together with attempt_steps, never alone (422). No window of an attempt feeds an estimate until it queued attempt_steps runs and every one has finished; a run a reset removed still counts as queued, without its measurements. An aborted attempt never feeds one: an item of it ended canceled (Stop, a queue clear) or failed because a model changed after the calibration was planned (error_code model_changed), it ended before it queued all its runs (Stop, a failed submission), another calibration ran on the GPU between its runs, or a reset removed a run of it while it ran. An item that failed ends that step, not the attempt. The run id derives from the idempotency_key, the request and the attempt, so an idempotency_key names one run: repeating the request under the same attempt returns that run, and reusing the key under another attempt is refused with 409 while the queue keeps the key's receipt. Make each key unique per run of an attempt.
+ */
+ attempt_id?: string | null;
+ /**
+ * Attempt Steps
+ * @description How many runs the attempt (attempt_id) queues, 1-256. Sent together with attempt_id, never alone (422), and the same by every run of the attempt: a run that sends another number than the attempt's runs already stored is refused with 409. The attempt's windows feed estimates only once it queued that many runs, those a reset removed since included, and all of them have finished with no item canceled.
+ */
+ attempt_steps?: number | null;
};
/** WorkingMemoryCalibrationResetResult */
WorkingMemoryCalibrationResetResult: {
@@ -54453,6 +54885,11 @@ export type components = {
* @description The error of a failed item, when the run failed
*/
error: string | null;
+ /**
+ * Error Code
+ * @description Why the failed item failed, where a client acts on it (`CalibrationErrorCode`): model_changed, a model its graph names changed or was removed after the calibration was planned. Null otherwise
+ */
+ error_code: "model_changed" | null;
/**
* Item Ids
* @description Every queue item of the run known, retries and the items they retried
@@ -54460,6 +54897,32 @@ export type components = {
item_ids: number[];
/** Point Count */
point_count: number;
+ /**
+ * Attempt Id
+ * @description The client's attempt the run belongs to; null when none was sent
+ */
+ attempt_id: string | null;
+ /**
+ * Attempt Steps
+ * @description How many runs the run's attempt planned; null without an attempt, and for a run stored before it was sent
+ */
+ attempt_steps: number | null;
+ };
+ /** WorkingMemoryCalibrationSharedModel */
+ WorkingMemoryCalibrationSharedModel: {
+ /** Key */
+ key: string;
+ /** Name */
+ name: string;
+ /** Base */
+ base: string;
+ /** Type */
+ type: string;
+ /**
+ * Lines
+ * @description The lines it shares with the planned model, `<operation>_<dtype>`
+ */
+ lines: string[];
};
/** WorkingMemoryCalibrationStatus */
WorkingMemoryCalibrationStatus: {
@@ -57662,14 +58125,14 @@ export interface operations {
};
content?: never;
};
- /** @description This machine cannot calibrate now (no GPU, or several generation devices), the device class's store file is unusable and kept as it is (possibly after the items were queued, which then fail when they start), the queue has no room for all of the run's items (it then takes none), or the idempotency key was used for another request */
+ /** @description This machine cannot calibrate now (no GPU, or several generation devices), the device class's store file is unusable and kept as it is (possibly after the items were queued, which then fail when they start), the queue has no room for all of the run's items (it then takes none), the idempotency key was used for another request, or attempt_steps differs from that of the attempt's runs already stored (or of the run a repeated request names). Three of them carry a code, as `{"code": ..., "message": ...}` in `detail`: `calibration_running`, another calibration attempt still runs on this GPU, or another owner's attempt is between its steps and was active in the last two minutes (an owner's new attempt replaces its own attempt that stopped between steps); `calibration_interleaved`, a later step of an attempt after another calibration ran on this GPU since the attempt began; `model_changed`, a model the graph names changed or was removed since the graph was compiled (its record differs from the graph's identifier or its graph_models entry), or since an earlier step of the attempt */
409: {
headers: {
[name: string]: unknown;
};
content?: never;
};
- /** @description The graph cannot be measured as a calibration run */
+ /** @description The graph cannot be measured as a calibration run, graph_models does not state exactly the graph's models, or attempt_id and attempt_steps were not sent together */
422: {
headers: {
[name: string]: unknown;
@@ -57719,6 +58182,101 @@ export interface operations {
};
};
};
+ get_model_working_memory_calibration_plan: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ /** @description Key of the model to calibrate */
+ key: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WorkingMemoryCalibrationPlan"];
+ };
+ };
+ /** @description The model could not be found */
+ 404: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
+ get_model_working_memory_calibration_summary: {
+ parameters: {
+ query?: {
+ /** @description The device class to act on; the current generation device's by default */
+ device_class_id?: string | null;
+ };
+ header?: never;
+ path: {
+ /** @description Key of the model whose measurements to summarise */
+ key: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WorkingMemoryCalibrationModelSummary"];
+ };
+ };
+ /** @description The model could not be found */
+ 404: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description No device_class_id was given and there is no current one */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ /** @description The calibration store cannot be read or written (unwritable root, lock timeout) */
+ 503: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ };
+ };
delete_working_memory_calibration_run: {
parameters: {
query?: never;
@@ -62118,6 +62676,13 @@ export interface operations {
"application/json": components["schemas"]["HTTPValidationError"];
};
};
+ /** @description The items include a working-memory calibration's, and its store cannot be written now (unwritable root, lock timeout): no item is retried, the request's other items included */
+ 503: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
};
};
clear: {
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 545b0b1407..066746fc7f 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -30,7 +30,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 29,
"scriptRawBytes": 1919842,
"scriptRequestCount": 25,
@@ -68,7 +68,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 0,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 29,
"scriptRawBytes": 1919842,
"scriptRequestCount": 25,
@@ -106,7 +106,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 87,
"scriptRawBytes": 4350945,
"scriptRequestCount": 82,
@@ -144,7 +144,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 87,
"scriptRawBytes": 4350945,
"scriptRequestCount": 82,
@@ -182,7 +182,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 96,
"scriptRawBytes": 4895726,
"scriptRequestCount": 91,
@@ -220,7 +220,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 96,
"scriptRawBytes": 4895726,
"scriptRequestCount": 91,
@@ -258,7 +258,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 94,
"scriptRawBytes": 4818320,
"scriptRequestCount": 88,
@@ -296,7 +296,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 94,
"scriptRawBytes": 4818320,
"scriptRequestCount": 88,
@@ -334,7 +334,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 87,
"scriptRawBytes": 4350945,
"scriptRequestCount": 82,
@@ -372,7 +372,7 @@
"fontRawBytes": 23664,
"imageRawBytes": 44398,
"largestAssetRawBytes": 751922,
- "otherRawBytes": 246409,
+ "otherRawBytes": 251060,
"requestCount": 87,
"scriptRawBytes": 4350945,
"scriptRequestCount": 82,
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 5f770878e7..a3f145bd5f 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1693,7 +1693,98 @@
"variant": "Variant",
"variantHelp": "Architecture variant, e.g. inpaint or dev.",
"viewModel": "View model",
- "viewQueue": "View queue"
+ "viewQueue": "View queue",
+ "workingMemory": {
+ "title": "Working memory",
+ "description": "Measures this model's VAE decode on this GPU, so Invoke reserves what it really needs.",
+ "loadFailed": "Could not load working memory",
+ "stateInUse": "Calibrated",
+ "stateStale": "May be outdated",
+ "stateUnusable": "Not used",
+ "stateInsufficient": "Too few sizes",
+ "stateInterrupted": "Interrupted",
+ "stateNone": "Not calibrated",
+ "operationDecode": "Decode",
+ "operationEncode": "Encode",
+ "pair": "{{label}} · {{detail}}",
+ "size": "{{width}} × {{height}}",
+ "measuredRange": "Fitted on {{min}}–{{max}} MP",
+ "tableLabel": "{{line}} measurements",
+ "columnSize": "Size",
+ "columnMeasured": "Measured",
+ "columnShipped": "Built-in",
+ "columnCalibrated": "Calibrated estimate",
+ "aboutColumn": "About {{column}}",
+ "hintMeasured": "The most VRAM the decode took at this size on this GPU, beyond the model weights.",
+ "hintShipped": "What Invoke reserves without calibration: values measured on reference GPUs, plus 5%.",
+ "hintCalibrated": "What Invoke reserves after calibration: a line fitted over your counted measurements, plus 5%. Beyond the largest measured size, the larger of this and Built-in applies.",
+ "notCounted": "Not counted",
+ "notCountedFragmented": "Not counted: allocator fragmentation",
+ "notCountedPartial": "Not counted: model not fully on GPU",
+ "notCountedAborted": "Not counted: calibration interrupted",
+ "helpInUse": "Estimates use these measurements.",
+ "helpStale": "Still used, but {{facts}} changed since.",
+ "helpUnusable": "Built-in estimates apply: {{facts}} differs.",
+ "helpUnusableNoFacts": "Built-in estimates apply: measured on a GPU not present here.",
+ "helpInsufficient": "Built-in estimates apply until more sizes are measured.",
+ "helpInterrupted": "Measured only by an interrupted calibration. Built-in estimates apply until you calibrate again.",
+ "sharedWith_one": "Also changes {{count}} other model",
+ "sharedWith_other": "Also changes {{count}} other models",
+ "notVerified": "Measurement method not verified on this hardware",
+ "neverCalibrated": "Not calibrated on this GPU. Built-in estimates apply.",
+ "usesOthers": "Uses measurements from other models on this GPU.",
+ "measuredBy": "Measured on: {{models}}",
+ "removedModel": "Removed model",
+ "modelRemoved": "This model is no longer installed.",
+ "encodeNotCovered": "Image-to-image and inpainting encodes keep the built-in estimates.",
+ "floorNote": "Only matters above the working-memory floor. It can change which large decodes tile, and tiled output is not pixel-identical.",
+ "calibrate": "Calibrate",
+ "recalibrate": "Recalibrate",
+ "stop": "Stop",
+ "blockedUnsupported": "This model cannot be calibrated.",
+ "blockedUnavailable": "Not available on this machine.",
+ "blockedStoreUnusable": "Calibration file unusable: {{problem}}",
+ "blockedRunning": "A calibration is queued or running.",
+ "alreadyRunning": "A calibration is already running on this GPU.",
+ "busyOnGpu": "A calibration of {{model}} is running on this GPU. Wait until it finishes, or stop it.",
+ "modelChanged": "The model changed after this calibration was planned. Calibrate again.",
+ "interleaved": "Another calibration ran on this GPU while this one was in progress. Calibrate again.",
+ "blockedCompile": "Cannot build the calibration runs: {{problem}}",
+ "queuing": "Queuing: {{done}}/{{total}}",
+ "running": "Calibrating: {{done}}/{{total}} runs",
+ "progressLabel": "Calibration progress",
+ "canceled": "Calibration stopped.",
+ "discarded": "This calibration's measurements were discarded.",
+ "failed": "Calibration failed",
+ "failedKept": "The other sizes it measured still count.",
+ "partial": "Calibration incomplete",
+ "partialQueued": "Only {{queued}} of {{total}} runs were queued.",
+ "partialCanceled": "Some runs were canceled.",
+ "stopTitle": "Stop calibration?",
+ "stopBody": "Queued runs are canceled, and all of this calibration's measurements are discarded, finished runs included.",
+ "stopFailed": "Could not stop calibration",
+ "resetTitle": "Reset calibration?",
+ "resetBody": "Removes this model's measurements on this GPU. Other models' measurements on the same lines still apply.",
+ "resetDone": "Calibration reset",
+ "resetFailed": "Could not reset calibration",
+ "dialogTitle": "Calibrate working memory",
+ "dialogDescription": "Runs short generations on {{device}}.",
+ "dialogDuration": "About {{minutes}} min.",
+ "dialogQueueNote": "They wait in the queue behind current work.",
+ "dialogThrough": "Generates with {{model}}.",
+ "dialogRuns": "Runs: {{count}}",
+ "dialogRepetitions": "Per size: {{warmUp}} warm-up, {{measured}} measured.",
+ "dialogChanged": "This calibration changed since it opened. Check it, then calibrate.",
+ "dialogSizesNote": "Sizes follow the GPU memory free when you calibrate.",
+ "facts": {
+ "allocator": "memory allocator",
+ "driver": "GPU driver",
+ "invokeai": "Invoke version",
+ "osBuild": "OS build",
+ "sdpaGuard": "ROCm attention guard",
+ "torchBuild": "PyTorch build"
+ }
+ }
},
"nodes": {
"addNodes": "Add Nodes",
diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
index 04d6739b00..bf8c3d2555 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs
@@ -225,8 +225,8 @@ test('the HTTP reset contract selects profiles explicitly and restores the start
}
});
-const withRepresentativeBackend = async (run) => {
- const backend = await startMockBackend(0, { profile: 'representative' });
+const withRepresentativeBackend = async (run, options = {}) => {
+ const backend = await startMockBackend(0, { ...options, profile: 'representative' });
try {
await run(backend);
@@ -1221,6 +1221,370 @@ test('workflow thumbnails round-trip their bytes and refresh the listed URL on e
});
});
+test('working-memory calibration: a run per request, replayed by its key, advanced by summary reads', async () => {
+ let now = 0;
+
+ await withRepresentativeBackend(
+ async (backend) => {
+ const base = '/api/v2/models/i/fixture-model-001/working_memory';
+ const plan = await getJson(backend, `${base}/plan`);
+ const request = (key, attempt = { attempt_id: 'attempt-1', attempt_steps: 2 }, nodes = {}, graphModels = {}) => ({
+ body: JSON.stringify({
+ ...attempt,
+ data: [],
+ graph: { edges: [], id: plan.cases[0].id, nodes },
+ graph_models: graphModels,
+ idempotency_key: key,
+ }),
+ method: 'POST',
+ });
+ const post = (key) => getJson(backend, `${base}/calibrate`, request(key));
+ const refusal = async (key, attempt) =>
+ (await fetch(`${backend.origin}${base}/calibrate`, request(key, attempt))).status;
+ /** The answer to a request whose graph names `model` as it compiled over it, stating `compiled` for it. */
+ const refusedFor = async (key, model, compiled = {}) => {
+ const identity = { base: model.base, format: record.format, hash: model.hash, type: model.type, variant: null };
+ const graphModels = { [model.key]: { ...identity, ...compiled } };
+ const response = await fetch(
+ `${backend.origin}${base}/calibrate`,
+ request(key, undefined, { main_model_loader: { id: 'main_model_loader', model } }, graphModels)
+ );
+ return [response.status, (await response.json()).detail];
+ };
+ const record = (await getJson(backend, '/api/v2/models/')).models.find(
+ (model) => model.key === 'fixture-model-001'
+ );
+ const identifier = {
+ base: record.base,
+ hash: record.hash,
+ key: record.key,
+ name: record.name,
+ type: record.type,
+ };
+
+ assert.equal(plan.supported, true);
+ assert.deepEqual((await getJson(backend, `${base}/summary`)).runs, []);
+
+ // The attempt id and its step count come together, and every run of an attempt names the same count.
+ assert.equal(await refusal('lone-id', { attempt_id: 'attempt-2' }), 422);
+ assert.equal(await refusal('lone-steps', { attempt_steps: 2 }), 422);
+ assert.equal(await refusal('too-many', { attempt_id: 'attempt-2', attempt_steps: 257 }), 422);
+
+ // A graph naming a model whose record changed, or that was removed, since it compiled is refused with a code.
+ assert.deepEqual(await refusedFor('stale', { ...identifier, hash: 'blake3:old' }), [
+ 409,
+ {
+ code: 'model_changed',
+ message: 'Fixture Model 001 changed after this calibration was planned (hash). Calibrate again.',
+ },
+ ]);
+ assert.deepEqual(await refusedFor('gone', { ...identifier, key: 'removed-model', name: 'Old SDXL' }), [
+ 409,
+ { code: 'model_changed', message: 'Old SDXL was removed after this calibration was planned. Calibrate again.' },
+ ]);
+ // The graph's identifier carries no variant: the identity compiled with it does.
+ assert.deepEqual(await refusedFor('variant', identifier, { variant: 'inpaint' }), [
+ 409,
+ {
+ code: 'model_changed',
+ message: 'Fixture Model 001 changed after this calibration was planned (variant). Calibrate again.',
+ },
+ ]);
+ // graph_models states exactly the graph's models, every fact of each.
+ const unstated = await fetch(
+ `${backend.origin}${base}/calibrate`,
+ request('unstated', undefined, { main_model_loader: { id: 'main_model_loader', model: identifier } })
+ );
+ assert.equal(unstated.status, 422);
+ assert.match((await unstated.json()).detail, /the graph names fixture-model-001, which graph_models lacks/);
+ const nullHash = await fetch(
+ `${backend.origin}${base}/calibrate`,
+ request(
+ 'null-hash',
+ undefined,
+ { main_model_loader: { id: 'main_model_loader', model: identifier } },
+ {
+ [identifier.key]: {
+ base: identifier.base,
+ format: record.format,
+ hash: null,
+ type: identifier.type,
+ variant: null,
+ },
+ }
+ )
+ );
+ assert.equal(nullHash.status, 422);
+ assert.match((await nullHash.json()).detail, /graph_models\[fixture-model-001\] does not state every fact/);
+
+ const first = await post('attempt:0');
+ assert.deepEqual(await post('attempt:0'), first);
+ assert.equal(await refusal('attempt:1', { attempt_id: 'attempt-1', attempt_steps: 3 }), 409);
+ // One attempt per GPU: another one is refused with a code while this one runs, on this model or another.
+ const busy = await fetch(
+ `${backend.origin}${base}/calibrate`,
+ request('other:0', { attempt_id: 'attempt-2', attempt_steps: 2 })
+ );
+ assert.equal(busy.status, 409);
+ assert.equal((await busy.json()).detail.code, 'calibration_running');
+ const second = await post('attempt:1');
+ assert.notEqual(second.run_id, first.run_id);
+
+ // A read a second after the last step finishes the running item and starts the next one.
+ const statuses = async () => {
+ now += 1_050;
+ return (await getJson(backend, `${base}/summary`)).runs.map((run) => run.status);
+ };
+ assert.deepEqual(await statuses(), ['running', 'running']);
+ const summary = await getJson(backend, `${base}/summary`);
+ assert.deepEqual(
+ summary.runs.map((run) => [run.attempt_id, run.attempt_steps, run.held_back, run.error_code]),
+ [
+ ['attempt-1', 2, 'running', null],
+ ['attempt-1', 2, 'running', null],
+ ]
+ );
+ assert.equal(summary.measurement_verified, true);
+ const badAttempt = await fetch(`${backend.origin}${base}/calibrate`, {
+ body: JSON.stringify({ attempt_id: 'has space', graph: { edges: [], id: 'x', nodes: {} }, graph_models: {} }),
+ method: 'POST',
+ });
+ assert.equal(badAttempt.status, 422);
+ assert.deepEqual(await statuses(), ['completed', 'running']);
+
+ const origin = encodeURIComponent(`invokeai:wm-calibration:${second.run_id}`);
+ assert.deepEqual(
+ await getJson(backend, `/api/v1/queue/default/cancel_all?origin_prefix=${origin}`, { method: 'PUT' }),
+ {
+ canceled: 1,
+ }
+ );
+ assert.deepEqual(await statuses(), ['completed', 'canceled']);
+
+ // The canceled run aborts its attempt: the window the first run measured never counts.
+ const aborted = await getJson(backend, `${base}/summary`);
+ assert.deepEqual(
+ aborted.runs.map((run) => run.held_back),
+ ['aborted_attempt', 'aborted_attempt']
+ );
+ // As the server stores them: the second run was canceled during its decode, which left an invalid window.
+ assert.deepEqual(
+ aborted.runs.map((run) => [run.status, run.point_count]),
+ [
+ ['completed', 1],
+ ['canceled', 1],
+ ]
+ );
+ const [line] = aborted.lines;
+ assert.equal(line.state, 'insufficient');
+ assert.match(line.problem, /^Stop or an interrupted submission discarded the measurements of this line/);
+ assert.deepEqual(
+ line.sizes.map((size) => [size.counted, size.excluded_reason]),
+ [[false, 'aborted_attempt']]
+ );
+ assert.equal(
+ (await getJson(backend, '/api/v2/models/working_memory/status')).device_classes[0].runs.find(
+ (run) => run.run_id === first.run_id
+ ).attempt_steps,
+ 2
+ );
+
+ assert.deepEqual(await getJson(backend, base, { method: 'DELETE' }), { points_removed: 1, runs_removed: 2 });
+ assert.deepEqual((await getJson(backend, `${base}/summary`)).lines, []);
+ // Calibration items never join the fixture queue.
+ assert.equal((await getJson(backend, '/api/v1/queue/default/item_ids')).total_count, 500);
+ },
+ { clock: () => now }
+ );
+});
+
+test('working-memory calibration: an open attempt holds the GPU, and a step after another calibration is refused', async () => {
+ let now = 0;
+
+ await withRepresentativeBackend(
+ async (backend) => {
+ const calibrate = async (modelKey, attempt_id, index) => {
+ const base = `/api/v2/models/i/${modelKey}/working_memory`;
+ const plan = await getJson(backend, `${base}/plan`);
+ const response = await fetch(`${backend.origin}${base}/calibrate`, {
+ body: JSON.stringify({
+ attempt_id,
+ attempt_steps: 3,
+ data: [],
+ graph: { edges: [], id: plan.cases[0].id, nodes: {} },
+ graph_models: {},
+ idempotency_key: `${attempt_id}:${String(index)}`,
+ }),
+ method: 'POST',
+ });
+ const body = await response.json();
+ return [response.status, body.detail?.code ?? null];
+ };
+ const summaryOf = (modelKey) => getJson(backend, `/api/v2/models/i/${modelKey}/working_memory/summary`);
+
+ // The first of three steps runs, then finishes: the attempt is between its steps.
+ assert.deepEqual(await calibrate('fixture-model-061', 'mine', 0), [201, null]);
+ for (const _ of [0, 1]) {
+ now += 1_050;
+ await summaryOf('fixture-model-061');
+ }
+ assert.deepEqual(
+ (await summaryOf('fixture-model-061')).runs.map((run) => run.status),
+ ['completed']
+ );
+
+ // Open, it still holds the GPU: another attempt is refused, on any model.
+ assert.deepEqual(await calibrate('fixture-model-021', 'theirs', 0), [409, 'calibration_running']);
+
+ // Idle past the grace, it is taken for abandoned and holds nothing.
+ now += 120_001;
+ assert.deepEqual(await calibrate('fixture-model-021', 'theirs', 0), [201, null]);
+
+ // Another calibration ran since its first step: its next step is refused, and it stays short, so aborted.
+ assert.deepEqual(await calibrate('fixture-model-061', 'mine', 1), [409, 'calibration_interleaved']);
+ assert.deepEqual(
+ (await summaryOf('fixture-model-061')).runs.map((run) => run.held_back),
+ ['aborted_attempt']
+ );
+ },
+ { clock: () => now }
+ );
+});
+
+test('working-memory calibration: seeded model states and device scenarios', async () => {
+ await withRepresentativeBackend(async (backend) => {
+ const summaryOf = (key) => getJson(backend, `/api/v2/models/i/${key}/working_memory/summary`);
+ const states = async (key) => (await summaryOf(key)).lines.map((line) => line.state);
+
+ assert.deepEqual(await states('fixture-model-006'), ['in_use', 'in_use']);
+ assert.deepEqual(await states('fixture-model-011'), ['stale', 'stale']);
+ assert.deepEqual(await states('fixture-model-016'), ['unusable', 'unusable']);
+ assert.deepEqual(await states('fixture-model-036'), ['insufficient']);
+ // Opt in: a running attempt, which holds the GPU. Another attempt, of any model, is refused for it; a request
+ // without an attempt is not.
+ assert.deepEqual((await summaryOf('fixture-model-021')).runs, []);
+ await getJson(backend, '/__faults', {
+ body: JSON.stringify({ runningCalibration: 'fixture-model-021' }),
+ method: 'POST',
+ });
+ assert.ok((await summaryOf('fixture-model-021')).runs.some((run) => run.status === 'running'));
+ const calibrateOther = (attempt) =>
+ fetch(`${backend.origin}/api/v2/models/i/fixture-model-001/working_memory/calibrate`, {
+ body: JSON.stringify({ ...attempt, data: [], graph: { edges: [], id: 'x', nodes: {} }, graph_models: {} }),
+ method: 'POST',
+ });
+ const busy = await calibrateOther({ attempt_id: 'mine', attempt_steps: 1 });
+ assert.deepEqual([busy.status, (await busy.json()).detail.code], [409, 'calibration_running']);
+ assert.equal((await calibrateOther({})).status, 201);
+ const failed = await summaryOf('fixture-model-026');
+ // The failed decode left an invalid window, which point_count counts like the server's.
+ assert.deepEqual(
+ failed.runs.filter((run) => run.status === 'failed').map((run) => run.point_count),
+ [1]
+ );
+ assert.ok(failed.runs.every((run) => run.held_back === null));
+ assert.deepEqual(
+ failed.lines.map((line) => line.state),
+ ['in_use', 'in_use']
+ );
+ assert.equal((await getJson(backend, '/api/v2/models/i/fixture-model-031/working_memory/plan')).supported, false);
+
+ // A model never calibrated itself shows the lines another model measured, which name both sides.
+ const shared = (await summaryOf('fixture-model-041')).lines;
+ assert.deepEqual(
+ shared.map((line) => [line.state, line.own_windows, line.measured_by.map((entry) => entry.model_key)]),
+ [
+ ['in_use', 0, ['fixture-model-006']],
+ ['in_use', 0, ['fixture-model-006']],
+ ]
+ );
+ const carrier = (await summaryOf('fixture-model-006')).lines[0];
+ assert.equal(carrier.own_windows, 9);
+ assert.deepEqual(carrier.measured_by, [{ model_key: 'fixture-model-006', name: 'Fixture Model 006', windows: 9 }]);
+ assert.equal((await fetch(`${backend.origin}/api/v2/models/i/no-such-model/working_memory/summary`)).status, 404);
+
+ // A warm 9060 XT: the largest fp32 size measured fragmentation and is left out of the fit and its range; an fp16
+ // size with one clean window among partially resident ones still counts, on that window alone.
+ const [fp16, fp32] = (await summaryOf('fixture-model-046')).lines;
+ const sizesOf = (line) => line.sizes.map((size) => [size.width, size.counted, size.excluded_reason, size.windows]);
+ assert.deepEqual(sizesOf(fp32), [
+ [576, true, null, 3],
+ [832, true, null, 3],
+ [1216, false, 'fragmented', 3],
+ ]);
+ assert.deepEqual(fp32.measured_range, { max_pixels: 832 * 832, min_pixels: 576 * 576 });
+ // Above that range the server prices the larger of the user line and the shipped value; here the line is lower.
+ const [, within, above] = fp32.sizes;
+ assert.equal(above.user_bytes, above.shipped_bytes);
+ assert.ok(within.user_bytes < within.shipped_bytes);
+ assert.equal(fp32.own_windows, 6);
+ assert.equal(fp32.state, 'in_use');
+ assert.deepEqual(sizesOf(fp16), [
+ [576, true, null, 3],
+ [832, true, null, 1],
+ [1216, true, null, 3],
+ ]);
+ assert.equal(fp16.own_windows, 7);
+
+ // Opt in: a model whose later steps failed as they were admitted, its record having changed after queuing.
+ await getJson(backend, '/__faults', {
+ body: JSON.stringify({ modelChangedCalibration: 'fixture-model-056' }),
+ method: 'POST',
+ });
+ const changed = await summaryOf('fixture-model-056');
+ const failedRuns = changed.runs.filter((run) => run.status === 'failed');
+ assert.equal(failedRuns.length, changed.runs.length - 4);
+ assert.ok(failedRuns.every((run) => run.error_code === 'model_changed'));
+ assert.match(failedRuns[0].error, /^Fixture Model 056 changed after this calibration was planned/);
+ const statusRun = (await getJson(backend, '/api/v2/models/working_memory/status')).device_classes[0].runs.find(
+ (run) => run.run_id === failedRuns[0].run_id
+ );
+ assert.equal(statusRun.error_code, 'model_changed');
+ // A changed model aborts the whole attempt: its completed steps feed no fit either.
+ assert.ok(changed.runs.every((run) => run.held_back === 'aborted_attempt'));
+ assert.ok(changed.lines.every((line) => line.sizes.every((size) => size.excluded_reason === 'aborted_attempt')));
+
+ // Opt in: a model whose attempt Stop aborted after four steps, whose windows never count.
+ await getJson(backend, '/__faults', {
+ body: JSON.stringify({ stoppedCalibration: 'fixture-model-051' }),
+ method: 'POST',
+ });
+ const stopped = await summaryOf('fixture-model-051');
+ assert.ok(stopped.runs.every((run) => run.held_back === 'aborted_attempt'));
+ assert.equal(stopped.runs.filter((run) => run.point_count > 0).length, 4);
+ assert.deepEqual(
+ stopped.lines.map((line) => [line.state, line.sizes.map((size) => size.excluded_reason)]),
+ [['insufficient', ['aborted_attempt', 'aborted_attempt']]]
+ );
+ const notMain = await fetch(`${backend.origin}/__faults`, {
+ body: JSON.stringify({ stoppedCalibration: 'no-such-model' }),
+ method: 'POST',
+ });
+ assert.equal(notMain.status, 400);
+
+ await getJson(backend, '/__faults', { body: JSON.stringify({ workingMemory: 'notVerified' }), method: 'POST' });
+ assert.equal((await summaryOf('fixture-model-006')).measurement_verified, false);
+
+ await getJson(backend, '/__faults', { body: JSON.stringify({ workingMemory: 'multiGpu' }), method: 'POST' });
+ const status = await getJson(backend, '/api/v2/models/working_memory/status');
+ assert.equal(status.available, false);
+ assert.match(status.unavailable_reason, /exactly one generation device/);
+ assert.equal(
+ (await fetch(`${backend.origin}/api/v2/models/i/fixture-model-001/working_memory/summary`)).status,
+ 409
+ );
+
+ await getJson(backend, '/__faults', { body: JSON.stringify({ workingMemory: 'error' }), method: 'POST' });
+ assert.equal((await fetch(`${backend.origin}/api/v2/models/i/fixture-model-001/working_memory/plan`)).status, 503);
+
+ const unknown = await fetch(`${backend.origin}/__faults`, {
+ body: JSON.stringify({ workingMemory: 'sideways' }),
+ method: 'POST',
+ });
+ assert.equal(unknown.status, 400);
+ });
+});
+
test('image storage: the layout is patched alone and the move count follows it', async () => {
await withRepresentativeBackend(async (backend) => {
assert.deepEqual(await getJson(backend, '/api/v1/image_moves/status'), {
diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjs
index 8ddbf05ae9..09102abbc9 100644
--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs
+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs
@@ -14,6 +14,7 @@ import {
MOCK_BACKEND_FIXED_EPOCH,
MODEL_SEED_SETS,
} from './mock-backend-fixtures.mjs';
+import { createWorkingMemoryMock, WORKING_MEMORY_SCENARIOS } from './mock-working-memory.mjs';
/** The canvas schema every mock project declares; the real server keeps the same floor per record. */
const DEFAULT_CANVAS_SCHEMA_VERSION = 3;
@@ -86,6 +87,10 @@ const ARCHITECTURE_CAPABILITIES = JSON.parse(
* already false). Like the real service, Start Move is refused while any queue item is pending or in progress (the
* representative profile seeds some; clear the queue first). While a move runs or a job awaits recovery, image files,
* media mutations and enqueueing answer 409 like the real maintenance guard; listings stay readable.
+ * `workingMemory` selects a calibration device scenario, and `stoppedCalibration: <main model key>` gives that model an
+ * attempt Stop aborted, `runningCalibration: <main model key>` one still running, which holds the GPU,
+ * `modelChangedCalibration: <main model key>` one whose steps failed for a changed model (see
+ * mock-working-memory.mjs).
*/
const CAPABILITY_FAULTS = new Set(['ok', 'error', 'empty']);
const INTERMEDIATES_CALLERS = new Set(['admin', 'user', 'multiuser-admin']);
@@ -97,7 +102,12 @@ const IMAGE_STORAGE_LAYOUTS = new Set(['flat', 'date', 'type', 'hash']);
/** Status reads a running move or recovery takes to finish, so polling clients observe it in progress. */
const IMAGE_MOVE_TICKS = 2;
-const createFaults = () => ({ capabilities: 'ok', imageMoves: 'idle', intermediatesCaller: 'admin' });
+const createFaults = () => ({
+ capabilities: 'ok',
+ imageMoves: 'idle',
+ intermediatesCaller: 'admin',
+ workingMemory: 'ok',
+});
/**
* Every fixture image is stored flat, so the move count is the whole library whenever the configured layout
@@ -449,8 +459,10 @@ const sortedWildcards = (state) =>
const wildcardNameTaken = (state, name, exceptId = null) =>
[...state.wildcards.values()].some((wildcard) => wildcard.name === name && wildcard.id !== exceptId);
-const createState = (profile) => {
+/** `clock` is the working-memory mock's time source (see mock-working-memory.mjs). */
+const createState = (profile, clock) => {
const fixture = assertMockBackendFixture(createMockBackendFixture(profile));
+ const models = new Map(fixture.models.map((model) => [model.key, clone(model)]));
return {
boardMembers: new Map(),
@@ -465,7 +477,7 @@ const createState = (profile) => {
externalProviders: createExternalProviderConfigs(fixture.models),
images: new Map(fixture.images.map((image) => [image.image_name, clone(image)])),
imageStorage: createImageStorage(),
- models: new Map(fixture.models.map((model) => [model.key, clone(model)])),
+ models,
/** What re-identify fills in per model key; only `POST /__models` seeds entries. */
modelProbes: new Map(),
mutationClock: 0,
@@ -487,6 +499,7 @@ const createState = (profile) => {
videos: new Map(fixture.videos.map((video) => [video.video_name, clone(video)])),
wildcards: createWildcards(profile === 'empty' ? 0 : SEEDED_WILDCARD_NAMES.length),
workflows: new Map(fixture.workflows.map((workflow) => [workflow.workflow_id, clone(workflow)])),
+ workingMemory: createWorkingMemoryMock(fixture.models, { clock, currentModel: (key) => models.get(key) }),
nextWorkflowNumber: fixture.workflows.length + 1,
/** Custom workflow thumbnails by workflow id; the version stands in for the server's cache-busting query. */
workflowThumbnails: new Map(),
@@ -1148,9 +1161,9 @@ const parseByteRange = (value, size) => {
: null;
};
-export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
+export const startMockBackend = async (port, { clock = Date.now, profile = 'empty' } = {}) => {
const initialProfile = assertMockBackendProfileName(profile);
- let state = createState(initialProfile);
+ let state = createState(initialProfile, clock);
let faults = createFaults();
const server = createServer(async (request, response) => {
@@ -1169,7 +1182,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
const requestedProfile = url.searchParams.get('profile') ?? body.profile ?? initialProfile;
try {
- state = createState(assertMockBackendProfileName(requestedProfile));
+ state = createState(assertMockBackendProfileName(requestedProfile), clock);
} catch (error) {
return json(400, { detail: error instanceof Error ? error.message : String(error) });
}
@@ -1230,6 +1243,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
const body = await readJsonBody(request);
const requested = url.searchParams.get('capabilities') ?? body.capabilities;
const caller = url.searchParams.get('intermediatesCaller') ?? body.intermediatesCaller;
+ const workingMemory = url.searchParams.get('workingMemory') ?? body.workingMemory;
const imageMoves = url.searchParams.get('imageMoves') ?? body.imageMoves;
if (body.sharedBoards === true && !state.boards.has(SHARED_BOARD_FIXTURES[0].board_id)) {
@@ -1252,6 +1266,35 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
faults.intermediatesCaller = caller;
}
+ if (workingMemory !== undefined && workingMemory !== null) {
+ if (!WORKING_MEMORY_SCENARIOS.has(workingMemory)) {
+ return json(400, { detail: `Unknown working-memory scenario: ${String(workingMemory)}` });
+ }
+
+ faults.workingMemory = workingMemory;
+ }
+
+ if (
+ body.modelChangedCalibration !== undefined &&
+ !state.workingMemory.seedModelChanged(body.modelChangedCalibration)
+ ) {
+ return json(400, {
+ detail: `No main model to seed a changed-model calibration on: ${String(body.modelChangedCalibration)}`,
+ });
+ }
+
+ if (body.runningCalibration !== undefined && !state.workingMemory.seedRunning(body.runningCalibration)) {
+ return json(400, {
+ detail: `No main model to seed a running calibration on: ${String(body.runningCalibration)}`,
+ });
+ }
+
+ if (body.stoppedCalibration !== undefined && !state.workingMemory.seedStopped(body.stoppedCalibration)) {
+ return json(400, {
+ detail: `No main model to seed a stopped calibration on: ${String(body.stoppedCalibration)}`,
+ });
+ }
+
if (imageMoves !== undefined && imageMoves !== null) {
if (!IMAGE_MOVE_FAULTS.has(imageMoves)) {
return json(400, { detail: `Unknown image moves fault: ${String(imageMoves)}` });
@@ -2054,6 +2097,23 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, { item_ids: returned, total_count: returned.length });
}
+ if (action === 'cancel_all' && method === 'PUT') {
+ const originPrefix = url.searchParams.get('origin_prefix');
+
+ // Calibration items live with the working-memory mock; see mock-working-memory.mjs.
+ if (originPrefix !== null && state.workingMemory.isCalibrationPrefix(originPrefix)) {
+ return json(200, { canceled: state.workingMemory.cancelByOrigin(originPrefix) });
+ }
+
+ let canceled = 0;
+ for (const item of scopedItems) {
+ if (item.status === 'pending' || item.status === 'in_progress') {
+ item.status = 'canceled';
+ canceled += 1;
+ }
+ }
+ return json(200, { canceled });
+ }
if (action === 'clear' && method === 'PUT') {
state.queueItems.clear();
return json(200, { deleted: true });
@@ -2137,6 +2197,15 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {
return json(200, null);
}
+ if (path.startsWith('/api/v2/models/') && path.includes('working_memory')) {
+ const body = method === 'POST' ? await readJsonBody(request) : null;
+ const answer = state.workingMemory.handle({ body, method, path, scenario: faults.workingMemory });
+
+ if (answer) {
+ return json(answer.status, answer.body);
+ }
+ }
+
if (method === 'GET' && path === '/api/v2/models/stats') {
return json(200, null);
}
diff --git a/invokeai/frontend/webv2/scripts/mock-working-memory.mjs b/invokeai/frontend/webv2/scripts/mock-working-memory.mjs
new file mode 100644
index 0000000000..e96dfc39d8
--- /dev/null
+++ b/invokeai/frontend/webv2/scripts/mock-working-memory.mjs
@@ -0,0 +1,900 @@
+/**
+ * Working-memory calibration for the mock backend: plans, summaries, the device status, calibration runs and resets
+ * (`/api/v2/models/.../working_memory`), and cancelling a run's items by origin. The mock has no Socket.IO, so a run
+ * advances when a client reads the model's summary: a read at least a second after the last step finishes the running
+ * item and starts the next, which a section polling every two seconds turns into visible progress.
+ *
+ * Main models (`fixture-model-001`, `-006`, ...) each show one state, by key (`MODEL_SCENARIOS`); every other main model is never
+ * calibrated, and VAEs are unsupported. `SHARED_LINES` pairs models whose decode lines pool their measurements, so one
+ * of them shows lines only the other measured. `fixture-model-046` follows a warm RX 9060 XT: its largest fp32 size
+ * measured allocator fragmentation and is not counted, and two of three windows at one fp16 size ran partially resident,
+ * which leaves that size counted on the third. `POST /__faults` with `workingMemory` selects a device scenario instead,
+ * with `stoppedCalibration: <model key>` replaces that main model's runs with an attempt Stop aborted, with
+ * `runningCalibration: <model key>` with one still running, which holds the GPU, and with
+ * `modelChangedCalibration: <model key>` with one whose later steps failed because the model changed after queuing.
+ * A calibrate request with an attempt is refused (409, coded) while another attempt runs on the GPU or is open (between
+ * its steps, short of them, not aborted, active within the last two minutes of `clock`), for a later step once another
+ * run was created since the attempt's first (`calibration_interleaved`), and for a graph naming a model whose hash,
+ * base, type, format or variant changed since it compiled, or that was removed. Like the server, it takes a request only
+ * with `graph_models` stating every model the graph names and no other (422).
+ * Calibration items live here rather than in the fixture queue, so profile counts stay fixed. Tests pass their own
+ * `clock` to advance runs without waiting.
+ */
+
+export const WORKING_MEMORY_SCENARIOS = new Set(['ok', 'multiGpu', 'noGpu', 'storeUnusable', 'error', 'notVerified']);
+
+const ORIGIN_PREFIX = 'invokeai:wm-calibration:';
+const ATTEMPT_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
+const DEVICE_CLASS = {
+ arch: 'sm_89',
+ backend: 'cuda',
+ id: '0123456789abcdef',
+ name: 'NVIDIA GeForce RTX 4090',
+ total_mib: 24_564,
+ vendor: 'nvidia',
+};
+const ENV_ID = 'fedcba9876543210';
+const OLD_ENV_ID = '00ff00ff00ff00ff';
+const MIB = 2 ** 20;
+const SIDES = [768, 1088, 1536];
+const DTYPES = ['fp16', 'fp32'];
+const REPETITIONS = { measured: 2, warm_up: 1 };
+const ENCODE_NOT_COVERED =
+ 'encode: text-to-image runs no encode, so image-to-image and inpainting encodes keep the shipped values';
+const SEEDED_AT = Date.parse('2025-12-01T10:00:00.000Z');
+/** The server's problem for a line that only aborted attempts measured. */
+const ABORTED_LINE_PROBLEM =
+ 'Stop or an interrupted submission discarded the measurements of this line: its windows come from aborted ' +
+ 'attempts, which never count. Calibrate again to measure it.';
+/** The server's bounds on an attempt's step count. */
+const MAX_ATTEMPT_STEPS = 256;
+/** A run's items advance at most this often, so a section that refetches on every queued step still shows progress. */
+const STEP_MS = 1_000;
+
+/** What each seeded main model shows, by key. */
+const MODEL_SCENARIOS = {
+ 'fixture-model-006': 'completed',
+ 'fixture-model-011': 'stale',
+ 'fixture-model-016': 'unusable',
+ 'fixture-model-026': 'failed',
+ 'fixture-model-031': 'unsupported',
+ 'fixture-model-036': 'insufficient',
+ 'fixture-model-046': 'fragmented',
+};
+
+/** The sizes the `fragmented` scenario measured, as the 9060 XT plan picked them. */
+const FRAGMENTED_SIDES = [576, 832, 1216];
+
+/** Why a seeded window of the `fragmented` scenario is excluded from the fit, by its step; undefined when it counts. */
+const excludedIn = (scenario, step, repetition) => {
+ if (scenario !== 'fragmented') {
+ return undefined;
+ }
+
+ if (step.line === 'decode_fp32' && step.width === 1216) {
+ return 'fragmented';
+ }
+
+ return step.line === 'decode_fp16' && step.width === 832 && repetition < 2 ? 'partial_residency' : undefined;
+};
+
+/** Models whose lines pool both models' measurements; the first is never calibrated itself. */
+const SHARED_LINES = [['fixture-model-041', 'fixture-model-006']];
+
+const partnersOf = (modelKey) =>
+ SHARED_LINES.flatMap(([left, right]) => (left === modelKey ? [right] : right === modelKey ? [left] : []));
+
+/** A plausible decode demand: the VAE's weights plus a per-pixel activation cost, twice that in fp32. */
+const demandOf = (pixels, dtype) => Math.round((dtype === 'fp32' ? 2 : 1) * (420 * MIB + pixels * 1_100));
+
+const casesOf = (model) =>
+ DTYPES.flatMap((dtype) =>
+ (MODEL_SCENARIOS[model.key] === 'fragmented' ? FRAGMENTED_SIDES : SIDES).map((side) => ({
+ components: {},
+ estimator: 'sd_vae_decode',
+ height: side,
+ id: `sd_vae_decode-decode-${dtype}-${side}x${side}`,
+ line: `decode_${dtype}`,
+ mode: 'txt2img',
+ model_key: model.key,
+ negative_prompt: '',
+ positive_prompt: 'a mountain lake at dawn, detailed photograph',
+ seed: 1,
+ settings: { vaePrecision: dtype },
+ steps: 2,
+ width: side,
+ }))
+ );
+
+const stepsOf = (cases) =>
+ DTYPES.flatMap((dtype) =>
+ cases
+ .filter((item) => item.line === `decode_${dtype}`)
+ .flatMap((item) => Array.from({ length: REPETITIONS.warm_up + REPETITIONS.measured }, () => item))
+ );
+
+/** The server's refusal while another attempt runs on the GPU: one attempt per device class at a time. */
+const RUNNING_REFUSAL = {
+ code: 'calibration_running',
+ message:
+ 'Another calibration is still running on this GPU. Wait until it has finished, or stop it, then calibrate again.',
+};
+
+/** The server's refusal of a later step once another calibration ran on the GPU since the attempt began. */
+const INTERLEAVED_REFUSAL = {
+ code: 'calibration_interleaved',
+ message:
+ 'Another calibration ran on this GPU after this calibration started, so its measurements can no longer be combined. Calibrate again.',
+};
+
+/** How long an attempt between its steps holds the GPU after its last activity, as the server waits. */
+const ATTEMPT_IDLE_GRACE_MS = 120_000;
+
+/** As webv2's `compiledModelIdentities` reads one: string key, hash, name, base and type; no submodel type but a string. */
+const isModelIdentifier = (value) =>
+ ['key', 'hash', 'name', 'base', 'type'].every((field) => typeof value[field] === 'string') &&
+ (value.submodel_type === undefined || value.submodel_type === null || typeof value.submodel_type === 'string');
+
+/** Every fact of a `graph_models` entry is stated; these three are never null, as the server requires. */
+const isStatedIdentity = (identity) =>
+ identity !== null &&
+ typeof identity === 'object' &&
+ IDENTITY_FACTS.every((fact) => fact in identity) &&
+ ['hash', 'base', 'type'].every((fact) => typeof identity[fact] === 'string');
+
+/** The model identifiers a graph names, as the server finds them: in the nodes' fields and nested in them. */
+const modelIdentifiersOf = (graph) => {
+ const found = [];
+ const visit = (value) => {
+ if (Array.isArray(value)) {
+ value.forEach(visit);
+ } else if (value !== null && typeof value === 'object') {
+ if (isModelIdentifier(value)) {
+ found.push(value);
+ } else {
+ Object.values(value).forEach(visit);
+ }
+ }
+ };
+
+ for (const node of Object.values(graph.nodes ?? {})) {
+ if (node !== null && typeof node === 'object') {
+ Object.values(node).forEach(visit);
+ }
+ }
+ return found;
+};
+
+const IDENTITY_FACTS = ['hash', 'base', 'type', 'format', 'variant'];
+
+/** Why `graphModels` does not state exactly the graph's models, every fact of each, or null when it does. */
+const graphModelsProblem = (graph, graphModels) => {
+ if (graphModels === null || typeof graphModels !== 'object' || Array.isArray(graphModels)) {
+ return 'graph_models is required: the identity of every model the graph names.';
+ }
+
+ const named = new Set(modelIdentifiersOf(graph).map((identifier) => identifier.key));
+ const stated = Object.keys(graphModels);
+ const problems = [
+ ...[...named]
+ .filter((key) => !(key in graphModels))
+ .map((key) => `the graph names ${key}, which graph_models lacks`),
+ ...stated.filter((key) => !named.has(key)).map((key) => `graph_models names ${key}, which the graph does not`),
+ ...stated
+ .filter((key) => !isStatedIdentity(graphModels[key]))
+ .map((key) => `graph_models[${key}] does not state every fact, or states a null hash, base or type`),
+ ];
+
+ return problems.length > 0
+ ? `graph_models must state every model the graph names, and only those: ${problems.join('; ')}`
+ : null;
+};
+
+/**
+ * `currentModel` reads a model's record as it is now, so a graph compiled over an older record is refused as the
+ * server refuses it; the fixture's records stand in without it.
+ */
+export const createWorkingMemoryMock = (models, { clock = Date.now, currentModel } = {}) => {
+ const mainModels = models.filter((model) => model.type === 'main');
+ const byKey = new Map(models.map((model) => [model.key, model]));
+ /** Runs by model key, oldest first: `{ run_id, created_at, items: [{ item_id, case, status, error }] }`. */
+ const runs = new Map();
+ /** Measured points by model key: `{ line, width, height, bytes, env_id }`. */
+ const points = new Map();
+ /** Run ids by idempotency key, so a resent request returns the run it created. */
+ const receipts = new Map();
+ let nextRunNumber = 1;
+ let nextItemId = 900_000;
+ let createdCount = 0;
+ let lastAdvanceAt = 0;
+
+ const now = () => new Date(SEEDED_AT + 86_400_000 * 30 + createdCount++ * 1_000).toISOString();
+
+ /**
+ * `excluded` names why the fit leaves the window out: `fragmented` or `partial_residency`. A window of an aborted
+ * attempt is left out as well, judged when lines are read (`heldBack`).
+ */
+ const addPoint = (modelKey, run, item, envId = ENV_ID, excluded = undefined) => {
+ const dtype = item.case.line.split('_').at(-1);
+ const list = points.get(modelKey) ?? [];
+ const demand = demandOf(item.case.width * item.case.height, dtype);
+
+ list.push({
+ // A fragmented allocator reserves well beyond what the decode needs.
+ bytes: excluded === 'fragmented' ? Math.round(demand * 1.4) : demand,
+ env_id: envId,
+ excluded,
+ height: item.case.height,
+ line: item.case.line,
+ run_id: run.run_id,
+ width: item.case.width,
+ });
+ points.set(modelKey, list);
+ };
+
+ const createRun = (modelKey, steps, createdAt, attemptId, attemptSteps) => {
+ const run = {
+ attempt_id: attemptId,
+ attempt_steps: attemptSteps,
+ created_at: createdAt,
+ items: steps.map((step) => ({ case: step, error: null, item_id: nextItemId++, status: 'pending' })),
+ // When the run last did something, on `clock`: its creation, then each item that settles.
+ lastActivityAt: clock(),
+ run_id: `mock-wm-run-${String(nextRunNumber++).padStart(4, '0')}`,
+ };
+ const list = runs.get(modelKey) ?? [];
+
+ list.push(run);
+ runs.set(modelKey, list);
+
+ return run;
+ };
+
+ /** Seeds one model's state: settled runs one per step, two seconds apart, a month before now. */
+ const seed = (model, scenario) => {
+ const cases = casesOf(model);
+ const steps = scenario === 'insufficient' ? stepsOf(cases).slice(0, 3) : stepsOf(cases);
+ const settledRuns = steps.map((step, index) =>
+ createRun(model.key, [step], new Date(SEEDED_AT + index * 2_000).toISOString(), `seed-${model.key}`, steps.length)
+ );
+
+ settledRuns.forEach((run, index) => {
+ const [item] = run.items;
+ const isRunning = scenario === 'running' && index >= 4;
+
+ // Seeded a month ago: a short seeded attempt is long abandoned, never open.
+ run.lastActivityAt = Number.NEGATIVE_INFINITY;
+
+ if (scenario === 'failed' && index === 7) {
+ item.status = 'failed';
+ item.error = 'OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB';
+ } else if (scenario === 'stopped' && index >= 4) {
+ // Stop canceled what the queue still held: the attempt is aborted, the four finished steps included.
+ item.status = 'canceled';
+ } else if (scenario === 'modelChanged' && index >= 4) {
+ // The record changed after queuing: the server failed the later items as it admitted them.
+ item.status = 'failed';
+ item.errorCode = 'model_changed';
+ item.error = `${model.name} changed after this calibration was planned (hash). Calibrate again.`;
+ } else if (isRunning) {
+ item.status = index === 4 ? 'in_progress' : 'pending';
+ } else {
+ const repetition = index % (REPETITIONS.warm_up + REPETITIONS.measured);
+
+ item.status = 'completed';
+ addPoint(
+ model.key,
+ run,
+ item,
+ scenario === 'unusable' ? OLD_ENV_ID : ENV_ID,
+ excludedIn(scenario, item.case, repetition)
+ );
+ }
+ });
+ };
+
+ const reset = () => {
+ runs.clear();
+ points.clear();
+ receipts.clear();
+ nextRunNumber = 1;
+ nextItemId = 900_000;
+ createdCount = 0;
+ lastAdvanceAt = 0;
+
+ for (const model of mainModels) {
+ const scenario = MODEL_SCENARIOS[model.key];
+
+ if (scenario && scenario !== 'unsupported') {
+ seed(model, scenario);
+ }
+ }
+ };
+
+ reset();
+
+ /**
+ * Replaces a main model's runs with an attempt stopped after four of its steps, so a browser check can review that
+ * state (`POST /__faults` with `stoppedCalibration`); false for a key that names no main model. `reset` drops it.
+ */
+ const seedStopped = (modelKey) => seedOpted(modelKey, 'stopped');
+
+ /**
+ * Replaces a main model's runs with an attempt still running, which holds the GPU (`POST /__faults` with
+ * `runningCalibration`); false for a key that names no main model.
+ */
+ const seedRunning = (modelKey) => seedOpted(modelKey, 'running');
+
+ /**
+ * Replaces a main model's runs with an attempt whose later steps failed because the model's record changed after
+ * they were queued (`POST /__faults` with `modelChangedCalibration`); false for a key that names no main model.
+ */
+ const seedModelChanged = (modelKey) => seedOpted(modelKey, 'modelChanged');
+
+ const seedOpted = (modelKey, scenario) => {
+ const model = mainModels.find((candidate) => candidate.key === modelKey);
+
+ if (!model) {
+ return false;
+ }
+
+ runs.delete(model.key);
+ points.delete(model.key);
+ seed(model, scenario);
+ return true;
+ };
+
+ const runStatus = (run, pointCount) => {
+ const statuses = run.items.map((item) => item.status);
+
+ if (statuses.some((status) => status === 'pending' || status === 'in_progress')) {
+ return { error: null, error_code: null, status: 'running' };
+ }
+
+ const failed = run.items.find((item) => item.status === 'failed');
+
+ if (failed) {
+ return { error: failed.error, error_code: failed.errorCode ?? null, status: 'failed' };
+ }
+
+ if (statuses.every((status) => status === 'completed')) {
+ return { error: null, error_code: null, status: 'completed' };
+ }
+
+ return { error: null, error_code: null, status: pointCount > 0 ? 'partial' : 'canceled' };
+ };
+
+ /** The windows that count: those of the run's completed items. */
+ const pointCountOf = (run) => run.items.filter((item) => item.status === 'completed').length;
+ /**
+ * The windows the run stored, as `point_count` reports them: the valid ones, plus the invalid window a decode
+ * leaves that failed or was canceled while it ran.
+ */
+ const storedPointsOf = (run) =>
+ pointCountOf(run) + run.items.filter((item) => item.status === 'failed' || item.interrupted).length;
+
+ /**
+ * Why no window of a run feeds a fit, by run id, judged per attempt as the server does: `running` while a run of it
+ * is unsettled; `aborted_attempt` once none is and a run of it ended canceled (Stop, a queue clear), failed because
+ * the model changed after it was planned, or it holds fewer runs than it planned (Stop, a failed submission). Any
+ * other failed run ends that run, not the attempt; a run without an attempt is never aborted.
+ */
+ const statusesOf = (attempt) => attempt.map((run) => runStatus(run, pointCountOf(run)).status);
+ const isShort = (attempt) => attempt.length < Math.max(...attempt.map((run) => run.attempt_steps ?? 0));
+ /** A run of the attempt ended canceled (Stop, a queue clear) or failed because the model changed. */
+ const endedEarly = (attempt) =>
+ statusesOf(attempt).some((status) => status === 'canceled' || status === 'partial') ||
+ attempt.some((run) => run.items.some((item) => item.status === 'failed' && item.errorCode === 'model_changed'));
+ /**
+ * Whether another attempt than `attemptId` holds the GPU, as the server's `_attempt_blocks` judges it: a run of it is
+ * running, or it is open: between its steps, short of them, nothing ended it early, and active within the grace.
+ */
+ const attemptBlocks = (attemptId) =>
+ [
+ ...Map.groupBy(
+ [...runs.values()].flat().filter((run) => run.attempt_id !== null && run.attempt_id !== attemptId),
+ (run) => run.attempt_id
+ ).values(),
+ ].some(
+ (attempt) =>
+ statusesOf(attempt).includes('running') ||
+ (isShort(attempt) &&
+ !endedEarly(attempt) &&
+ clock() - Math.max(...attempt.map((run) => run.lastActivityAt)) <= ATTEMPT_IDLE_GRACE_MS)
+ );
+
+ const heldBack = () => {
+ const reasons = new Map();
+
+ for (const list of runs.values()) {
+ const attempts = Map.groupBy(list, (run) => run.attempt_id ?? `run:${run.run_id}`);
+
+ for (const attempt of attempts.values()) {
+ const aborted = attempt[0].attempt_id !== null && (isShort(attempt) || endedEarly(attempt));
+ const reason = statusesOf(attempt).includes('running') ? 'running' : aborted ? 'aborted_attempt' : null;
+
+ for (const run of attempt) {
+ reasons.set(run.run_id, reason);
+ }
+ }
+ }
+
+ return reasons;
+ };
+
+ const modelRuns = (modelKey) => {
+ const reasons = heldBack();
+
+ return (runs.get(modelKey) ?? []).map((run) => {
+ const pointCount = pointCountOf(run);
+
+ return {
+ attempt_id: run.attempt_id,
+ attempt_steps: run.attempt_steps,
+ created_at: run.created_at,
+ held_back: reasons.get(run.run_id) ?? null,
+ point_count: storedPointsOf(run),
+ run_id: run.run_id,
+ ...runStatus(run, pointCount),
+ };
+ });
+ };
+
+ /** Finishes the running item of the model's oldest unsettled run and starts the next one. */
+ const advance = (modelKey) => {
+ if (clock() - lastAdvanceAt < STEP_MS) {
+ return;
+ }
+ lastAdvanceAt = clock();
+
+ const items = (runs.get(modelKey) ?? []).flatMap((run) => run.items.map((item) => ({ item, run })));
+ const running = items.find(({ item }) => item.status === 'in_progress');
+
+ if (running) {
+ running.item.status = 'completed';
+ running.run.lastActivityAt = clock();
+ addPoint(modelKey, running.run, running.item);
+ }
+
+ const next = items.find(({ item }) => item.status === 'pending');
+
+ if (next) {
+ next.item.status = 'in_progress';
+ }
+ };
+
+ /**
+ * A model's lines: its own points, plus its partners' points in the current environment, which the server pools
+ * the same way. A line only partners measured appears with `own_windows` 0.
+ */
+ const linesOf = (modelKey, scenario) => {
+ const reasons = heldBack();
+ // A window of an aborted attempt never counts, whatever else it measured.
+ const judged = (point, key) => ({
+ ...point,
+ excluded: reasons.get(point.run_id) === 'aborted_attempt' ? 'aborted_attempt' : point.excluded,
+ model_key: key,
+ });
+ const own = (points.get(modelKey) ?? []).map((point) => judged(point, modelKey));
+ const shared = partnersOf(modelKey).flatMap((key) =>
+ (points.get(key) ?? []).filter((point) => point.env_id === ENV_ID).map((point) => judged(point, key))
+ );
+
+ return DTYPES.flatMap((dtype) => {
+ const line = `decode_${dtype}`;
+ const ownPoints = own.filter((point) => point.line === line);
+ const envId = ownPoints.at(-1)?.env_id ?? ENV_ID;
+ const linePoints = [...ownPoints, ...(envId === ENV_ID ? shared.filter((point) => point.line === line) : [])];
+
+ if (linePoints.length === 0) {
+ return [];
+ }
+
+ // Only counted windows feed the fit; a size counts while any of its windows does.
+ const countedPoints = linePoints.filter((point) => point.excluded === undefined);
+ const sides = [...new Set(linePoints.map((point) => point.width))].sort((left, right) => left - right);
+ const countedSides = new Set(countedPoints.map((point) => point.width));
+ const fitted = countedSides.size >= 2;
+ const maxCounted = Math.max(...countedSides);
+ const sizes = sides.map((side) => {
+ const counted = countedSides.has(side);
+ const atSide = (counted ? countedPoints : linePoints).filter((point) => point.width === side);
+ const largest = atSide.reduce((left, right) => (right.bytes > left.bytes ? right : left));
+ const pixels = side * side;
+ const demand = demandOf(pixels, dtype);
+ const shipped = Math.round(demand * 1.35);
+ const line = Math.round(demand * 1.05);
+
+ const reasonsAtSide = new Set(atSide.map((point) => point.excluded));
+
+ return {
+ counted,
+ // As the server names a size all of whose windows are left out: aborted where that is the only reason.
+ excluded_reason: counted
+ ? null
+ : reasonsAtSide.size === 1 && reasonsAtSide.has('aborted_attempt')
+ ? 'aborted_attempt'
+ : reasonsAtSide.has('fragmented')
+ ? 'fragmented'
+ : 'partial_residency',
+ height: side,
+ measured_bytes: largest.bytes,
+ pixels,
+ shipped_bytes: shipped,
+ // Like the server's resolve: above the measured range the larger of the user line and the shipped value.
+ user_bytes: fitted && envId === ENV_ID ? (side > maxCounted ? Math.max(line, shipped) : line) : null,
+ width: side,
+ windows: atSide.length,
+ };
+ });
+ const state =
+ envId !== ENV_ID ? 'unusable' : !fitted ? 'insufficient' : scenario === 'stale' ? 'stale' : 'in_use';
+ const measuredBy = [...new Set(countedPoints.map((point) => point.model_key))]
+ .map((key) => ({
+ model_key: key,
+ name: byKey.get(key)?.name ?? null,
+ windows: countedPoints.filter((point) => point.model_key === key).length,
+ }))
+ .sort((left, right) => left.name.localeCompare(right.name) || left.model_key.localeCompare(right.model_key));
+
+ return [
+ {
+ base_bytes: fitted ? 420 * MIB : null,
+ carrier: 'sd_vae_decode',
+ changed_facts: state === 'stale' ? ['driver'] : state === 'unusable' ? ['torch', 'cuda'] : [],
+ env_id: envId,
+ estimator: 'sd_vae_decode',
+ line,
+ measured_by: measuredBy,
+ measured_range: fitted
+ ? { max_pixels: Math.max(...countedSides) ** 2, min_pixels: Math.min(...countedSides) ** 2 }
+ : null,
+ own_windows: countedPoints.filter((point) => point.model_key === modelKey).length,
+ problem: fitted
+ ? null
+ : countedPoints.length === 0 && linePoints.every((point) => point.excluded === 'aborted_attempt')
+ ? ABORTED_LINE_PROBLEM
+ : 'A line needs two sizes at least 1.5 times apart.',
+ slope_bytes_per_pixel: fitted ? 1_100 : null,
+ sizes,
+ state,
+ version: 1,
+ },
+ ];
+ });
+ };
+
+ const unavailableReason = (scenario) =>
+ scenario === 'multiGpu'
+ ? 'Calibration needs exactly one generation device; this machine generates on cuda:0 and cuda:1.'
+ : scenario === 'noGpu'
+ ? 'This machine has no GPU to calibrate.'
+ : scenario === 'storeUnusable'
+ ? `working_memory/${DEVICE_CLASS.id}.json has schema_version 9; this version reads up to 1.`
+ : null;
+
+ const plan = (model, scenario) => {
+ const base = {
+ calibrated_through: null,
+ cases: [],
+ device_class: null,
+ estimated_seconds: null,
+ estimators: model.type === 'main' ? ['sd_vae_decode'] : [],
+ model_key: model.key,
+ not_covered: [],
+ reason: null,
+ repetitions: REPETITIONS,
+ shared_with: [],
+ supported: false,
+ };
+
+ if (model.type !== 'main') {
+ return {
+ ...base,
+ reason: `Calibration covers the decode of SD1, SD2, SDXL, SD3, FLUX.1, FLUX.2, Z-Image and CogView4 main models and their VAEs; no installed main model generates with this ${model.base} ${model.type}.`,
+ };
+ }
+
+ if (MODEL_SCENARIOS[model.key] === 'unsupported') {
+ return { ...base, reason: 'The inpaint variant does not generate from text alone.' };
+ }
+
+ if (scenario === 'multiGpu' || scenario === 'noGpu') {
+ return { ...base, reason: unavailableReason(scenario) };
+ }
+
+ const cases = casesOf(model);
+ const shared = mainModels.filter((other) => other.key !== model.key).slice(0, 3);
+
+ return {
+ ...base,
+ cases,
+ device_class: { id: DEVICE_CLASS.id, name: DEVICE_CLASS.name },
+ estimated_seconds: 30 + stepsOf(cases).length * 6,
+ not_covered: [ENCODE_NOT_COVERED],
+ shared_with: shared.map((other) => ({
+ base: other.base,
+ key: other.key,
+ lines: DTYPES.map((dtype) => `decode_${dtype}`),
+ name: other.name,
+ type: other.type,
+ })),
+ supported: true,
+ };
+ };
+
+ const status = (scenario) => {
+ const reason = unavailableReason(scenario);
+ const hasClass = scenario !== 'multiGpu' && scenario !== 'noGpu';
+ const allRuns = [...runs.entries()].flatMap(([modelKey, list]) =>
+ list.map((run) => {
+ const pointCount = pointCountOf(run);
+
+ return {
+ attempt_id: run.attempt_id,
+ attempt_steps: run.attempt_steps,
+ created_at: run.created_at,
+ env_id: ENV_ID,
+ item_ids: run.items.map((item) => item.item_id),
+ model_hash: byKey.get(modelKey)?.hash ?? null,
+ model_key: modelKey,
+ point_count: storedPointsOf(run),
+ run_id: run.run_id,
+ user_id: 'system',
+ ...runStatus(run, pointCount),
+ };
+ })
+ );
+
+ return {
+ available: reason === null,
+ current_device_class_id: hasClass ? DEVICE_CLASS.id : null,
+ current_env_id: hasClass ? ENV_ID : null,
+ device_classes: hasClass
+ ? [
+ {
+ device_class: scenario === 'storeUnusable' ? null : DEVICE_CLASS,
+ device_class_id: DEVICE_CLASS.id,
+ envs:
+ scenario === 'storeUnusable'
+ ? []
+ : [
+ {
+ hard: {
+ cuda: '12.8',
+ os: scenario === 'notVerified' ? 'linux' : 'windows',
+ torch: '2.7',
+ },
+ hard_matches_current: true,
+ id: ENV_ID,
+ point_count: [...points.values()].flat().filter((point) => point.env_id === ENV_ID).length,
+ soft: { driver: '576.02' },
+ soft_matches_current: true,
+ },
+ ],
+ is_current: true,
+ ...measurement(scenario),
+ point_counts: [],
+ problem: scenario === 'storeUnusable' ? reason : null,
+ runs: scenario === 'storeUnusable' ? [] : allRuns,
+ usable: scenario !== 'storeUnusable',
+ },
+ ]
+ : [],
+ unavailable_reason: reason,
+ };
+ };
+
+ /** The measurement method of the device class; `notVerified` stands for a backend nobody checked it on. */
+ const measurement = (scenario) => ({
+ measurement_method: 'allocator_peak',
+ measurement_verified: scenario !== 'notVerified',
+ });
+
+ const summary = (model, scenario) => {
+ advance(model.key);
+
+ return {
+ current_env_id: ENV_ID,
+ device_class_id: DEVICE_CLASS.id,
+ excluded_windows: 0,
+ lines: scenario === 'storeUnusable' ? [] : linesOf(model.key, MODEL_SCENARIOS[model.key]),
+ ...measurement(scenario),
+ model_key: model.key,
+ problem: scenario === 'storeUnusable' ? unavailableReason(scenario) : null,
+ runs: scenario === 'storeUnusable' ? [] : modelRuns(model.key),
+ usable: scenario !== 'storeUnusable',
+ };
+ };
+
+ const calibrate = (model, body, scenario) => {
+ if (unavailableReason(scenario) !== null) {
+ return { body: { detail: unavailableReason(scenario) }, status: 409 };
+ }
+
+ if (typeof body?.graph?.nodes !== 'object' || body.graph.nodes === null) {
+ return { body: { detail: 'The graph cannot be measured as a calibration run.' }, status: 422 };
+ }
+
+ const graphModelsRefusal = graphModelsProblem(body.graph, body.graph_models);
+
+ if (graphModelsRefusal !== null) {
+ return { body: { detail: graphModelsRefusal }, status: 422 };
+ }
+
+ const attemptId = body.attempt_id ?? null;
+ const attemptSteps = body.attempt_steps ?? null;
+
+ if (attemptId !== null && !(typeof attemptId === 'string' && ATTEMPT_ID_PATTERN.test(attemptId))) {
+ return { body: { detail: 'attempt_id must be 1 to 64 of A-Z a-z 0-9 _ . : -' }, status: 422 };
+ }
+
+ if ((attemptId === null) !== (attemptSteps === null)) {
+ return { body: { detail: 'attempt_id and attempt_steps are sent together, or neither.' }, status: 422 };
+ }
+
+ if (
+ attemptSteps !== null &&
+ !(Number.isInteger(attemptSteps) && attemptSteps >= 1 && attemptSteps <= MAX_ATTEMPT_STEPS)
+ ) {
+ return { body: { detail: `attempt_steps must be 1 to ${String(MAX_ATTEMPT_STEPS)}.` }, status: 422 };
+ }
+
+ const attemptRuns = (runs.get(model.key) ?? []).filter((run) => attemptId !== null && run.attempt_id === attemptId);
+
+ if (attemptRuns.some((run) => run.attempt_steps !== attemptSteps)) {
+ return { body: { detail: "attempt_steps differs from that of the attempt's runs already stored." }, status: 409 };
+ }
+
+ const key = typeof body.idempotency_key === 'string' ? body.idempotency_key : null;
+ const known = key ? receipts.get(key) : undefined;
+ const existing = known && (runs.get(model.key) ?? []).find((run) => run.run_id === known);
+
+ if (!existing) {
+ // A later step after another run, of any model or none, was created since the attempt's first: it would measure
+ // the GPU after that calibration. The attempt stays short, and so aborted.
+ const ownFirst = [...runs.values()]
+ .flat()
+ .filter((run) => attemptId !== null && run.attempt_id === attemptId)
+ .map((run) => run.created_at)
+ .sort()[0];
+
+ if (
+ ownFirst !== undefined &&
+ [...runs.values()].flat().some((run) => run.attempt_id !== attemptId && run.created_at > ownFirst)
+ ) {
+ return { body: { detail: INTERLEAVED_REFUSAL }, status: 409 };
+ }
+
+ // One attempt per device class, as the server judges it: a request with an attempt is refused while another
+ // attempt, of any model, runs or is open (`attemptBlocks`). A run without an attempt holds nothing, and a
+ // request without one is never refused for it.
+ if (attemptId !== null && attemptBlocks(attemptId)) {
+ return { body: { detail: RUNNING_REFUSAL }, status: 409 };
+ }
+
+ // Every model the graph names must still be the record it compiled over: as its identifier and its
+ // graph_models entry name it.
+ for (const identifier of modelIdentifiersOf(body.graph)) {
+ const record = currentModel ? currentModel(identifier.key) : byKey.get(identifier.key);
+ const name = identifier.name ?? record?.name ?? identifier.key;
+
+ if (!record) {
+ const message = `${name} was removed after this calibration was planned. Calibrate again.`;
+ return { body: { detail: { code: 'model_changed', message } }, status: 409 };
+ }
+
+ const compiled = body.graph_models[identifier.key];
+ const facts = IDENTITY_FACTS.filter(
+ (fact) =>
+ (fact in identifier && record[fact] !== identifier[fact]) || (record[fact] ?? null) !== compiled[fact]
+ );
+
+ if (facts.length > 0) {
+ const message = `${name} changed after this calibration was planned (${facts.join(', ')}). Calibrate again.`;
+ return { body: { detail: { code: 'model_changed', message } }, status: 409 };
+ }
+ }
+ }
+
+ const caseId = typeof body.graph.id === 'string' ? body.graph.id : null;
+ const step = casesOf(model).find((item) => item.id === caseId) ?? casesOf(model)[0];
+ const run = existing ?? createRun(model.key, [step], now(), attemptId, attemptSteps);
+
+ if (key) {
+ receipts.set(key, run.run_id);
+ }
+
+ return {
+ body: { device_class_id: DEVICE_CLASS.id, item_ids: run.items.map((item) => item.item_id), run_id: run.run_id },
+ status: 201,
+ };
+ };
+
+ const cancelByOrigin = (originPrefix) => {
+ let canceled = 0;
+
+ for (const list of runs.values()) {
+ for (const run of list) {
+ if (!`${ORIGIN_PREFIX}${run.run_id}`.startsWith(originPrefix)) {
+ continue;
+ }
+
+ for (const item of run.items) {
+ if (item.status === 'pending' || item.status === 'in_progress') {
+ // A decode canceled while it ran leaves an invalid window.
+ item.interrupted = item.status === 'in_progress';
+ item.status = 'canceled';
+ canceled += 1;
+ }
+ }
+ }
+ }
+
+ return canceled;
+ };
+
+ const resetModel = (modelKey) => {
+ const removed = runs.get(modelKey) ?? [];
+ const pointsRemoved = (points.get(modelKey) ?? []).length;
+
+ runs.delete(modelKey);
+ points.delete(modelKey);
+
+ return { points_removed: pointsRemoved, runs_removed: removed.length };
+ };
+
+ /** Answers a working-memory route, or returns null for any other path. */
+ const handle = ({ body, method, path, scenario }) => {
+ if (path === '/api/v2/models/working_memory/status' && method === 'GET') {
+ return scenario === 'error'
+ ? { body: { detail: 'The calibration store cannot be read (fixture outage).' }, status: 503 }
+ : { body: status(scenario), status: 200 };
+ }
+
+ const match = /^\/api\/v2\/models\/i\/([^/]+)\/working_memory(?:\/(plan|summary|calibrate))?$/.exec(path);
+
+ if (!match) {
+ return null;
+ }
+
+ const model = byKey.get(decodeURIComponent(match[1]));
+
+ if (!model) {
+ return { body: { detail: 'The model could not be found' }, status: 404 };
+ }
+
+ if (scenario === 'error') {
+ return { body: { detail: 'The calibration store cannot be read (fixture outage).' }, status: 503 };
+ }
+
+ const noDeviceClass = scenario === 'multiGpu' || scenario === 'noGpu';
+
+ switch (`${method} ${match[2] ?? ''}`) {
+ case 'GET plan':
+ return { body: plan(model, scenario), status: 200 };
+ case 'GET summary':
+ return noDeviceClass
+ ? { body: { detail: 'No device_class_id was given and there is no current one' }, status: 409 }
+ : { body: summary(model, scenario), status: 200 };
+ case 'POST calibrate':
+ return calibrate(model, body, scenario);
+ case 'DELETE ':
+ return noDeviceClass
+ ? { body: { detail: 'No device_class_id was given and there is no current one' }, status: 409 }
+ : { body: resetModel(model.key), status: 200 };
+ default:
+ return { body: { detail: 'Method Not Allowed' }, status: 405 };
+ }
+ };
+
+ return {
+ cancelByOrigin,
+ handle,
+ isCalibrationPrefix: (prefix) => prefix.startsWith(ORIGIN_PREFIX),
+ reset,
+ seedModelChanged,
+ seedRunning,
+ seedStopped,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/app/calibrationGraphs.browser.test.ts b/invokeai/frontend/webv2/src/app/calibrationGraphs.browser.test.ts
new file mode 100644
index 0000000000..57a6130515
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/calibrationGraphs.browser.test.ts
@@ -0,0 +1,130 @@
+import type { ModelConfig, WorkingMemoryCase } from '@features/models';
+
+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+/** Serves the capability table; module mocks cannot be used here, since they would instrument the worker's modules. */
+const fetchCapabilities = () =>
+ vi
+ .spyOn(globalThis, 'fetch')
+ .mockImplementation(() => Promise.resolve(Response.json(architectureCapabilitiesFixture)));
+
+const SDXL = {
+ base: 'sdxl',
+ format: 'diffusers',
+ hash: 'blake3:sdxl',
+ key: 'sdxl',
+ name: 'SDXL',
+ type: 'main',
+ variant: 'normal',
+} as ModelConfig;
+
+const planCase = (id: string, modelKey = 'sdxl'): WorkingMemoryCase => ({
+ components: {},
+ estimator: 'sdxl_vae_decode',
+ height: 768,
+ id,
+ line: 'decode_fp32',
+ mode: 'txt2img',
+ model_key: modelKey,
+ negative_prompt: '',
+ positive_prompt: 'a lake',
+ seed: 1,
+ settings: { vaePrecision: 'fp32' },
+ steps: 2,
+ width: 768,
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+/** The records a caller read for the compile. */
+const records = () => Promise.resolve([SDXL]);
+
+/** Runs the real worker: its bundle must start in a browser and compile without the page's modules. */
+describe('compileCalibrationGraphs', () => {
+ it('compiles the cases in a worker over the records it is given and the served capability table', async () => {
+ const fetch = fetchCapabilities();
+ const { compileCalibrationGraphs } = await import('./calibrationGraphs');
+
+ const [compiled] = await compileCalibrationGraphs([planCase('fp32-768')], records(), new AbortController().signal);
+ const nodes = Object.values((compiled!.graph as { nodes: Record<string, Record<string, unknown>> }).nodes);
+
+ expect(String(fetch.mock.calls[0]?.[0])).toMatch(/\/api\/v2\/models\/capabilities$/);
+ expect(compiled!.caseId).toBe('fp32-768');
+ expect(nodes.find((node) => node.type === 'l2i')).toMatchObject({ fp32: true });
+ expect(nodes.find((node) => node.type === 'noise')).toMatchObject({ height: 768, width: 768 });
+ });
+
+ it('rejects with the compiler’s message for a case that cannot compile', async () => {
+ fetchCapabilities();
+ const { compileCalibrationGraphs } = await import('./calibrationGraphs');
+
+ await expect(
+ compileCalibrationGraphs([planCase('lost', 'removed-model')], records(), new AbortController().signal)
+ ).rejects.toThrow(/^Case lost: model_key "removed-model" is not a selectable main model/);
+ });
+
+ it('rejects with the records read’s error, starting no worker', async () => {
+ fetchCapabilities();
+ const { compileCalibrationGraphs } = await import('./calibrationGraphs');
+ const started = vi.spyOn(Worker.prototype, 'postMessage');
+
+ await expect(
+ compileCalibrationGraphs(
+ [planCase('fp32-768')],
+ Promise.reject(new Error('Failed to load models.')),
+ new AbortController().signal
+ )
+ ).rejects.toThrow('Failed to load models.');
+ expect(started).not.toHaveBeenCalled();
+ });
+
+ /** A worker that never answers: its request is dropped. Resolves once the request would have been sent. */
+ const silenceWorker = () => {
+ const terminate = vi.spyOn(Worker.prototype, 'terminate');
+ let sent = () => undefined as void;
+ const posted = new Promise<void>((resolve) => {
+ sent = resolve;
+ });
+ vi.spyOn(Worker.prototype, 'postMessage').mockImplementation(() => sent());
+
+ return { posted, terminate };
+ };
+
+ it('stops the worker and rejects when its owner aborts', async () => {
+ fetchCapabilities();
+ const { compileCalibrationGraphs } = await import('./calibrationGraphs');
+ const { posted, terminate } = silenceWorker();
+ const owner = new AbortController();
+
+ const compiling = compileCalibrationGraphs([planCase('fp32-768')], records(), owner.signal);
+ await posted;
+ owner.abort(new Error('Calibration stopped.'));
+
+ await expect(compiling).rejects.toThrow('Calibration stopped.');
+ expect(terminate).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops a worker that does not answer in time and rejects', async () => {
+ fetchCapabilities();
+ const { COMPILE_TIMEOUT_MS, compileCalibrationGraphs } = await import('./calibrationGraphs');
+ const { posted, terminate } = silenceWorker();
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+
+ try {
+ const compiling = compileCalibrationGraphs([planCase('fp32-768')], records(), new AbortController().signal);
+ const outcome = expect(compiling).rejects.toThrow(/did not answer within 60 s/);
+ await posted;
+ vi.advanceTimersByTime(COMPILE_TIMEOUT_MS - 1);
+ expect(terminate).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ await outcome;
+ expect(terminate).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/calibrationGraphs.test.ts b/invokeai/frontend/webv2/src/app/calibrationGraphs.test.ts
new file mode 100644
index 0000000000..d8bbb86828
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/calibrationGraphs.test.ts
@@ -0,0 +1,86 @@
+import type { WorkingMemoryCase } from '@features/models';
+
+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';
+import { describe, expect, it } from 'vitest';
+
+import { toCalibrationGraphs, toGraphExportCase } from './calibrationGraphs';
+import { exportGraphs } from './graphExport';
+
+const MODELS = [
+ {
+ base: 'sdxl',
+ format: 'diffusers',
+ hash: 'blake3:sdxl',
+ key: 'sdxl',
+ name: 'SDXL',
+ type: 'main',
+ variant: 'normal',
+ },
+];
+
+/** A case as the server's plan sends it for an SDXL decode in fp32. */
+const planCase = (overrides: Partial<WorkingMemoryCase> = {}): WorkingMemoryCase => ({
+ components: {},
+ estimator: 'sdxl_vae_decode',
+ height: 1088,
+ id: 'sdxl_vae_decode-decode-fp32-1088x1088',
+ line: 'decode_fp32',
+ mode: 'txt2img',
+ model_key: 'sdxl',
+ negative_prompt: '',
+ positive_prompt: 'a mountain lake at dawn, detailed photograph',
+ seed: 1,
+ settings: { vaePrecision: 'fp32' },
+ steps: 2,
+ width: 1088,
+ ...overrides,
+});
+
+const compile = (cases: WorkingMemoryCase[]) =>
+ toCalibrationGraphs(
+ cases,
+ exportGraphs({
+ capabilities: architectureCapabilitiesFixture,
+ cases: cases.map(toGraphExportCase),
+ models: MODELS,
+ version: 1,
+ })
+ );
+
+const nodesOf = (graph: unknown) => Object.values((graph as { nodes: Record<string, Record<string, unknown>> }).nodes);
+
+describe('calibration graphs', () => {
+ it('compiles a plan case as Generate would, at its size, steps and decode precision', () => {
+ const [compiled] = compile([planCase()]);
+ const nodes = nodesOf(compiled!.graph);
+
+ expect(compiled!.caseId).toBe('sdxl_vae_decode-decode-fp32-1088x1088');
+ expect((compiled!.graph as { id: string }).id).toBe('sdxl_vae_decode-decode-fp32-1088x1088');
+ expect(nodes.find((node) => node.type === 'noise')).toMatchObject({ height: 1088, width: 1088 });
+ expect(nodes.find((node) => node.type === 'denoise_latents')).toMatchObject({ steps: 2 });
+ expect(nodes.find((node) => node.type === 'l2i')).toMatchObject({ fp32: true });
+ // Seed and prompt travel as batch data, as Generate queues them.
+ expect(compiled!.data).toEqual([
+ [
+ { field_name: 'value', items: [1], node_path: 'seed' },
+ { field_name: 'value', items: ['a mountain lake at dawn, detailed photograph'], node_path: 'positive_prompt' },
+ { field_name: 'value', items: [''], node_path: 'negative_prompt' },
+ ],
+ ]);
+ });
+
+ it('keeps fp16 cases on the fp16 decode', () => {
+ const [compiled] = compile([
+ planCase({ id: 'fp16-case', line: 'decode_fp16', settings: { vaePrecision: 'fp16' } }),
+ ]);
+ const nodes = nodesOf(compiled!.graph);
+
+ expect(nodes.find((node) => node.type === 'l2i')).toMatchObject({ fp32: false });
+ });
+
+ it('rejects naming the case that cannot compile, so nothing is queued', () => {
+ expect(() => compile([planCase(), planCase({ id: 'missing-model', model_key: 'not-installed' })])).toThrow(
+ /^Case missing-model: model_key "not-installed" is not a selectable main model/
+ );
+ });
+});
diff --git a/invokeai/frontend/webv2/src/app/calibrationGraphs.ts b/invokeai/frontend/webv2/src/app/calibrationGraphs.ts
new file mode 100644
index 0000000000..8f45562c77
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/calibrationGraphs.ts
@@ -0,0 +1,106 @@
+/**
+ * The graphs a working-memory calibration queues, compiled exactly as `pnpm graphs:export` compiles its cases, which
+ * is how Generate compiles them: over the model records the caller read and the capability table the server serves.
+ * The Model Manager loads this module only once Calibrate is clicked, to check that the plan compiles before its
+ * confirmation opens (`compileCalibrationGraphs` in `router.tsx`); the compiler itself runs in
+ * `calibrationGraphs.worker.ts`.
+ */
+
+import type { CalibrationGraph, ModelConfig, WorkingMemoryCase } from '@features/models';
+
+import { apiFetchJson } from '@platform/transport/http';
+
+import type { CalibrationWorkerReply } from './calibrationGraphs.worker';
+import type { GraphExportResponse } from './graphExport';
+
+const GRAPH_EXPORT_VERSION = 1;
+
+/**
+ * A plan case in the export's snake_case case format. The plan adds what the case measures (`estimator`, `line`),
+ * which the export reader rejects as unknown fields.
+ */
+export const toGraphExportCase = ({
+ estimator: _estimator,
+ line: _line,
+ ...record
+}: WorkingMemoryCase): Omit<WorkingMemoryCase, 'estimator' | 'line'> => record;
+
+/** Each case's graph and batch data; rejects naming the first case that cannot compile, before anything is queued. */
+export const toCalibrationGraphs = (
+ cases: readonly WorkingMemoryCase[],
+ response: GraphExportResponse
+): CalibrationGraph[] =>
+ cases.map((item) => {
+ const result = response.cases.find((candidate) => candidate.id === item.id);
+
+ if (!result) {
+ throw new Error(`Case ${item.id} was not compiled.`);
+ }
+
+ if ('error' in result) {
+ throw new Error(`Case ${item.id}: ${result.error}`);
+ }
+
+ return { caseId: item.id, data: result.batch.data, graph: result.batch.graph };
+ });
+
+/** Compiling a large plan takes seconds; a worker that has not answered by then is stuck. */
+export const COMPILE_TIMEOUT_MS = 60_000;
+
+/** Settles exactly once: with the worker's answer, or rejecting on a failure, the timeout or `signal`. */
+const runWorker = (request: unknown, signal: AbortSignal): Promise<GraphExportResponse> =>
+ new Promise((resolve, reject) => {
+ signal.throwIfAborted();
+
+ const worker = new Worker(new URL('./calibrationGraphs.worker.ts', import.meta.url), {
+ name: 'calibration-graphs',
+ type: 'module',
+ });
+ const settle = (error: Error | null, response?: GraphExportResponse) => {
+ worker.terminate();
+ clearTimeout(timeout);
+ signal.removeEventListener('abort', onAbort);
+
+ if (error) {
+ reject(error);
+ } else {
+ resolve(response!);
+ }
+ };
+ const onAbort = () => settle(signal.reason instanceof Error ? signal.reason : new Error('Compiling was stopped.'));
+ const timeout = setTimeout(
+ () => settle(new Error(`The graph compiler did not answer within ${String(COMPILE_TIMEOUT_MS / 1_000)} s.`)),
+ COMPILE_TIMEOUT_MS
+ );
+
+ signal.addEventListener('abort', onAbort, { once: true });
+ worker.addEventListener('message', (event: MessageEvent<CalibrationWorkerReply>) => {
+ if (event.data.ok) {
+ settle(null, event.data.response);
+ } else {
+ settle(new Error(event.data.error));
+ }
+ });
+ worker.addEventListener('messageerror', () => settle(new Error('The graph compiler’s answer could not be read.')));
+ worker.addEventListener('error', (event) => {
+ settle(new Error(event.message || 'The graph compiler did not start.'));
+ });
+ worker.postMessage(request);
+ });
+
+export const compileCalibrationGraphs = async (
+ cases: readonly WorkingMemoryCase[],
+ models: Promise<readonly ModelConfig[]>,
+ signal: AbortSignal
+): Promise<CalibrationGraph[]> => {
+ const [capabilities, records] = await Promise.all([
+ apiFetchJson<unknown>('/api/v2/models/capabilities', { signal }),
+ models,
+ ]);
+ const response = await runWorker(
+ { capabilities, cases: cases.map(toGraphExportCase), models: records, version: GRAPH_EXPORT_VERSION },
+ signal
+ );
+
+ return toCalibrationGraphs(cases, response);
+};
diff --git a/invokeai/frontend/webv2/src/app/calibrationGraphs.worker.ts b/invokeai/frontend/webv2/src/app/calibrationGraphs.worker.ts
new file mode 100644
index 0000000000..f1dd3a477b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/app/calibrationGraphs.worker.ts
@@ -0,0 +1,26 @@
+/**
+ * Compiles working-memory calibration cases with the offline graph export (`graphExport.ts`), in a worker. Its own
+ * bundle keeps Generate's compiler out of both routes' chunk graphs, and its own capability table cannot replace the
+ * one an open editor holds.
+ */
+
+import { exportGraphs } from './graphExport';
+
+export type CalibrationWorkerReply =
+ | { ok: true; response: ReturnType<typeof exportGraphs> }
+ | { ok: false; error: string };
+
+interface WorkerScope {
+ addEventListener(type: 'message', listener: (event: MessageEvent<unknown>) => void): void;
+ postMessage(message: CalibrationWorkerReply): void;
+}
+
+const scope = globalThis as unknown as WorkerScope;
+
+scope.addEventListener('message', (event) => {
+ try {
+ scope.postMessage({ ok: true, response: exportGraphs(event.data) });
+ } catch (error) {
+ scope.postMessage({ error: error instanceof Error ? error.message : String(error), ok: false });
+ }
+});
diff --git a/invokeai/frontend/webv2/src/app/graphExport.test.ts b/invokeai/frontend/webv2/src/app/graphExport.test.ts
index 94905172b5..c3ffe4e22c 100644
--- a/invokeai/frontend/webv2/src/app/graphExport.test.ts
+++ b/invokeai/frontend/webv2/src/app/graphExport.test.ts
@@ -226,6 +226,23 @@ describe('graph export', () => {
});
});
+ // The working-memory calibration planner (`default_vae`) restates this: it sizes each case for the VAE that decodes.
+ it("decodes with the main model's default VAE, which a pick replaces where the model has a VAE slot", () => {
+ const withDefaultVae = (key: string, vaeKey: string) => [
+ ...MODELS.map((entry) => (entry.key === key ? { ...entry, default_settings: { vae: vaeKey } } : entry)),
+ model('flux-vae-b', 'flux', 'vae', { format: 'checkpoint' }),
+ ];
+ const { batch } = exportOne(sdxlCase('sdxl-default-vae'), withDefaultVae('sdxl', 'sdxl-vae'));
+ const zImage = { ...sdxlCase('z-image'), model_key: 'z-image-gguf' };
+ const zImageModels = withDefaultVae('z-image-gguf', 'flux-vae-b');
+
+ expect(nodesOfType(batch.graph, 'vae_loader').map((node) => (node.vae_model as { key: string }).key)).toEqual([
+ 'sdxl-vae',
+ ]);
+ expect(exportOne(zImage, zImageModels).components.vae).toBe('flux-vae-b');
+ expect(exportOne({ ...zImage, components: { vae: 'flux-vae' } }, zImageModels).components.vae).toBe('flux-vae');
+ });
+
it('rejects an installed component the slot does not offer', () => {
const [result] = exportGraphs(
request([sdxlCase('z-image', { components: { qwen3EncoderModel: 'qwen3-8b' }, model_key: 'z-image-gguf' })])
diff --git a/invokeai/frontend/webv2/src/app/router.tsx b/invokeai/frontend/webv2/src/app/router.tsx
index b4de9e0889..3fd4acacb7 100644
--- a/invokeai/frontend/webv2/src/app/router.tsx
+++ b/invokeai/frontend/webv2/src/app/router.tsx
@@ -11,8 +11,10 @@ import {
type Capabilities,
} from '@features/identity';
import {
+ CalibrationGraphCompilerProvider,
ModelInstallRuntime,
ModelsUiProvider,
+ type CalibrationGraphCompiler,
type ModelsUiAdapter,
type SchedulerPolicySource,
type SchedulerPolicyState,
@@ -200,8 +202,18 @@ const requireLaunchpadCapability = async (capability: keyof Capabilities): Promi
}
};
+/** Loads Generate's compiler only once the Model Manager prepares a working-memory calibration. */
+const compileCalibrationGraphs: CalibrationGraphCompiler = (cases, models, signal) =>
+ import('./calibrationGraphs').then((module) => module.compileCalibrationGraphs(cases, models, signal));
+
+const LaunchpadRoute = () => (
+ <CalibrationGraphCompilerProvider compile={compileCalibrationGraphs}>
+ <Launchpad />
+ </CalibrationGraphCompilerProvider>
+);
+
const launchpadRouteOptions = {
- component: Launchpad,
+ component: LaunchpadRoute,
getParentRoute: () => authenticatedRoute,
};
diff --git a/invokeai/frontend/webv2/src/features/models/core/workingMemory.test.ts b/invokeai/frontend/webv2/src/features/models/core/workingMemory.test.ts
new file mode 100644
index 0000000000..981c4f3eb9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/core/workingMemory.test.ts
@@ -0,0 +1,704 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ModelConfig } from './types';
+
+import {
+ calibrationIdempotencyKey,
+ changesCalibration,
+ compiledModelIdentities,
+ deriveCalibrationProgress,
+ describeCoverage,
+ describeFact,
+ getCalibrationBlocker,
+ isMeasurementMethodVerified,
+ modelCalibratingOnGpu,
+ lineDisplayState,
+ planCalibrationSteps,
+ selectAttemptRuns,
+ summarizeLineStates,
+ type LocalAttempt,
+ type WorkingMemoryCase,
+ type WorkingMemoryLine,
+ type WorkingMemoryLineSize,
+ type WorkingMemoryPlan,
+ type WorkingMemoryRun,
+ type WorkingMemoryStatus,
+} from './workingMemory';
+
+const planCase = (dtype: string, side: number): WorkingMemoryCase => ({
+ components: {},
+ estimator: 'sd_vae_decode',
+ height: side,
+ id: `sd_vae_decode-decode-${dtype}-${String(side)}x${String(side)}`,
+ line: `decode_${dtype}`,
+ mode: 'txt2img',
+ model_key: 'main',
+ negative_prompt: '',
+ positive_prompt: 'a lake',
+ seed: 1,
+ settings: { vaePrecision: dtype },
+ steps: 2,
+ width: side,
+});
+
+const plan = (
+ cases: WorkingMemoryCase[],
+ warmUp = 1,
+ measured = 2
+): Pick<WorkingMemoryPlan, 'cases' | 'repetitions'> => ({
+ cases,
+ repetitions: { measured, warm_up: warmUp },
+});
+
+const T0 = Date.parse('2026-10-01T12:00:00.000Z');
+
+const run = (
+ id: string,
+ offsetSeconds: number,
+ status: WorkingMemoryRun['status'],
+ error: string | null = null,
+ attemptId: string | null = 'attempt',
+ overrides: Partial<WorkingMemoryRun> = {}
+): WorkingMemoryRun => ({
+ attempt_id: attemptId,
+ attempt_steps: null,
+ created_at: new Date(T0 + offsetSeconds * 1_000).toISOString(),
+ error,
+ error_code: null,
+ held_back: null,
+ // As the server counts: a failed or canceled decode leaves its window too, as an invalid one.
+ point_count: status === 'running' ? 0 : 1,
+ run_id: id,
+ status,
+ ...overrides,
+});
+const ABORTED = { held_back: 'aborted_attempt' } as const;
+
+const describeSteps = (steps: ReturnType<typeof planCalibrationSteps>) =>
+ steps.map((step) => `${step.case.line}@${String(step.case.width)}:${step.phase}${String(step.repetition)}`);
+
+describe('planCalibrationSteps', () => {
+ it('groups cases by precision and warms each case up right before measuring it', () => {
+ // The plan lists an fp32 case between two fp16 ones; grouping keeps one precision switch.
+ const steps = planCalibrationSteps(plan([planCase('fp16', 512), planCase('fp32', 512), planCase('fp16', 1024)]));
+
+ expect(describeSteps(steps)).toEqual([
+ 'decode_fp16@512:warm_up1',
+ 'decode_fp16@512:measured1',
+ 'decode_fp16@512:measured2',
+ 'decode_fp16@1024:warm_up1',
+ 'decode_fp16@1024:measured1',
+ 'decode_fp16@1024:measured2',
+ 'decode_fp32@512:warm_up1',
+ 'decode_fp32@512:measured1',
+ 'decode_fp32@512:measured2',
+ ]);
+ expect(steps.map((step) => step.index)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]);
+ });
+
+ it('starts every precision with a warm-up, whatever the repetition counts', () => {
+ const steps = planCalibrationSteps(
+ plan([planCase('fp32', 768), planCase('fp16', 768), planCase('fp32', 1536)], 2, 3)
+ );
+ const switches = steps.filter((step, index) => index === 0 || steps[index - 1]!.case.line !== step.case.line);
+
+ expect(steps).toHaveLength(15);
+ expect(switches.map((step) => [step.case.line, step.phase])).toEqual([
+ ['decode_fp32', 'warm_up'],
+ ['decode_fp16', 'warm_up'],
+ ]);
+ });
+});
+
+describe('changesCalibration', () => {
+ const confirmed = plan([planCase('fp16', 512), planCase('fp32', 512)]);
+
+ it('lets new sizes through, which the free memory moves, but not other lines or another number of runs', () => {
+ expect(changesCalibration(confirmed, plan([planCase('fp16', 768), planCase('fp32', 640)]))).toBe(false);
+ // The same two cases in another order are the same calibration.
+ expect(changesCalibration(confirmed, plan([planCase('fp32', 512), planCase('fp16', 512)]))).toBe(false);
+
+ // fp32 is no longer measured, though the run count stays.
+ expect(changesCalibration(confirmed, plan([planCase('fp16', 512), planCase('fp16', 768)]))).toBe(true);
+ // A size more on the same lines.
+ expect(
+ changesCalibration(confirmed, plan([planCase('fp16', 512), planCase('fp16', 768), planCase('fp32', 512)]))
+ ).toBe(true);
+ // The same cases repeated more often.
+ expect(changesCalibration(confirmed, plan([planCase('fp16', 512), planCase('fp32', 512)], 1, 3))).toBe(true);
+ });
+});
+
+describe('calibrationIdempotencyKey', () => {
+ const steps = planCalibrationSteps(plan([planCase('fp16', 512), planCase('fp32', 512)]));
+
+ it('is the same for a resent step and differs across steps and attempts', () => {
+ const keys = steps.map((step) => calibrationIdempotencyKey('attempt-a', step));
+
+ expect(steps.map((step) => calibrationIdempotencyKey('attempt-a', step))).toEqual(keys);
+ expect(new Set(keys).size).toBe(steps.length);
+ expect(keys.some((key) => steps.some((step) => calibrationIdempotencyKey('attempt-b', step) === key))).toBe(false);
+ });
+
+ it('fits the server limit for plan ids of realistic length', () => {
+ const longStep = planCalibrationSteps(
+ plan([{ ...planCase('fp16', 4096), id: 'flux2_vae_decode-decode-bf16-4096x4096' }])
+ )[2]!;
+
+ expect(calibrationIdempotencyKey('0f8fad5b-d9cb-469f-a165-70867728950e', longStep).length).toBeLessThanOrEqual(255);
+ });
+});
+
+describe('selectAttemptRuns', () => {
+ it("takes the newest run's attempt, oldest run first, however long its runs took", () => {
+ const runs = [
+ run('new-2', 3_000, 'running', null, 'new'),
+ run('old-1', 0, 'failed', null, 'old'),
+ run('new-0', 300, 'completed', null, 'new'),
+ run('old-2', 1, 'completed', null, 'old'),
+ ];
+
+ expect(selectAttemptRuns(runs).map((entry) => entry.run_id)).toEqual(['new-0', 'new-2']);
+ expect(selectAttemptRuns(runs, 'old').map((entry) => entry.run_id)).toEqual(['old-1', 'old-2']);
+ expect(selectAttemptRuns([])).toEqual([]);
+ });
+
+ it('counts each run without an attempt id as an attempt of its own', () => {
+ const runs = [run('legacy-1', 0, 'completed', null, null), run('legacy-2', 1, 'failed', 'boom', null)];
+
+ expect(selectAttemptRuns(runs).map((entry) => entry.run_id)).toEqual(['legacy-2']);
+ });
+});
+
+describe('deriveCalibrationProgress', () => {
+ const steps = planCalibrationSteps(plan([planCase('fp16', 512), planCase('fp32', 512)]));
+ const local = (overrides: Partial<LocalAttempt> = {}): LocalAttempt => ({
+ attemptId: 'mine',
+ newestRunAtStart: null,
+ stopped: false,
+ submissionError: null,
+ submitting: false,
+ total: steps.length,
+ ...overrides,
+ });
+
+ it('reports progress and the case the queue is on while any run is pending or running', () => {
+ const runs = [
+ run('r0', 0, 'completed'),
+ run('r1', 1, 'completed'),
+ run('r2', 2, 'running'),
+ run('r3', 3, 'running'),
+ ];
+
+ expect(deriveCalibrationProgress({ local: null, runs, steps })).toEqual({
+ activity: { currentCase: steps[2]!.case, done: 2, kind: 'running', queuing: false, total: 6 },
+ outcome: { kind: 'none' },
+ });
+ });
+
+ it('counts an attempt that is still queuing as running before the server lists any run', () => {
+ const { activity } = deriveCalibrationProgress({ local: local({ submitting: true }), runs: [], steps });
+
+ expect(activity).toEqual({ currentCase: steps[0]!.case, done: 0, kind: 'running', queuing: true, total: 6 });
+ });
+
+ it('reports the error of a failed run, which discards the attempt only where the attempt was aborted too', () => {
+ // An out-of-memory step ends its run, not the attempt: the other steps still feed the fit.
+ const ranOn = [run('r0', 0, 'completed'), run('r1', 1, 'failed', 'CUDA out of memory'), run('r2', 2, 'completed')];
+ // Stopped after the failure: the server holds the attempt back as aborted.
+ const stopped = [
+ run('r0', 0, 'completed', null, 'attempt', ABORTED),
+ run('r1', 1, 'failed', 'CUDA out of memory', 'attempt', ABORTED),
+ run('r2', 2, 'canceled', null, 'attempt', ABORTED),
+ ];
+
+ expect(deriveCalibrationProgress({ local: null, runs: ranOn, steps }).outcome).toEqual({
+ discarded: false,
+ error: 'CUDA out of memory',
+ kept: true,
+ kind: 'failed',
+ });
+ expect(deriveCalibrationProgress({ local: null, runs: stopped, steps }).outcome).toEqual({
+ discarded: true,
+ error: 'CUDA out of memory',
+ kept: false,
+ kind: 'failed',
+ });
+ // Every step failed out of memory: each left an invalid window, and nothing still counts.
+ const allFailed = steps.map((_, index) => run(`f${String(index)}`, index, 'failed', 'OOM'));
+ expect(deriveCalibrationProgress({ local: null, runs: allFailed, steps }).outcome).toEqual({
+ discarded: false,
+ error: 'OOM',
+ kept: false,
+ kind: 'failed',
+ });
+ // The first step failed and Stop canceled the rest: the server holds the attempt back, but its only window is
+ // invalid, so nothing was discarded.
+ const stoppedMidDecode = [
+ run('f0', 0, 'failed', 'OOM', 'attempt', ABORTED),
+ ...steps
+ .slice(1)
+ .map((_, index) => run(`c${String(index + 1)}`, index + 1, 'canceled', null, 'attempt', ABORTED)),
+ ];
+ expect(deriveCalibrationProgress({ local: null, runs: stoppedMidDecode, steps }).outcome).toEqual({
+ discarded: false,
+ error: 'OOM',
+ kept: false,
+ kind: 'failed',
+ });
+ });
+
+ it('tells completed, canceled and partial attempts apart', () => {
+ const completed = steps.map((_, index) => run(`r${String(index)}`, index, 'completed'));
+ // A queue clear canceled these: the server discards the attempt.
+ const canceled = [
+ run('r0', 0, 'canceled', null, 'attempt', ABORTED),
+ run('r1', 1, 'canceled', null, 'attempt', ABORTED),
+ ];
+ const someCanceled = [
+ ...completed.slice(0, 3).map((settled) => ({ ...settled, ...ABORTED })),
+ run('r3', 3, 'canceled', null, 'attempt', ABORTED),
+ run('r4', 4, 'partial', null, 'attempt', ABORTED),
+ ];
+
+ expect(deriveCalibrationProgress({ local: null, runs: completed, steps }).outcome).toEqual({ kind: 'completed' });
+ // Every run was canceled, the first one during its decode: its window is invalid, so nothing was lost.
+ expect(deriveCalibrationProgress({ local: null, runs: canceled, steps }).outcome).toEqual({ kind: 'canceled' });
+ // A canceled run of no attempt (a script's) is judged on its own.
+ expect(
+ deriveCalibrationProgress({ local: null, runs: [run('r0', 0, 'canceled', null, null)], steps }).outcome
+ ).toEqual({ kind: 'canceled' });
+ expect(deriveCalibrationProgress({ local: null, runs: someCanceled, steps }).outcome).toEqual({
+ canceled: true,
+ discarded: true,
+ error: null,
+ kind: 'partial',
+ queued: 5,
+ total: 5,
+ });
+ });
+
+ it('judges an attempt another tab started by its runs, not by a plan that may have changed since', () => {
+ const fewerThanPlanned = [run('r0', 0, 'completed'), run('r1', 1, 'completed')];
+
+ expect(deriveCalibrationProgress({ local: null, runs: fewerThanPlanned, steps }).outcome).toEqual({
+ kind: 'completed',
+ });
+ });
+
+ it('reports an attempt whose queuing stopped early as partial, or failed when nothing was queued', () => {
+ // Two of six steps were queued: the server holds the attempt back as aborted.
+ const shortOf = { ...ABORTED, attempt_steps: 6 };
+ const runs = [run('r0', 0, 'completed', null, 'mine', shortOf), run('r1', 1, 'completed', null, 'mine', shortOf)];
+
+ expect(deriveCalibrationProgress({ local: local({ submissionError: 'Queue full' }), runs, steps }).outcome).toEqual(
+ {
+ canceled: false,
+ discarded: true,
+ error: 'Queue full',
+ kind: 'partial',
+ queued: 2,
+ total: 6,
+ }
+ );
+ // Its graphs did not compile, so nothing of it was queued; an older attempt does not hide the error.
+ const older = [run('old', 0, 'completed', null, 'old')];
+ const failedStart = local({ newestRunAtStart: 'old', submissionError: 'Case x: unknown model' });
+ expect(deriveCalibrationProgress({ local: failedStart, runs: older, steps }).outcome).toEqual({
+ discarded: false,
+ error: 'Case x: unknown model',
+ kept: false,
+ kind: 'failed',
+ });
+ });
+
+ it('names a step that failed because a model changed after planning, whatever else failed', () => {
+ const changed = { error_code: 'model_changed' as const };
+ const runs = [
+ run('r0', 0, 'completed'),
+ run('r1', 1, 'failed', 'CUDA out of memory'),
+ run('r2', 2, 'failed', 'This SDXL changed after this calibration was planned (hash).', 'attempt', changed),
+ ];
+
+ expect(deriveCalibrationProgress({ local: null, runs, steps }).outcome).toMatchObject({
+ error: 'This SDXL changed after this calibration was planned (hash).',
+ // The completed step measured a model that has changed since: no claim that it still counts.
+ kept: false,
+ kind: 'failed',
+ refusal: 'modelChanged',
+ });
+ // A failure without the code is not read as one by its text.
+ const worded = [run('r0', 0, 'failed', 'This SDXL changed after this calibration was planned (hash).')];
+ expect(deriveCalibrationProgress({ local: null, runs: worded, steps }).outcome).not.toHaveProperty(
+ 'refusal',
+ 'modelChanged'
+ );
+ });
+
+ it('follows the server once the attempt settled, whatever this tab saw of its end', () => {
+ const recorded = { attempt_steps: 6 };
+ const finished = steps.map((_, index) => run(`r${String(index)}`, index, 'completed', null, 'mine', recorded));
+
+ // Stop came after the last step finished: nothing was canceled, and the server keeps the attempt.
+ expect(deriveCalibrationProgress({ local: local({ stopped: true }), runs: finished, steps }).outcome).toEqual({
+ kind: 'completed',
+ });
+ // Stop came while the last step failed: the server keeps the other steps.
+ const lastFailed = [...finished.slice(0, 5), run('r5', 5, 'failed', 'CUDA out of memory', 'mine', recorded)];
+ expect(deriveCalibrationProgress({ local: local({ stopped: true }), runs: lastFailed, steps }).outcome).toEqual({
+ discarded: false,
+ error: 'CUDA out of memory',
+ kept: true,
+ kind: 'failed',
+ });
+ // The last step's answer failed three times, but the server had recorded it: the attempt is complete.
+ expect(
+ deriveCalibrationProgress({
+ local: local({ submissionError: 'The calibration store is locked' }),
+ runs: finished,
+ steps,
+ }).outcome
+ ).toEqual({ kind: 'completed' });
+ });
+
+ it('lets an attempt that queued nothing give way to any attempt that ran after it', () => {
+ // This tab could not reach the server; another tab then calibrated to the end.
+ const failedStart = local({ newestRunAtStart: 'old', submissionError: 'Failed to fetch' });
+ const theirs = steps.map((_, index) => run(`theirs-${String(index)}`, 100 + index, 'completed', null, 'theirs'));
+
+ expect(
+ deriveCalibrationProgress({
+ local: failedStart,
+ runs: [run('old', 0, 'completed', null, 'old'), ...theirs],
+ steps,
+ }).outcome
+ ).toEqual({ kind: 'completed' });
+ expect(
+ deriveCalibrationProgress({ local: { ...failedStart, newestRunAtStart: null }, runs: theirs, steps }).outcome
+ ).toEqual({ kind: 'completed' });
+ });
+
+ it('reports an attempt the user stopped as canceled, even where queuing ended before any run was canceled', () => {
+ // Stopped after two of six steps were queued: the server holds the attempt back as aborted.
+ const shortOf = { ...ABORTED, attempt_steps: 6 };
+ const runs = [run('r0', 0, 'completed', null, 'mine', shortOf), run('r1', 1, 'completed', null, 'mine', shortOf)];
+
+ // Stop discards the attempt, the steps it finished included, before the server's next summary says so.
+ expect(deriveCalibrationProgress({ local: local({ stopped: true }), runs, steps }).outcome).toEqual({
+ canceled: true,
+ discarded: true,
+ error: null,
+ kind: 'partial',
+ queued: 2,
+ total: 6,
+ });
+ // Stopped before its first step was queued: nothing was measured to discard.
+ expect(deriveCalibrationProgress({ local: local({ stopped: true }), runs: [], steps }).outcome).toEqual({
+ kind: 'canceled',
+ });
+ });
+
+ it('tells an attempt whose queuing ended early from a complete one by the step count stored with its runs', () => {
+ const counted = { attempt_steps: 6 };
+ const truncated = [
+ run('r0', 0, 'completed', null, 'attempt', { ...counted, ...ABORTED }),
+ run('r1', 1, 'completed', null, 'attempt', { ...counted, ...ABORTED }),
+ ];
+ const complete = steps.map((_, index) => run(`r${String(index)}`, index, 'completed', null, 'attempt', counted));
+
+ // After a reload this tab has no record of it.
+ expect(deriveCalibrationProgress({ local: null, runs: truncated, steps }).outcome).toEqual({
+ canceled: false,
+ discarded: true,
+ error: null,
+ kind: 'partial',
+ queued: 2,
+ total: 6,
+ });
+ expect(deriveCalibrationProgress({ local: null, runs: complete, steps }).outcome).toEqual({ kind: 'completed' });
+ });
+
+ it('follows the newer attempt another tab started, not this tab’s older one', () => {
+ const runs = [
+ run('mine', 0, 'failed', 'old failure', 'mine'),
+ run('theirs-0', 100, 'completed', null, 'theirs'),
+ run('theirs-1', 101, 'running', null, 'theirs'),
+ ];
+ const { activity } = deriveCalibrationProgress({ local: local(), runs, steps });
+
+ expect(activity).toMatchObject({ done: 1, kind: 'running' });
+ });
+});
+
+describe('summarizeLineStates', () => {
+ it('reports the most severe line, or null without lines', () => {
+ expect(summarizeLineStates(['in_use', 'stale'])).toBe('stale');
+ expect(summarizeLineStates(['insufficient', 'in_use'])).toBe('insufficient');
+ expect(summarizeLineStates(['interrupted', 'in_use'])).toBe('interrupted');
+ expect(summarizeLineStates(['interrupted', 'insufficient'])).toBe('insufficient');
+ expect(summarizeLineStates(['stale', 'unusable'])).toBe('unusable');
+ expect(summarizeLineStates(['in_use'])).toBe('in_use');
+ expect(summarizeLineStates([])).toBeNull();
+ });
+});
+
+describe('lineDisplayState', () => {
+ const size = (excludedReason: WorkingMemoryLineSize['excluded_reason']) => ({ excluded_reason: excludedReason });
+ const sized = (state: WorkingMemoryLine['state'], reasons: WorkingMemoryLineSize['excluded_reason'][]) =>
+ ({ sizes: reasons.map(size), state }) as Pick<WorkingMemoryLine, 'sizes' | 'state'>;
+
+ it('reads a line only stopped attempts measured as stopped, not as short of sizes', () => {
+ expect(lineDisplayState(sized('insufficient', ['aborted_attempt', 'aborted_attempt']))).toBe('interrupted');
+ // A size of its own, or one left out for another reason, makes it short of sizes after all.
+ expect(lineDisplayState(sized('insufficient', ['aborted_attempt', null]))).toBe('insufficient');
+ expect(lineDisplayState(sized('insufficient', ['aborted_attempt', 'fragmented']))).toBe('insufficient');
+ expect(lineDisplayState(sized('insufficient', []))).toBe('insufficient');
+ expect(lineDisplayState(sized('in_use', ['aborted_attempt', null, null]))).toBe('in_use');
+ });
+});
+
+describe('describeCoverage', () => {
+ type Line = Pick<WorkingMemoryLine, 'env_id' | 'estimator' | 'line' | 'own_windows' | 'sizes' | 'state' | 'version'>;
+ const line = (
+ state: WorkingMemoryLine['state'],
+ {
+ envId = 'current',
+ lineName = 'decode_fp16',
+ ownWindows = 3,
+ version = 2,
+ }: { envId?: string; lineName?: string; ownWindows?: number; version?: number } = {}
+ ): Line => ({
+ env_id: envId,
+ estimator: 'sd_vae_decode',
+ line: lineName,
+ own_windows: ownWindows,
+ sizes: [],
+ state,
+ version,
+ });
+ const coverage = (lines: Line[], runs: WorkingMemoryRun[] = []) =>
+ describeCoverage({ current_env_id: 'current', lines, runs });
+
+ it("takes the headline from the current environment's lines, else from all lines", () => {
+ // An old environment's unusable line does not outrank what applies now.
+ expect(coverage([line('unusable', { envId: 'old' }), line('in_use')])).toMatchObject({
+ hasCurrentLines: true,
+ state: 'in_use',
+ });
+ expect(coverage([line('unusable', { envId: 'old' })])).toMatchObject({ hasCurrentLines: false, state: 'unusable' });
+ expect(coverage([])).toMatchObject({ hasCurrentLines: false, hasOwnMeasurements: false, state: null });
+ });
+
+ it('lets a line recalibrated under a new estimator version supersede the old version’s unusable line', () => {
+ const oldVersion = line('unusable', { version: 1 });
+
+ expect(coverage([oldVersion, line('in_use')]).state).toBe('in_use');
+ expect(coverage([oldVersion, line('stale')]).state).toBe('stale');
+ expect(coverage([oldVersion]).state).toBe('unusable');
+ // Only the same line supersedes it.
+ expect(coverage([oldVersion, line('in_use', { lineName: 'decode_fp32' })]).state).toBe('unusable');
+ expect(coverage([oldVersion, line('insufficient')]).state).toBe('unusable');
+ });
+
+ it('tells lines only other models measured from the model’s own', () => {
+ expect(coverage([line('in_use', { ownWindows: 0 })])).toMatchObject({
+ hasOwnMeasurements: false,
+ usesOthersOnly: true,
+ });
+ expect(coverage([line('in_use', { ownWindows: 0 }), line('stale')])).toMatchObject({
+ hasOwnMeasurements: true,
+ usesOthersOnly: false,
+ });
+ // A shared line that does not apply is not used.
+ expect(coverage([line('insufficient', { ownWindows: 0 })]).usesOthersOnly).toBe(false);
+ // Runs that measured nothing still leave something to reset.
+ expect(coverage([], [run('r0', 0, 'canceled')]).hasOwnMeasurements).toBe(true);
+ });
+});
+
+describe('getCalibrationBlocker', () => {
+ const supported = { reason: null, supported: true };
+ const available = { available: true, unavailable_reason: null };
+ const usable = { problem: null, usable: true };
+
+ it('names the reason a user can least act on first', () => {
+ expect(
+ getCalibrationBlocker({
+ isRunning: true,
+ plan: { reason: 'Not a text-to-image model.', supported: false },
+ status: { available: false, unavailable_reason: 'Two GPUs.' },
+ summary: null,
+ })
+ ).toEqual({ kind: 'unsupported', reason: 'Not a text-to-image model.' });
+ expect(
+ getCalibrationBlocker({
+ isRunning: true,
+ plan: supported,
+ status: { available: false, unavailable_reason: 'File unusable.' },
+ summary: { problem: 'schema_version 9', usable: false },
+ })
+ ).toEqual({ kind: 'storeUnusable', reason: 'schema_version 9' });
+ expect(
+ getCalibrationBlocker({
+ isRunning: false,
+ plan: supported,
+ status: { available: false, unavailable_reason: 'Two GPUs.' },
+ summary: null,
+ })
+ ).toEqual({ kind: 'unavailable', reason: 'Two GPUs.' });
+ expect(getCalibrationBlocker({ isRunning: true, plan: supported, status: available, summary: usable })).toEqual({
+ kind: 'running',
+ });
+ expect(getCalibrationBlocker({ isRunning: false, plan: supported, status: available, summary: usable })).toBeNull();
+ });
+});
+
+describe('modelCalibratingOnGpu', () => {
+ const classOf = (
+ isCurrent: boolean,
+ runs: { attempt_id: string | null; model_key: string; status: WorkingMemoryRun['status'] }[]
+ ) => ({
+ is_current: isCurrent,
+ runs,
+ });
+ const statusOf = (...classes: ReturnType<typeof classOf>[]) =>
+ ({ device_classes: classes }) as unknown as Pick<WorkingMemoryStatus, 'device_classes'>;
+
+ it('names the model whose attempt runs on this GPU, as the server judges which run holds it', () => {
+ const running = { attempt_id: 'a', model_key: 'sdxl', status: 'running' as const };
+
+ expect(modelCalibratingOnGpu(statusOf(classOf(true, [running])))).toBe('sdxl');
+ // Another device class, a finished run, and a run without an attempt hold nothing here.
+ expect(modelCalibratingOnGpu(statusOf(classOf(false, [running])))).toBeNull();
+ expect(modelCalibratingOnGpu(statusOf(classOf(true, [{ ...running, status: 'completed' }])))).toBeNull();
+ expect(modelCalibratingOnGpu(statusOf(classOf(true, [{ ...running, attempt_id: null }])))).toBeNull();
+ });
+});
+
+describe('isMeasurementMethodVerified', () => {
+ const status = (verified: boolean | null): WorkingMemoryStatus => ({
+ available: true,
+ current_device_class_id: 'class',
+ current_env_id: 'env',
+ device_classes: [
+ {
+ device_class: { arch: null, backend: 'cuda', id: 'class', name: 'GPU', total_mib: 8192, vendor: 'x' },
+ device_class_id: 'class',
+ envs: [],
+ is_current: true,
+ measurement_method: 'allocator',
+ measurement_verified: verified,
+ point_counts: [],
+ problem: null,
+ runs: [],
+ usable: true,
+ },
+ ],
+ unavailable_reason: null,
+ });
+
+ it("takes the model summary's answer, then the current device class's", () => {
+ expect(isMeasurementMethodVerified({ measurement_verified: false }, status(true))).toBe(false);
+ expect(isMeasurementMethodVerified({ measurement_verified: null }, status(false))).toBe(false);
+ expect(isMeasurementMethodVerified(null, status(true))).toBe(true);
+ expect(isMeasurementMethodVerified(null, status(null))).toBeNull();
+ });
+});
+
+describe('describeFact', () => {
+ it('names runtimes by product, translates the rest, and shows variables and settings by their own name', () => {
+ expect(['torch', 'hip', 'cudnn', 'os'].map(describeFact)).toEqual([
+ { name: 'PyTorch' },
+ { name: 'ROCm' },
+ { name: 'cuDNN' },
+ { name: 'OS' },
+ ]);
+ expect(['driver', 'allocator_backend', 'rocm_sdpa_guard'].map(describeFact)).toEqual([
+ { translated: 'driver' },
+ { translated: 'allocator' },
+ { translated: 'sdpaGuard' },
+ ]);
+ expect(describeFact('setting.attention_type')).toEqual({ name: 'attention_type' });
+ expect(describeFact('env.PYTORCH_CUDA_ALLOC_CONF')).toEqual({ name: 'PYTORCH_CUDA_ALLOC_CONF' });
+ expect(describeFact('something_new')).toEqual({ name: 'something_new' });
+ });
+});
+
+// Read rather than imported: the snapshot belongs to Generation, whose internals this feature never imports.
+const ANIMA_LLLITE_GRAPHS = Object.values(
+ import.meta.glob('../../generation/core/__snapshots__/animaLLLiteCanvasGraphs.json', {
+ eager: true,
+ import: 'default',
+ })
+)[0];
+
+describe('compiledModelIdentities', () => {
+ const record = (key: string, extra: Partial<ModelConfig> = {}) =>
+ ({
+ base: 'sdxl',
+ format: 'diffusers',
+ hash: `blake3:${key}`,
+ key,
+ name: key,
+ type: 'main',
+ ...extra,
+ }) as ModelConfig;
+ const identifier = (key: string) => ({ base: 'sdxl', hash: `blake3:${key}`, key, name: key, type: 'main' });
+
+ it("names every model the graph's nodes name, nested ones included, from the records it compiled over", () => {
+ const graph = {
+ id: 'case',
+ nodes: {
+ loader: { id: 'loader', model: identifier('main'), type: 'sdxl_model_loader' },
+ loras: { id: 'loras', loras: [{ lora: identifier('lora'), weight: 1 }], type: 'lora_collection_loader' },
+ // A metadata node's record of a model, which the server counts too.
+ metadata: { id: 'metadata', t5_encoder: identifier('encoder'), type: 'core_metadata' },
+ // Not model identifiers the server counts: no hash, and a submodel type that is no string.
+ other: {
+ id: 'other',
+ numbered: { ...identifier('numbered'), submodel_type: 3 },
+ type: 'other',
+ value: { base: 'sdxl', key: 'no-hash', name: 'x', type: 'main' },
+ },
+ },
+ };
+ const records = [
+ record('main', { variant: 'normal' }),
+ record('no-hash'),
+ record('numbered'),
+ record('lora', { format: 'lycoris' }),
+ record('encoder', { format: 't5_encoder' }),
+ record('unused'),
+ ];
+
+ expect(compiledModelIdentities(graph, records)).toEqual({
+ encoder: { base: 'sdxl', format: 't5_encoder', hash: 'blake3:encoder', type: 'main', variant: null },
+ lora: { base: 'sdxl', format: 'lycoris', hash: 'blake3:lora', type: 'main', variant: null },
+ main: { base: 'sdxl', format: 'diffusers', hash: 'blake3:main', type: 'main', variant: 'normal' },
+ });
+ });
+
+ it('finds the models of a graph the canvas compiler wrote, as the server does', () => {
+ // The server's test (`test_the_models_a_compiled_graph_names_are_found_where_the_client_finds_them`) reads the
+ // same graph and expects the same keys.
+ const graph = (ANIMA_LLLITE_GRAPHS as Record<string, unknown>).inpaint_three_adapters;
+ const keys = ['anima-model', 'depth', 'pose', 'qwen-vae', 'qwen3', 'sketch'];
+
+ expect(
+ Object.keys(
+ compiledModelIdentities(
+ graph,
+ keys.map((key) => record(key))
+ )
+ ).sort()
+ ).toEqual(keys);
+ });
+
+ it('refuses a graph naming a model its records lack', () => {
+ const graph = { nodes: { loader: { id: 'loader', model: identifier('gone'), type: 'sdxl_model_loader' } } };
+
+ expect(() => compiledModelIdentities(graph, [record('main')])).toThrow(
+ 'The graph names model gone, which the records it was compiled over lack.'
+ );
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/core/workingMemory.ts b/invokeai/frontend/webv2/src/features/models/core/workingMemory.ts
new file mode 100644
index 0000000000..1ea2dcd969
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/core/workingMemory.ts
@@ -0,0 +1,605 @@
+/**
+ * Working-memory calibration as the Model Manager sees it: the order a plan's cases run in, the retry keys that make a
+ * lost response safe to resend, which of a model's runs make up the latest attempt, and what the section shows for
+ * a plan, a summary and the device status. The server owns every measurement and every state; this module only
+ * orders, groups and reads them.
+ */
+
+import type { components } from '@api/schema';
+
+import type { ModelConfig } from './types';
+
+type Schemas = components['schemas'];
+
+export type WorkingMemoryPlan = Schemas['WorkingMemoryCalibrationPlan'];
+export type WorkingMemoryCase = Schemas['WorkingMemoryCalibrationCase'];
+export type WorkingMemorySummary = Schemas['WorkingMemoryCalibrationModelSummary'];
+export type WorkingMemoryLine = Schemas['WorkingMemoryCalibrationModelLine'];
+export type WorkingMemoryLineSize = Schemas['WorkingMemoryCalibrationLineSize'];
+export type WorkingMemoryRun = Schemas['WorkingMemoryCalibrationModelRun'];
+export type WorkingMemoryStatus = Schemas['WorkingMemoryCalibrationStatus'];
+export type WorkingMemoryRunCreated = Schemas['WorkingMemoryCalibrationRunCreated'];
+export type WorkingMemoryLineState = WorkingMemoryLine['state'];
+export type WorkingMemoryLineContributor = Schemas['WorkingMemoryCalibrationLineContributor'];
+/**
+ * A model the graph names, as the record the graph was compiled over has it: what the server compares with the model's
+ * record when the step arrives (`graph_models`). Format and variant are null for a record without one.
+ */
+export type CalibrationCompiledModel = Schemas['CalibrationCompiledModel'];
+
+/** The server reserves this origin prefix for calibration queue items; the run id follows it. */
+export const CALIBRATION_ORIGIN_PREFIX = 'invokeai:wm-calibration:';
+
+export const calibrationRunOrigin = (runId: string): string => `${CALIBRATION_ORIGIN_PREFIX}${runId}`;
+
+export const isCalibrationOrigin = (origin: unknown): boolean =>
+ typeof origin === 'string' && origin.startsWith(CALIBRATION_ORIGIN_PREFIX);
+
+/** Models whose plan the section asks for: calibration covers main models and standalone VAEs. */
+export const supportsWorkingMemoryCalibration = (model: { type: string }): boolean =>
+ model.type === 'main' || model.type === 'vae';
+
+/** A case's enqueue payload as Generate would build it: the graph and its batch data. */
+export interface CalibrationGraph {
+ caseId: string;
+ graph: unknown;
+ data: unknown;
+}
+
+/** A case's graph with the identity of every model it names, from the records it was compiled over. */
+export interface CompiledCalibration extends CalibrationGraph {
+ models: Readonly<Record<string, CalibrationCompiledModel>>;
+}
+
+type JsonObject = Record<string, unknown>;
+
+const isJsonObject = (value: unknown): value is JsonObject =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/**
+ * A model identifier as the server reads one in a graph: an object that validates as its `ModelIdentifierField`, with a
+ * string key, hash, name, base and type, and a submodel type that is absent, null or a string. The server also checks
+ * base, type and submodel type against its enums. This module has no list of those that stays current with the
+ * server's, and a compiled graph's identifiers come from server records, whose values are the server's own.
+ */
+const isModelIdentifier = (value: JsonObject): value is JsonObject & { key: string } =>
+ ['key', 'hash', 'name', 'base', 'type'].every((field) => typeof value[field] === 'string') &&
+ (value.submodel_type === undefined || value.submodel_type === null || typeof value.submodel_type === 'string');
+
+/**
+ * The keys of every model the graph's nodes name, in a field or nested in one (a LoRA collection's list, a metadata
+ * node's record), as the server finds them (`graph_model_identifiers`): it takes the identities of exactly those.
+ */
+const modelKeysOf = (graph: unknown): Set<string> => {
+ const keys = new Set<string>();
+ const visit = (value: unknown): void => {
+ if (Array.isArray(value)) {
+ value.forEach(visit);
+ } else if (isJsonObject(value)) {
+ if (isModelIdentifier(value)) {
+ keys.add(value.key);
+ } else {
+ Object.values(value).forEach(visit);
+ }
+ }
+ };
+ const nodes = isJsonObject(graph) && isJsonObject(graph.nodes) ? Object.values(graph.nodes) : [];
+
+ for (const node of nodes) {
+ if (isJsonObject(node)) {
+ Object.values(node).forEach(visit);
+ }
+ }
+ return keys;
+};
+
+/**
+ * The identity of every model `graph` names, from `records`, the records it was compiled over. Throws for a model
+ * they lack, which a compiler over them cannot have named.
+ */
+export const compiledModelIdentities = (
+ graph: unknown,
+ records: readonly ModelConfig[]
+): Record<string, CalibrationCompiledModel> => {
+ const byKey = new Map(records.map((record) => [record.key, record]));
+ const identities: Record<string, CalibrationCompiledModel> = {};
+
+ for (const key of modelKeysOf(graph)) {
+ const record = byKey.get(key);
+
+ if (!record) {
+ throw new Error(`The graph names model ${key}, which the records it was compiled over lack.`);
+ }
+ identities[key] = {
+ base: record.base,
+ format: record.format,
+ hash: record.hash,
+ type: record.type,
+ variant: record.variant ?? null,
+ };
+ }
+ return identities;
+};
+
+/**
+ * Builds every case's graph over `models`, or rejects naming the case that cannot compile, with the records' read
+ * error, or once `signal` aborts. `models` are the records the server holds now, still being read when the compiler
+ * is called, so it can fetch what else it needs meanwhile. Generation owns graph compilation and depends on Models,
+ * so App supplies this; its implementation loads lazily on first call.
+ */
+export type CalibrationGraphCompiler = (
+ cases: readonly WorkingMemoryCase[],
+ models: Promise<readonly ModelConfig[]>,
+ signal: AbortSignal
+) => Promise<CalibrationGraph[]>;
+
+export type CalibrationPhase = 'warm_up' | 'measured';
+
+/** One queue item of an attempt: a case at one repetition. Each step is its own POST and its own server run. */
+export interface CalibrationStep {
+ /** Position in the attempt, which is also the order the server creates the step's run in. */
+ index: number;
+ case: WorkingMemoryCase;
+ phase: CalibrationPhase;
+ /** 1-based within the phase. */
+ repetition: number;
+}
+
+/**
+ * The plan's cases grouped by line (one decode dtype each), each case's warm-ups right before its measured runs.
+ * Grouping keeps one precision switch per dtype: the first decode after a switch recasts the VAE, and the server
+ * excludes those windows, so a switch must land on a warm-up.
+ */
+export const planCalibrationSteps = (plan: Pick<WorkingMemoryPlan, 'cases' | 'repetitions'>): CalibrationStep[] => {
+ const groups = new Map<string, WorkingMemoryCase[]>();
+
+ for (const item of plan.cases) {
+ const group = groups.get(item.line);
+
+ if (group) {
+ group.push(item);
+ } else {
+ groups.set(item.line, [item]);
+ }
+ }
+
+ const steps: CalibrationStep[] = [];
+ const push = (item: WorkingMemoryCase, phase: CalibrationPhase, count: number) => {
+ for (let repetition = 1; repetition <= count; repetition += 1) {
+ steps.push({ case: item, index: steps.length, phase, repetition });
+ }
+ };
+
+ for (const cases of groups.values()) {
+ for (const item of cases) {
+ push(item, 'warm_up', plan.repetitions.warm_up);
+ push(item, 'measured', plan.repetitions.measured);
+ }
+ }
+
+ return steps;
+};
+
+/**
+ * Whether a plan read again when a calibration is confirmed asks for another calibration than the one confirmed: other
+ * lines (an operation in another dtype), or another number of runs. The sizes follow the GPU memory free when the plan
+ * is read, which a running generation moves by its working set, so new sizes alone are no reason to ask again.
+ */
+export const changesCalibration = (
+ confirmed: Pick<WorkingMemoryPlan, 'cases' | 'repetitions'>,
+ current: Pick<WorkingMemoryPlan, 'cases' | 'repetitions'>
+): boolean => {
+ const linesOf = (plan: Pick<WorkingMemoryPlan, 'cases'>) =>
+ [...new Set(plan.cases.map((item) => `${item.estimator}\u0000${item.line}`))].sort().join('\u0001');
+
+ return (
+ linesOf(confirmed) !== linesOf(current) ||
+ planCalibrationSteps(confirmed).length !== planCalibrationSteps(current).length
+ );
+};
+
+/**
+ * The retry key of one step. Resending a step after a lost response with the same key returns the run the first
+ * request created. The key carries the attempt id: the server keys its retry receipts on the key alone, so a key
+ * reused by a new attempt would be refused.
+ */
+export const calibrationIdempotencyKey = (attemptId: string, step: CalibrationStep): string =>
+ `webv2:wm-calibration:${attemptId}:${String(step.index)}:${step.case.id}:${step.phase}-${String(step.repetition)}`;
+
+const byCreation = (left: WorkingMemoryRun, right: WorkingMemoryRun): number =>
+ Date.parse(left.created_at) - Date.parse(right.created_at);
+
+/** The id of the most recently created run, or null without runs. */
+export const newestRunId = (runs: readonly WorkingMemoryRun[]): string | null =>
+ [...runs].sort(byCreation).at(-1)?.run_id ?? null;
+
+/**
+ * The runs of one attempt, oldest first: those carrying `attemptId`, or by default those of the newest run's attempt.
+ * A run without an attempt id (created before the server stored one) is an attempt of its own.
+ */
+export const selectAttemptRuns = (runs: readonly WorkingMemoryRun[], attemptId?: string): WorkingMemoryRun[] => {
+ const ordered = [...runs].sort(byCreation);
+ const newest = ordered.at(-1);
+ const target = attemptId ?? newest?.attempt_id ?? null;
+
+ if (target === null) {
+ return newest ? [newest] : [];
+ }
+
+ return ordered.filter((run) => run.attempt_id === target);
+};
+
+/**
+ * Why the server refused a calibration's step, where the section says it in its own words: another attempt is
+ * running on this GPU, the model's record changed after the graphs were compiled over it, or another calibration ran
+ * on this GPU between this attempt's steps (`interleaved`), whose later steps then no longer combine with its earlier
+ * ones.
+ */
+export type CalibrationRefusal = 'alreadyRunning' | 'interleaved' | 'modelChanged';
+
+/** What this tab knows of an attempt it started. */
+export interface LocalAttempt {
+ attemptId: string;
+ /** Steps the attempt meant to queue. */
+ total: number;
+ /** Still posting steps. */
+ submitting: boolean;
+ /** Why posting stopped early, when it did. */
+ submissionError: string | null;
+ /** The refusal that error was, when the server named one. */
+ submissionRefusal?: CalibrationRefusal;
+ /** The user stopped it. */
+ stopped: boolean;
+ /**
+ * The newest of the model's runs this tab knew when the attempt started. While the attempt has no runs of its own
+ * (it failed before queuing anything), it is the latest attempt only until a newer run appears.
+ */
+ newestRunAtStart: string | null;
+}
+
+export type CalibrationActivity =
+ | { kind: 'idle' }
+ | {
+ kind: 'running';
+ /** Steps settled so far. */
+ done: number;
+ total: number;
+ /** The case the queue is running or about to run, when it can be told. */
+ currentCase: WorkingMemoryCase | null;
+ /** Still posting steps. */
+ queuing: boolean;
+ };
+
+/**
+ * `discarded`: the attempt measured something, but the server aborted it (stopped, a run canceled, or its queuing
+ * ended early), so none of its windows feeds a fit. A run that failed does not abort it: `kept` says that the other
+ * steps measured something, which still counts.
+ */
+export type CalibrationOutcome =
+ | { kind: 'none' }
+ | { kind: 'completed' }
+ /** Every run was canceled before it measured anything, so nothing was discarded. */
+ | { kind: 'canceled' }
+ /** `canceled`: runs were canceled, so the attempt did not stop because queuing ended early. */
+ | {
+ kind: 'partial';
+ canceled: boolean;
+ discarded: boolean;
+ error: string | null;
+ /** The refusal that `error` was, when the server named one. */
+ refusal?: CalibrationRefusal;
+ queued: number;
+ total: number;
+ }
+ | { kind: 'failed'; discarded: boolean; error: string | null; kept: boolean; refusal?: CalibrationRefusal };
+
+/**
+ * Progress and the latest attempt's outcome. A run counts as running while any of its items is pending or running
+ * (the server derives that from the queue), so a pending item blocks a second start across reloads and tabs.
+ */
+export const deriveCalibrationProgress = ({
+ local,
+ runs,
+ steps,
+}: {
+ local: LocalAttempt | null;
+ runs: readonly WorkingMemoryRun[];
+ steps: readonly CalibrationStep[];
+}): { activity: CalibrationActivity; outcome: CalibrationOutcome } => {
+ // Another tab may have started a newer attempt since; this tab's record then describes an older one. A record whose
+ // attempt queued nothing (it failed to compile or to post its first step) stays current until a newer run exists.
+ const newest = [...runs].sort(byCreation).at(-1);
+ const current =
+ local !== null &&
+ (local.submitting ||
+ (newest !== undefined && newest.attempt_id === local.attemptId) ||
+ (!runs.some((run) => run.attempt_id === local.attemptId) &&
+ (newest?.run_id ?? null) === local.newestRunAtStart &&
+ !runs.some((run) => run.status === 'running')))
+ ? local
+ : null;
+ const attempt = selectAttemptRuns(runs, current?.attemptId);
+ // The attempt's own step count: this tab's record, else the one the server stored with its runs, so any tab can tell
+ // an attempt whose queuing ended early (a reload, a closed tab) from a complete one. A running attempt with neither
+ // is assumed to follow the current plan; a settled one is judged by its runs alone, since the plan may have changed.
+ const planned = current?.total ?? attempt.find((run) => run.attempt_steps !== null)?.attempt_steps ?? null;
+ const total = Math.max(planned ?? steps.length, attempt.length);
+ const plannedTotal = planned ?? attempt.length;
+ const runningIndex = attempt.findIndex((run) => run.status === 'running');
+ const queuing = current?.submitting ?? false;
+
+ if (queuing || runningIndex !== -1) {
+ // Steps settle in order: the queue runs an attempt's items first in, first out.
+ const done = attempt.filter((run) => run.status !== 'running').length;
+ const currentIndex = runningIndex === -1 ? attempt.length : runningIndex;
+
+ return {
+ activity: { currentCase: steps[currentIndex]?.case ?? null, done, kind: 'running', queuing, total },
+ outcome: { kind: 'none' },
+ };
+ }
+
+ const idle: CalibrationActivity = { kind: 'idle' };
+ const canceled =
+ (current?.stopped ?? false) || attempt.some((run) => run.status === 'canceled' || run.status === 'partial');
+ // Once the attempt settled, the server alone says whether it discards the attempt's windows: a Stop that came after
+ // the last step finished cancels nothing, and a step whose response was lost may still have been recorded. Before
+ // the summary lists the attempt's runs, nothing of it was measured, so nothing reads as discarded either. Measured
+ // means a run that completed, or partly did: `point_count` also counts the invalid windows of a decode that failed
+ // or was canceled.
+ const measured = attempt.some((run) => run.status === 'completed' || run.status === 'partial');
+ const aborted = attempt.some((run) => run.held_back === 'aborted_attempt');
+ const discarded = measured && aborted;
+ const partial = (error: string | null, refusal?: CalibrationRefusal): CalibrationOutcome => ({
+ canceled,
+ discarded,
+ error,
+ kind: 'partial',
+ queued: attempt.length,
+ refusal,
+ total: plannedTotal,
+ });
+
+ // A submission error stands until the server lists every step this tab meant to queue: then the step whose answer
+ // failed was recorded after all (a lost response, a 503 after queuing), and the runs alone tell the outcome.
+ if (current?.submissionError && attempt.length < plannedTotal) {
+ return {
+ activity: idle,
+ outcome:
+ attempt.length === 0
+ ? {
+ discarded,
+ error: current.submissionError,
+ kept: false,
+ kind: 'failed',
+ refusal: current.submissionRefusal,
+ }
+ : partial(current.submissionError, current.submissionRefusal),
+ };
+ }
+
+ if (attempt.length === 0) {
+ return { activity: idle, outcome: current?.stopped ? { kind: 'canceled' } : { kind: 'none' } };
+ }
+
+ // A model of the graph changed after the attempt was planned: its items fail as they are admitted, and the section
+ // says so in its own words rather than the server's.
+ const failed =
+ attempt.find((run) => run.status === 'failed' && run.error_code === 'model_changed') ??
+ attempt.find((run) => run.status === 'failed');
+
+ if (failed) {
+ const modelChanged = failed.error_code === 'model_changed';
+
+ return {
+ activity: idle,
+ outcome: {
+ discarded,
+ error: failed.error,
+ // What earlier steps measured is of a model that has changed since: no claim that it still counts.
+ kept: measured && !aborted && !modelChanged,
+ kind: 'failed',
+ refusal: modelChanged ? 'modelChanged' : undefined,
+ },
+ };
+ }
+
+ if (attempt.every((run) => run.status === 'canceled')) {
+ return { activity: idle, outcome: { kind: 'canceled' } };
+ }
+
+ if (attempt.every((run) => run.status === 'completed') && attempt.length >= plannedTotal) {
+ return { activity: idle, outcome: { kind: 'completed' } };
+ }
+
+ return { activity: idle, outcome: partial(null) };
+};
+
+/**
+ * How a line reads: its server state, or `interrupted` for a line that only aborted attempts measured (Stop, a queue
+ * clear, a failed submission, a changed model). The server calls that line `insufficient`, but its cause is the
+ * interruption, not a lack of sizes.
+ */
+export type LineDisplayState = WorkingMemoryLineState | 'interrupted';
+
+export const lineDisplayState = (line: Pick<WorkingMemoryLine, 'sizes' | 'state'>): LineDisplayState =>
+ line.state === 'insufficient' &&
+ line.sizes.length > 0 &&
+ line.sizes.every((size) => size.excluded_reason === 'aborted_attempt')
+ ? 'interrupted'
+ : line.state;
+
+const LINE_STATE_SEVERITY: readonly LineDisplayState[] = ['unusable', 'stale', 'insufficient', 'interrupted', 'in_use'];
+
+/** The most severe of the lines' display states, or null without lines. */
+export const summarizeLineStates = (states: readonly LineDisplayState[]): LineDisplayState | null =>
+ LINE_STATE_SEVERITY.find((state) => states.includes(state)) ?? null;
+
+/** What a summary says about the model as a whole. */
+export interface CalibrationCoverage {
+ /** The headline state: of the current environment's lines, or of all lines when it has none. */
+ state: LineDisplayState | null;
+ /** Some line of the current environment exists, measured by this model or another. */
+ hasCurrentLines: boolean;
+ /** This model has windows on some line or has runs, so a reset removes something. */
+ hasOwnMeasurements: boolean;
+ /** Estimates use lines that only other models measured. */
+ usesOthersOnly: boolean;
+}
+
+export const describeCoverage = (
+ summary: {
+ current_env_id: string | null;
+ lines: readonly Pick<
+ WorkingMemoryLine,
+ 'env_id' | 'estimator' | 'line' | 'own_windows' | 'sizes' | 'state' | 'version'
+ >[];
+ runs: readonly unknown[];
+ } | null
+): CalibrationCoverage => {
+ const lines = summary?.lines ?? [];
+ const current = lines.filter((line) => line.env_id === summary?.current_env_id);
+ const hasOwnWindows = lines.some((line) => line.own_windows > 0);
+ const applies = (line: (typeof lines)[number]) => line.state === 'in_use' || line.state === 'stale';
+ // An estimator update leaves the old version's windows as an unusable line; once the new version's line applies,
+ // the old one is superseded and does not head the section.
+ const headline = current.filter(
+ (line) =>
+ line.state !== 'unusable' ||
+ !current.some(
+ (other) =>
+ other.estimator === line.estimator &&
+ other.line === line.line &&
+ other.version !== line.version &&
+ applies(other)
+ )
+ );
+
+ return {
+ hasCurrentLines: current.length > 0,
+ hasOwnMeasurements: hasOwnWindows || (summary?.runs.length ?? 0) > 0,
+ state: summarizeLineStates((current.length > 0 ? headline : lines).map(lineDisplayState)),
+ usesOthersOnly: !hasOwnWindows && current.some(applies),
+ };
+};
+
+/** A line's contributors with this model first, the rest in the server's order (by name). */
+export const orderContributors = (
+ contributors: readonly WorkingMemoryLineContributor[],
+ modelKey: string
+): WorkingMemoryLineContributor[] => [
+ ...contributors.filter((entry) => entry.model_key === modelKey),
+ ...contributors.filter((entry) => entry.model_key !== modelKey),
+];
+
+export type CalibrationBlocker =
+ | { kind: 'unsupported'; reason: string | null }
+ | { kind: 'unavailable'; reason: string | null }
+ | { kind: 'storeUnusable'; reason: string | null }
+ | { kind: 'running' };
+
+/**
+ * Why Calibrate is unavailable, in the order a user can act on: nothing helps an unsupported model; a missing or
+ * second GPU and an unusable store are machine problems; a running attempt only needs to finish.
+ */
+export const getCalibrationBlocker = ({
+ isRunning,
+ plan,
+ status,
+ summary,
+}: {
+ isRunning: boolean;
+ plan: Pick<WorkingMemoryPlan, 'reason' | 'supported'>;
+ status: Pick<WorkingMemoryStatus, 'available' | 'unavailable_reason'>;
+ /** Null when the server has no current device class to summarise. */
+ summary: Pick<WorkingMemorySummary, 'problem' | 'usable'> | null;
+}): CalibrationBlocker | null => {
+ if (!plan.supported) {
+ return { kind: 'unsupported', reason: plan.reason };
+ }
+
+ if (summary && !summary.usable) {
+ return { kind: 'storeUnusable', reason: summary.problem };
+ }
+
+ if (!status.available || summary === null) {
+ return { kind: 'unavailable', reason: status.unavailable_reason };
+ }
+
+ return isRunning ? { kind: 'running' } : null;
+};
+
+/**
+ * The model whose calibration attempt holds this GPU, as the status lists it, or null. The server takes one attempt
+ * per device class at a time; a run without an attempt holds nothing. An attempt between its steps runs nothing and
+ * reads as free here: the status cannot tell it from an abandoned one, which the server judges by its last activity.
+ * The server's refusal covers that gap of seconds.
+ */
+export const modelCalibratingOnGpu = (status: Pick<WorkingMemoryStatus, 'device_classes'>): string | null =>
+ status.device_classes
+ .find((entry) => entry.is_current)
+ ?.runs.find((run) => run.status === 'running' && run.attempt_id !== null)?.model_key ?? null;
+
+/**
+ * Whether the server's way of measuring GPU memory was checked against real hardware on this GPU's backend: the
+ * model summary's answer, else the current device class's; null while neither can tell.
+ */
+export const isMeasurementMethodVerified = (
+ summary: Pick<WorkingMemorySummary, 'measurement_verified'> | null,
+ status: WorkingMemoryStatus
+): boolean | null =>
+ summary?.measurement_verified ??
+ status.device_classes.find((entry) => entry.is_current)?.measurement_verified ??
+ null;
+
+/** `decode_fp16` → operation `decode`, dtype `fp16`. A line without a dtype suffix keeps its whole name. */
+export const splitLine = (line: string): { dtype: string | null; operation: string } => {
+ const separator = line.lastIndexOf('_');
+
+ return separator <= 0
+ ? { dtype: null, operation: line }
+ : { dtype: line.slice(separator + 1), operation: line.slice(0, separator) };
+};
+
+/** Changed facts the section names with a translated label. */
+export type TranslatedFact = 'allocator' | 'driver' | 'invokeai' | 'osBuild' | 'sdpaGuard' | 'torchBuild';
+
+/** Facts named by a product or runtime name, which needs no translation. */
+const FACT_NAMES: Readonly<Record<string, string>> = {
+ cuda: 'CUDA',
+ cudnn: 'cuDNN',
+ hip: 'ROCm',
+ miopen: 'MIOpen',
+ os: 'OS',
+ torch: 'PyTorch',
+ xpu: 'XPU runtime',
+};
+
+const TRANSLATED_FACTS: Readonly<Record<string, TranslatedFact>> = {
+ allocator_backend: 'allocator',
+ driver: 'driver',
+ invokeai: 'invokeai',
+ os_build: 'osBuild',
+ rocm_sdpa_guard: 'sdpaGuard',
+ torch_build: 'torchBuild',
+};
+
+/**
+ * How the section names a changed environment fact (the server's fingerprint keys): a product name, a translated
+ * label, or for environment variables and Invoke settings their own name. An unknown key shows as sent.
+ */
+export const describeFact = (key: string): { name: string } | { translated: TranslatedFact } => {
+ const translated = TRANSLATED_FACTS[key];
+
+ if (translated) {
+ return { translated };
+ }
+
+ for (const prefix of ['env.', 'setting.']) {
+ if (key.startsWith(prefix) && key.length > prefix.length) {
+ return { name: key.slice(prefix.length) };
+ }
+ }
+
+ return { name: FACT_NAMES[key] ?? key };
+};
diff --git a/invokeai/frontend/webv2/src/features/models/data/workingMemoryApi.test.ts b/invokeai/frontend/webv2/src/features/models/data/workingMemoryApi.test.ts
new file mode 100644
index 0000000000..91e88fc4b9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/data/workingMemoryApi.test.ts
@@ -0,0 +1,38 @@
+import { expect, it, vi } from 'vitest';
+
+import type { ModelsDataPort } from './transport';
+
+const requestJson = vi.hoisted(() => vi.fn((_path: string, _init?: RequestInit) => Promise.resolve({})));
+
+vi.mock('./transport', () => ({
+ browserModelsDataPort: {
+ buildUrl: (path: string) => path,
+ request: vi.fn(),
+ requestJson: requestJson as unknown as ModelsDataPort['requestJson'],
+ } satisfies ModelsDataPort,
+}));
+
+const { calibrateWorkingMemory } = await import('./workingMemoryApi');
+
+it('sends the attempt id with its step count and the compiled model identities, in the server field names', async () => {
+ await calibrateWorkingMemory('sdxl main', {
+ attemptId: 'attempt-1',
+ attemptSteps: 18,
+ data: [],
+ graph: { id: 'case' },
+ graphModels: { sdxl: { base: 'sdxl', format: 'diffusers', hash: 'blake3:sdxl', type: 'main', variant: null } },
+ idempotencyKey: 'key-0',
+ });
+
+ const [path, init] = requestJson.mock.calls[0]!;
+ expect(path).toBe('/api/v2/models/i/sdxl%20main/working_memory/calibrate');
+ expect(init?.method).toBe('POST');
+ expect(JSON.parse(init?.body as string)).toEqual({
+ attempt_id: 'attempt-1',
+ attempt_steps: 18,
+ data: [],
+ graph: { id: 'case' },
+ graph_models: { sdxl: { base: 'sdxl', format: 'diffusers', hash: 'blake3:sdxl', type: 'main', variant: null } },
+ idempotency_key: 'key-0',
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/data/workingMemoryApi.ts b/invokeai/frontend/webv2/src/features/models/data/workingMemoryApi.ts
new file mode 100644
index 0000000000..9d14952839
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/data/workingMemoryApi.ts
@@ -0,0 +1,89 @@
+import type {
+ CalibrationCompiledModel,
+ WorkingMemoryPlan,
+ WorkingMemoryRunCreated,
+ WorkingMemoryStatus,
+ WorkingMemorySummary,
+} from '@features/models/core/workingMemory';
+
+import { calibrationRunOrigin } from '@features/models/core/workingMemory';
+
+import { browserModelsDataPort } from './transport';
+
+/** REST client for working-memory calibration, admin-only on the server. */
+
+const { request, requestJson } = browserModelsDataPort;
+
+const modelPath = (key: string): string => `/api/v2/models/i/${encodeURIComponent(key)}/working_memory`;
+
+/** Calibration items are ordinary queue items; the queue routes act on them by origin. */
+const QUEUE_BASE = '/api/v1/queue/default';
+
+export const getWorkingMemoryPlan = (key: string, signal?: AbortSignal): Promise<WorkingMemoryPlan> =>
+ requestJson<WorkingMemoryPlan>(`${modelPath(key)}/plan`, { signal });
+
+/** 409 when there is no current device class (no GPU, or several generation devices). */
+export const getWorkingMemorySummary = (key: string, signal?: AbortSignal): Promise<WorkingMemorySummary> =>
+ requestJson<WorkingMemorySummary>(`${modelPath(key)}/summary`, { signal });
+
+export const getWorkingMemoryStatus = (signal?: AbortSignal): Promise<WorkingMemoryStatus> =>
+ requestJson<WorkingMemoryStatus>('/api/v2/models/working_memory/status', { signal });
+
+export interface CalibrateRequest {
+ /** Groups the runs of one Calibrate click; the server returns it on every run. */
+ attemptId: string;
+ /**
+ * How many runs the attempt queues, the same on every one of them. The server counts an attempt that ends with fewer
+ * as aborted and never fits its windows.
+ */
+ attemptSteps: number;
+ graph: unknown;
+ /**
+ * Every model the graph names, as the records it was compiled over have them (`CompiledCalibration.models`). The
+ * server refuses the step as `model_changed` when a record differs now.
+ */
+ graphModels: Readonly<Record<string, CalibrationCompiledModel>>;
+ data: unknown;
+ idempotencyKey: string;
+}
+
+/** Enqueues one queue item as one server run. Resending with the same key returns that run and enqueues nothing. */
+export const calibrateWorkingMemory = (
+ key: string,
+ { attemptId, attemptSteps, data, graph, graphModels, idempotencyKey }: CalibrateRequest,
+ signal?: AbortSignal
+): Promise<WorkingMemoryRunCreated> =>
+ requestJson<WorkingMemoryRunCreated>(`${modelPath(key)}/calibrate`, {
+ body: JSON.stringify({
+ attempt_id: attemptId,
+ attempt_steps: attemptSteps,
+ data,
+ graph,
+ graph_models: graphModels,
+ idempotency_key: idempotencyKey,
+ }),
+ method: 'POST',
+ signal,
+ });
+
+/** Releases the server's receipt for a key whose response arrived; until then it counts toward a per-owner limit. */
+export const acknowledgeCalibrationEnqueue = async (idempotencyKey: string, signal?: AbortSignal): Promise<void> => {
+ await request(`${QUEUE_BASE}/enqueue_batch/acknowledge`, {
+ body: JSON.stringify({ idempotency_key: idempotencyKey }),
+ headers: { 'Content-Type': 'application/json' },
+ method: 'POST',
+ signal,
+ });
+};
+
+/** Cancels a run's items, the running one included. */
+export const cancelCalibrationRun = async (runId: string, signal?: AbortSignal): Promise<void> => {
+ const params = new URLSearchParams({ origin_prefix: calibrationRunOrigin(runId) });
+
+ await request(`${QUEUE_BASE}/cancel_all?${params.toString()}`, { method: 'PUT', signal });
+};
+
+/** Removes the model's runs and measurements on the current device class. */
+export const resetWorkingMemory = async (key: string, signal?: AbortSignal): Promise<void> => {
+ await request(modelPath(key), { method: 'DELETE', signal });
+};
diff --git a/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.test.ts b/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.test.ts
new file mode 100644
index 0000000000..0f296590fe
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.test.ts
@@ -0,0 +1,257 @@
+import type { ModelConfig } from '@features/models/core/types';
+import type {
+ CalibrationGraphCompiler,
+ WorkingMemoryPlan,
+ WorkingMemoryRunCreated,
+} from '@features/models/core/workingMemory';
+import type { ConnectionListener } from '@platform/transport/socketHub';
+
+import { QueryClient, QueryObserver } from '@tanstack/react-query';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ModelsApi from './api';
+import type { CalibrateRequest } from './workingMemoryApi';
+
+const hub = vi.hoisted(() => ({ statusChanged: null as ((payload: unknown) => void) | null }));
+
+vi.mock('@platform/transport/socketHub', () => ({
+ socketHub: {
+ on: (event: string, listener: (payload: unknown) => void) => {
+ if (event === 'queue_item_status_changed') {
+ hub.statusChanged = listener;
+ }
+ return () => {
+ hub.statusChanged = null;
+ };
+ },
+ onConnectionChange: (listener: ConnectionListener) => {
+ listener('connected');
+ return () => undefined;
+ },
+ },
+}));
+
+const api = vi.hoisted(() => ({
+ acknowledgeCalibrationEnqueue: vi.fn((_idempotencyKey: string, _signal?: AbortSignal) => Promise.resolve()),
+ calibrateWorkingMemory:
+ vi.fn<(modelKey: string, request: CalibrateRequest, signal?: AbortSignal) => Promise<WorkingMemoryRunCreated>>(),
+ cancelCalibrationRun: vi.fn(),
+ getWorkingMemoryPlan: vi.fn(),
+ getWorkingMemoryStatus: vi.fn(),
+ getWorkingMemorySummary: vi.fn(),
+ resetWorkingMemory: vi.fn(),
+}));
+
+vi.mock('./workingMemoryApi', () => api);
+
+/** The model records the server holds, which a compile reads. */
+const library = vi.hoisted(() => ({ models: [] as unknown[] }));
+
+vi.mock('./api', async (importOriginal) => ({
+ ...(await importOriginal<typeof ModelsApi>()),
+ listModels: () => Promise.resolve(library.models),
+}));
+
+const { attachWorkingMemoryRealtime, compileWorkingMemoryPlan, startCalibration } =
+ await import('./workingMemoryCalibration');
+const { workingMemoryKeys } = await import('./workingMemoryQueries');
+const { calibrationRunOrigin } = await import('@features/models/core/workingMemory');
+const { accountLifecycle, captureAccountScope } = await import('@platform/state/accountLifecycle');
+const { ApiError } = await import('@platform/transport/http');
+
+let queryClient: QueryClient;
+let detach: () => void;
+
+beforeEach(() => {
+ accountLifecycle.activate('wm-realtime-test', ':user:wm-realtime-test');
+ queryClient = new QueryClient();
+ detach = attachWorkingMemoryRealtime(queryClient);
+});
+
+afterEach(() => {
+ detach();
+ queryClient.clear();
+ accountLifecycle.invalidate();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+it("marks every model's plan stale when a calibration item changes status, without reading one then", () => {
+ const owner = captureAccountScope();
+ const plans = [workingMemoryKeys.plan(owner, 'sdxl'), workingMemoryKeys.plan(owner, 'flux')];
+ const read = vi.fn(() => Promise.resolve({}));
+ const unsubscribe = plans.map((key) => {
+ queryClient.setQueryData(key, { supported: true });
+ // An observed plan, as an open section has: an invalidation that refetched would read it now.
+ return new QueryObserver(queryClient, { queryFn: read, queryKey: key, staleTime: Infinity }).subscribe(
+ () => undefined
+ );
+ });
+
+ hub.statusChanged?.({ origin: 'generation' });
+ expect(plans.map((key) => queryClient.getQueryState(key)?.isInvalidated)).toEqual([false, false]);
+
+ hub.statusChanged?.({ origin: calibrationRunOrigin('run-1'), status: 'completed' });
+
+ expect(plans.map((key) => queryClient.getQueryState(key)?.isInvalidated)).toEqual([true, true]);
+ expect(read).not.toHaveBeenCalled();
+ for (const stop of unsubscribe) {
+ stop();
+ }
+});
+
+describe('posting the steps of a calibration', () => {
+ const MODEL_KEY = 'sdxl';
+ // One case, one warm-up and two measured runs: three steps.
+ const PLAN: WorkingMemoryPlan = {
+ calibrated_through: null,
+ cases: [
+ {
+ components: {},
+ estimator: 'sdxl_vae_decode',
+ height: 512,
+ id: 'sdxl_vae_decode-decode-fp16-512x512',
+ line: 'decode_fp16',
+ mode: 'txt2img',
+ model_key: MODEL_KEY,
+ negative_prompt: '',
+ positive_prompt: 'a lake',
+ seed: 1,
+ settings: { vaePrecision: 'fp16' },
+ steps: 2,
+ width: 512,
+ },
+ ],
+ device_class: { id: '0123456789abcdef', name: 'Fixture GPU' },
+ estimated_seconds: 60,
+ estimators: ['sdxl_vae_decode'],
+ model_key: MODEL_KEY,
+ not_covered: [],
+ reason: null,
+ repetitions: { measured: 2, warm_up: 1 },
+ shared_with: [],
+ supported: true,
+ };
+ const graphs = PLAN.cases.map((item) => ({ caseId: item.id, data: [], graph: { id: item.id }, models: {} }));
+
+ /**
+ * Answers like the server: a new key queues its items once, a repeat of a key returns the run it queued. The first
+ * `times` requests of the first key get `failure` once its items are queued, as a failed store write does.
+ */
+ const serve = (failure: InstanceType<typeof ApiError>, times = 1) => {
+ const queued = new Map<string, WorkingMemoryRunCreated>();
+ let firstKeyRequests = 0;
+ api.calibrateWorkingMemory.mockImplementation((_modelKey, request) => {
+ const known = queued.get(request.idempotencyKey);
+ const created = known ?? {
+ device_class_id: PLAN.device_class!.id,
+ item_ids: [queued.size + 1],
+ run_id: `run-${String(queued.size + 1)}`,
+ };
+ queued.set(request.idempotencyKey, created);
+
+ if (queued.size === 1) {
+ firstKeyRequests += 1;
+ }
+ return queued.size === 1 && firstKeyRequests <= times ? Promise.reject(failure) : Promise.resolve(created);
+ });
+ return queued;
+ };
+
+ const postedKeys = () => api.calibrateWorkingMemory.mock.calls.map(([, request]) => request.idempotencyKey);
+
+ it('names the attempt and the step count it plans on every step, so the server can tell an aborted attempt', async () => {
+ serve(new ApiError('{"detail":"unused"}', 503), 0);
+
+ await startCalibration({ graphs, modelKey: MODEL_KEY, plan: PLAN, queryClient });
+
+ const requests = api.calibrateWorkingMemory.mock.calls.map(([, request]) => request);
+ expect(requests).toHaveLength(3);
+ expect(requests.map((request) => request.attemptSteps)).toEqual([3, 3, 3]);
+ expect(new Set(requests.map((request) => request.attemptId)).size).toBe(1);
+ });
+
+ it('posts the identities of the records the graphs compiled over, not of a later read', async () => {
+ serve(new ApiError('{"detail":"unused"}', 503), 0);
+ const record = (variant: string) =>
+ ({
+ base: 'flux2',
+ format: 'diffusers',
+ hash: 'blake3:flux2',
+ key: MODEL_KEY,
+ name: 'FLUX.2',
+ type: 'main',
+ variant,
+ }) as ModelConfig;
+ // Like Generate's compiler, it names the model as the records it was given have it. Another tab edits the model's
+ // variant once they were read, before the steps are posted.
+ const compile: CalibrationGraphCompiler = async (cases, models) => {
+ const [model] = await models;
+ const named = { base: model!.base, hash: model!.hash, key: model!.key, name: model!.name, type: model!.type };
+ library.models = [record('klein_9b')];
+
+ return cases.map((item) => ({
+ caseId: item.id,
+ data: [],
+ graph: { id: item.id, nodes: { loader: { id: 'loader', model: named, type: 'flux2_model_loader' } } },
+ }));
+ };
+ library.models = [record('klein_4b')];
+ const compiled = await compileWorkingMemoryPlan(compile, PLAN);
+ await startCalibration({ graphs: compiled, modelKey: MODEL_KEY, plan: PLAN, queryClient });
+
+ const posted = api.calibrateWorkingMemory.mock.calls.map(([, request]) => request.graphModels);
+ const compiledIdentity = {
+ base: 'flux2',
+ format: 'diffusers',
+ hash: 'blake3:flux2',
+ type: 'main',
+ variant: 'klein_4b',
+ };
+ expect(posted).toEqual([1, 2, 3].map(() => ({ [MODEL_KEY]: compiledIdentity })));
+ });
+
+ it('repeats a step the server answered with 503 after queuing it, with the same key, then posts the later steps', async () => {
+ vi.useFakeTimers();
+ const queued = serve(new ApiError('{"detail":"The calibration store is locked"}', 503));
+
+ const started = startCalibration({ graphs, modelKey: MODEL_KEY, plan: PLAN, queryClient });
+ await vi.runAllTimersAsync();
+ await started;
+
+ const keys = postedKeys();
+ // The first step twice under one key, then each later step once.
+ expect(keys).toHaveLength(4);
+ expect(keys[1]).toBe(keys[0]);
+ expect(new Set(keys).size).toBe(3);
+ expect(queued.size).toBe(3);
+ // Every step's response arrived, so every key is acknowledged once.
+ expect(api.acknowledgeCalibrationEnqueue.mock.calls.map(([key]) => key)).toEqual([...new Set(keys)]);
+ });
+
+ it('gives up on a step the server keeps answering with 503 after three requests, posting no later step', async () => {
+ vi.useFakeTimers();
+ serve(new ApiError('{"detail":"The calibration store is locked"}', 503), Infinity);
+
+ const started = startCalibration({ graphs, modelKey: MODEL_KEY, plan: PLAN, queryClient });
+ await vi.runAllTimersAsync();
+ await started;
+
+ const keys = postedKeys();
+ expect(keys).toHaveLength(3);
+ expect(new Set(keys).size).toBe(1);
+ expect(api.acknowledgeCalibrationEnqueue).not.toHaveBeenCalled();
+ });
+
+ it('stops at any other answer of the server without repeating it or posting the later steps', async () => {
+ vi.useFakeTimers();
+ serve(new ApiError('{"detail":"The queue has no room for the run"}', 409));
+
+ const started = startCalibration({ graphs, modelKey: MODEL_KEY, plan: PLAN, queryClient });
+ await vi.runAllTimersAsync();
+ await started;
+
+ expect(postedKeys()).toHaveLength(1);
+ expect(api.acknowledgeCalibrationEnqueue).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.ts b/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.ts
new file mode 100644
index 0000000000..e8d2d07b9c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/data/workingMemoryCalibration.ts
@@ -0,0 +1,424 @@
+import type { QueryClient } from '@tanstack/react-query';
+
+import {
+ calibrationIdempotencyKey,
+ compiledModelIdentities,
+ isCalibrationOrigin,
+ modelCalibratingOnGpu,
+ newestRunId,
+ planCalibrationSteps,
+ type CalibrationGraphCompiler,
+ type CalibrationRefusal,
+ type CompiledCalibration,
+ type LocalAttempt,
+ type WorkingMemoryPlan,
+ type WorkingMemoryRunCreated,
+ type WorkingMemorySummary,
+} from '@features/models/core/workingMemory';
+import { createUuid } from '@platform/browser/randomUuid';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+ registerAccountOwnedResource,
+ type AccountScope,
+} from '@platform/state/accountLifecycle';
+import { createExternalStore } from '@platform/state/externalStore';
+import { ApiError, getApiErrorCode, getApiErrorMessage, sleep } from '@platform/transport/http';
+import { socketHub } from '@platform/transport/socketHub';
+
+import { listModels } from './api';
+import {
+ acknowledgeCalibrationEnqueue,
+ calibrateWorkingMemory,
+ cancelCalibrationRun,
+ resetWorkingMemory,
+ type CalibrateRequest,
+} from './workingMemoryApi';
+import {
+ workingMemoryKeys,
+ workingMemoryPlanQueryOptions,
+ workingMemoryStatusQueryOptions,
+ workingMemorySummaryQueryOptions,
+} from './workingMemoryQueries';
+
+/**
+ * The calibration attempts this tab started, by model key: what only this tab knows (that it is still posting steps,
+ * how many it meant to post, why it stopped). Every step's run carries the attempt id, so the server's
+ * runs say which runs belong together, after a reload too. Kept outside the section so leaving a model's details
+ * while an attempt queues, and coming back, shows the same attempt.
+ */
+const attemptsStore = createExternalStore<{ byModel: ReadonlyMap<string, LocalAttempt> }>({ byModel: new Map() });
+
+/** How queuing an attempt ended for the tab that asked: `alreadyRunning` when the server refused its first step. */
+export interface CalibrationStart {
+ alreadyRunning: boolean;
+}
+
+interface Flight {
+ promise: Promise<CalibrationStart>;
+ /** Ends queuing before the next step; a step being posted is not aborted, since its run exists once it answers. */
+ stopRequested: boolean;
+}
+
+/** The attempt queuing per model; at most one, so a double click cannot post a second attempt. */
+const flights = new Map<string, Flight>();
+
+registerAccountOwnedResource({
+ clear: () => {
+ for (const flight of flights.values()) {
+ flight.stopRequested = true;
+ }
+ flights.clear();
+ attemptsStore.setSnapshot({ byModel: new Map() });
+ },
+ name: 'working-memory-calibration',
+});
+
+const setAttempt = (modelKey: string, attempt: LocalAttempt | null): void => {
+ const byModel = new Map(attemptsStore.getSnapshot().byModel);
+
+ if (attempt) {
+ byModel.set(modelKey, attempt);
+ } else {
+ byModel.delete(modelKey);
+ }
+
+ attemptsStore.setSnapshot({ byModel });
+};
+
+const updateAttempt = (modelKey: string, attemptId: string, change: (attempt: LocalAttempt) => LocalAttempt) => {
+ const attempt = attemptsStore.getSnapshot().byModel.get(modelKey);
+
+ // A reset or a newer attempt replaced it meanwhile.
+ if (attempt?.attemptId === attemptId) {
+ setAttempt(modelKey, change(attempt));
+ }
+};
+
+export const useLocalAttempt = (modelKey: string): LocalAttempt | null =>
+ attemptsStore.useSelector((snapshot) => snapshot.byModel.get(modelKey) ?? null, Object.is);
+
+/**
+ * The refusals of a step the section explains, by the `code` of the server's structured 409 detail: another attempt
+ * runs on this GPU or is between its steps, another calibration ran on it since this attempt began, or a model the
+ * graph names changed or was removed since it compiled (or since an earlier step). Every other 409 has a plain detail,
+ * which names no code. Each ends the attempt where it stands.
+ */
+const REFUSAL_CODES: Readonly<Record<string, CalibrationRefusal>> = {
+ calibration_interleaved: 'interleaved',
+ calibration_running: 'alreadyRunning',
+ model_changed: 'modelChanged',
+};
+
+const refusalOf = (error: unknown): CalibrationRefusal | undefined =>
+ error instanceof ApiError && error.status === 409 ? REFUSAL_CODES[getApiErrorCode(error) ?? ''] : undefined;
+
+/**
+ * A lost response is resent with the same key, which returns the run the first request created. So is a 503: the
+ * store failed for a passing reason (an unwritable root, a lock timeout), possibly after the items were queued, and a
+ * repeat with the key records them without queuing anything new.
+ */
+const POST_ATTEMPTS = 3;
+const POST_RETRY_DELAY_MS = 1_000;
+
+const postStep = async (
+ modelKey: string,
+ request: CalibrateRequest,
+ signal: AbortSignal
+): Promise<WorkingMemoryRunCreated> => {
+ for (let attempt = 1; ; attempt += 1) {
+ try {
+ return await calibrateWorkingMemory(modelKey, request, signal);
+ } catch (error) {
+ // Any other answer of the server holds for a repeat of the same request.
+ if ((error instanceof ApiError && error.status !== 503) || signal.aborted || attempt >= POST_ATTEMPTS) {
+ throw error;
+ }
+ await sleep(POST_RETRY_DELAY_MS, signal);
+ }
+ }
+};
+
+/**
+ * Every model's summary moves: lines are shared across models, and a reset or new points change their fits. So does
+ * every model's plan, which prices on those fits and sizes for the memory the stored measurements found. Plans are
+ * only marked stale, not read now: a read measures the GPU's free memory, which a calibration that is running or just
+ * ended does not leave as a generation finds it, and a running attempt's progress names its cases from the shown plan.
+ * The next open of a section and the next start read them (`refreshWorkingMemoryPlan`, `fetchCurrentWorkingMemoryPlan`).
+ */
+const invalidateAfterChange = async (queryClient: QueryClient, owner: AccountScope) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: workingMemoryKeys.summaries(owner) }),
+ queryClient.invalidateQueries({ queryKey: workingMemoryKeys.status(owner) }),
+ queryClient.invalidateQueries({ queryKey: workingMemoryKeys.plans(owner), refetchType: 'none' }),
+ ]);
+};
+
+/** Reads the model's plan again if a section shows it, else on its next read: the GPU's free memory may have moved. */
+export const refreshWorkingMemoryPlan = (queryClient: QueryClient, modelKey: string): Promise<void> =>
+ queryClient.invalidateQueries({ queryKey: workingMemoryPlanQueryOptions(modelKey).queryKey });
+
+/**
+ * The model whose calibration holds this GPU as the server sees it now, from any tab, or null when none does
+ * (`modelCalibratingOnGpu`). Read right before an attempt starts, after its graphs compiled; the status query keeps
+ * the read, so the section names that model, or holds a failed read's error, which the section shows. A running
+ * attempt marks every model's summary stale, so an attempt of the shown model appears with its progress.
+ */
+export const calibrationOnGpuNow = async (queryClient: QueryClient): Promise<string | null> => {
+ const owner = captureAccountScope();
+ const busy = modelCalibratingOnGpu(
+ await queryClient.fetchQuery({ ...workingMemoryStatusQueryOptions(owner), staleTime: 0 })
+ );
+
+ if (busy !== null) {
+ await queryClient.invalidateQueries({ queryKey: workingMemoryKeys.summaries(owner) });
+ }
+ return busy;
+};
+
+const fetchCurrentWorkingMemorySummary = (queryClient: QueryClient, modelKey: string, owner: AccountScope) =>
+ queryClient.fetchQuery({
+ ...workingMemorySummaryQueryOptions(modelKey, { isConnected: true, isSubmitting: false }, owner),
+ staleTime: 0,
+ });
+
+/** The model's plan as the server builds it now, for a calibration about to start. Rejects with the read's error. */
+export const fetchCurrentWorkingMemoryPlan = (queryClient: QueryClient, modelKey: string): Promise<WorkingMemoryPlan> =>
+ queryClient.fetchQuery({ ...workingMemoryPlanQueryOptions(modelKey), staleTime: 0 });
+
+/**
+ * The graphs of the plan's cases, as Generate would compile them over the model records the server holds now, each
+ * with the identity of every model it names from those same records; loads the compiler on first use. Each step posts
+ * those identities, never a later read, so the server refuses a step whose models changed since they compiled. Rejects
+ * with the compiler's error, naming the first case that cannot compile, such as one whose model needs a text encoder
+ * that is not installed, or with the error of reading the records. A start needs them, so compiling first is how a
+ * plan the server supports turns out to be one this machine cannot run.
+ */
+export const compileWorkingMemoryPlan = async (
+ compile: CalibrationGraphCompiler,
+ plan: WorkingMemoryPlan,
+ signal?: AbortSignal
+): Promise<CompiledCalibration[]> => {
+ const owner = captureAccountScope();
+ const compileSignal = signal ? AbortSignal.any([owner.signal, signal]) : owner.signal;
+
+ compileSignal.throwIfAborted();
+ // Not this tab's models store: another tab or a script may have changed a record since it loaded, and a model's
+ // base edited under the same key can plan the same SD cases while the run executes as the record the server holds.
+ // Only the records, not the library's missing-file check, which stats every model's files on the server.
+ const records = listModels(compileSignal);
+ // The compiler awaits the records only once it has loaded; until then a failed read must not count as unhandled.
+ void records.catch(() => undefined);
+
+ const graphs = await compile(plan.cases, records, compileSignal);
+ const compiledOver = await records;
+
+ assertAccountScopeCurrent(owner);
+ return graphs.map((compiled) => ({ ...compiled, models: compiledModelIdentities(compiled.graph, compiledOver) }));
+};
+
+/**
+ * Posts every step of the plan with its compiled graph (`compileWorkingMemoryPlan`), in order and each after the last
+ * one's response, so the queue runs them in step order. Every step names the attempt and its step count, so the server
+ * fits the attempt's windows only once all of its steps have run. Stops at the first step that still fails once its
+ * retries are spent: the runs already queued still run, but the server discards the attempt as aborted, and the
+ * section reports it as partial. A first step the server refuses because another attempt runs on this GPU leaves
+ * no record of this one: the section follows what the server lists instead.
+ */
+export const startCalibration = ({
+ graphs,
+ modelKey,
+ plan,
+ queryClient,
+}: {
+ graphs: readonly CompiledCalibration[];
+ modelKey: string;
+ plan: WorkingMemoryPlan;
+ queryClient: QueryClient;
+}): Promise<CalibrationStart> => {
+ const running = flights.get(modelKey);
+
+ if (running) {
+ return running.promise;
+ }
+
+ const owner = captureAccountScope();
+ const steps = planCalibrationSteps(plan);
+ const attemptId = createUuid();
+ const flight: Flight = { promise: Promise.resolve({ alreadyRunning: false }), stopRequested: false };
+ let queued = 0;
+ const byCase = new Map(graphs.map((compiled) => [compiled.caseId, compiled]));
+
+ const known = queryClient.getQueryData<WorkingMemorySummary | null>(workingMemoryKeys.summary(owner, modelKey));
+
+ setAttempt(modelKey, {
+ attemptId,
+ newestRunAtStart: newestRunId(known?.runs ?? []),
+ stopped: false,
+ submissionError: null,
+ submitting: true,
+ total: steps.length,
+ });
+
+ const queue = async () => {
+ for (const step of steps) {
+ if (flight.stopRequested || !isAccountScopeCurrent(owner)) {
+ return;
+ }
+
+ const compiled = byCase.get(step.case.id);
+
+ if (!compiled) {
+ throw new Error(`No graph was built for case ${step.case.id}.`);
+ }
+
+ const idempotencyKey = calibrationIdempotencyKey(attemptId, step);
+ await postStep(
+ modelKey,
+ {
+ attemptId,
+ attemptSteps: steps.length,
+ data: compiled.data,
+ graph: compiled.graph,
+ graphModels: compiled.models,
+ idempotencyKey,
+ },
+ owner.signal
+ );
+
+ queued += 1;
+ assertAccountScopeCurrent(owner);
+ // Best effort: an unacknowledged receipt only expires later.
+ void acknowledgeCalibrationEnqueue(idempotencyKey, owner.signal).catch(() => undefined);
+ void queryClient.invalidateQueries({ queryKey: workingMemoryKeys.summary(owner, modelKey) });
+ }
+ };
+
+ flight.promise = queue()
+ .then(() => ({ alreadyRunning: false }))
+ .catch((error: unknown) => {
+ const refusal = refusalOf(error);
+
+ // Another attempt runs on this GPU: this one queued nothing, so it leaves nothing to report.
+ if (refusal === 'alreadyRunning' && queued === 0) {
+ if (isAccountScopeCurrent(owner)) {
+ setAttempt(modelKey, null);
+ }
+ return { alreadyRunning: true };
+ }
+
+ // A step that fails once a stop was asked for leaves the attempt stopped, not failed.
+ if (isAccountScopeCurrent(owner) && !flight.stopRequested) {
+ updateAttempt(modelKey, attemptId, (attempt) => ({
+ ...attempt,
+ submissionError: getApiErrorMessage(error, ''),
+ submissionRefusal: refusal,
+ }));
+ }
+ return { alreadyRunning: false };
+ })
+ .finally(() => {
+ if (flights.get(modelKey) === flight) {
+ flights.delete(modelKey);
+ }
+
+ if (isAccountScopeCurrent(owner)) {
+ updateAttempt(modelKey, attemptId, (attempt) => ({ ...attempt, submitting: false }));
+ void invalidateAfterChange(queryClient, owner);
+ }
+ });
+ flights.set(modelKey, flight);
+
+ return flight.promise;
+};
+
+/**
+ * Stops queuing, then cancels every run of the model the queue still holds, newest first so no later item starts
+ * while an earlier one is cancelled. Waits for the step in flight: its run exists once the response arrives.
+ */
+export const stopCalibration = async ({
+ modelKey,
+ queryClient,
+}: {
+ modelKey: string;
+ queryClient: QueryClient;
+}): Promise<void> => {
+ const owner = captureAccountScope();
+ const flight = flights.get(modelKey);
+
+ const local = attemptsStore.getSnapshot().byModel.get(modelKey);
+
+ if (local) {
+ updateAttempt(modelKey, local.attemptId, (attempt) => ({ ...attempt, stopped: true }));
+ }
+
+ if (flight) {
+ flight.stopRequested = true;
+ await flight.promise;
+ }
+
+ const summary = await fetchCurrentWorkingMemorySummary(queryClient, modelKey, owner);
+ const running = (summary?.runs ?? [])
+ .filter((run) => run.status === 'running')
+ .sort((left, right) => Date.parse(right.created_at) - Date.parse(left.created_at));
+
+ try {
+ for (const run of running) {
+ await cancelCalibrationRun(run.run_id, owner.signal);
+ }
+ } finally {
+ // Awaited, so a confirmation closing after this sees whether Calibrate is available again.
+ if (isAccountScopeCurrent(owner)) {
+ await invalidateAfterChange(queryClient, owner);
+ }
+ }
+};
+
+/** Removes the model's runs and measurements; the shipped estimates apply again from the next generation on. */
+export const resetCalibration = async ({
+ modelKey,
+ queryClient,
+}: {
+ modelKey: string;
+ queryClient: QueryClient;
+}): Promise<void> => {
+ const owner = captureAccountScope();
+
+ await resetWorkingMemory(modelKey, owner.signal);
+ assertAccountScopeCurrent(owner);
+ setAttempt(modelKey, null);
+ await invalidateAfterChange(queryClient, owner);
+};
+
+/**
+ * Keeps an open section current: a calibration item changing status refreshes the summaries, and a reconnect
+ * refreshes everything, since events during the gap were lost. Polling covers the time without a socket.
+ */
+export const attachWorkingMemoryRealtime = (queryClient: QueryClient): (() => void) => {
+ const owner = captureAccountScope();
+
+ const detachStatus = socketHub.on('queue_item_status_changed', (payload: never) => {
+ const origin = (payload as { origin?: unknown } | null)?.origin;
+
+ if (isCalibrationOrigin(origin) && isAccountScopeCurrent(owner)) {
+ void invalidateAfterChange(queryClient, owner);
+ }
+ });
+
+ // The hub reports the current status on subscribe; only a later transition to connected is a reconnect.
+ let wasConnected: boolean | null = null;
+ const detachConnection = socketHub.onConnectionChange((status) => {
+ const isConnected = status === 'connected';
+
+ if (isConnected && wasConnected === false && isAccountScopeCurrent(owner)) {
+ void queryClient.invalidateQueries({ queryKey: workingMemoryKeys.forAccount(owner) });
+ }
+ wasConnected = isConnected;
+ });
+
+ return () => {
+ detachStatus();
+ detachConnection();
+ };
+};
diff --git a/invokeai/frontend/webv2/src/features/models/data/workingMemoryQueries.ts b/invokeai/frontend/webv2/src/features/models/data/workingMemoryQueries.ts
new file mode 100644
index 0000000000..b56f8602b7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/data/workingMemoryQueries.ts
@@ -0,0 +1,81 @@
+import type { WorkingMemorySummary } from '@features/models/core/workingMemory';
+
+import { assertAccountScopeCurrent, captureAccountScope, type AccountScope } from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
+import { queryOptions } from '@tanstack/react-query';
+
+import { getWorkingMemoryPlan, getWorkingMemoryStatus, getWorkingMemorySummary } from './workingMemoryApi';
+
+/** Polls while a run is pending or running and the socket is down, which includes a backend without one (the mock). */
+export const WORKING_MEMORY_POLL_MS = 2_000;
+/** With a socket, its events drive updates; this only catches a missed one. */
+export const WORKING_MEMORY_FALLBACK_POLL_MS = 30_000;
+
+const accountKey = (owner: AccountScope) => ({ accountId: owner.accountId, epoch: owner.epoch });
+
+/** Keys carry the account so a sign-out never serves one account's calibration to the next. */
+export const workingMemoryKeys = {
+ forAccount: (owner: AccountScope) => ['models', 'workingMemory', accountKey(owner)] as const,
+ plan: (owner: AccountScope, modelKey: string) => [...workingMemoryKeys.plans(owner), modelKey] as const,
+ plans: (owner: AccountScope) => [...workingMemoryKeys.forAccount(owner), 'plan'] as const,
+ status: (owner: AccountScope) => [...workingMemoryKeys.forAccount(owner), 'status'] as const,
+ summaries: (owner: AccountScope) => [...workingMemoryKeys.forAccount(owner), 'summary'] as const,
+ summary: (owner: AccountScope, modelKey: string) => [...workingMemoryKeys.summaries(owner), modelKey] as const,
+};
+
+const fenced = <T>(owner: AccountScope, request: (signal: AbortSignal) => Promise<T>, signal: AbortSignal) =>
+ request(AbortSignal.any([signal, owner.signal])).then((result) => {
+ assertAccountScopeCurrent(owner);
+ return result;
+ });
+
+export const hasRunningRun = (summary: WorkingMemorySummary | null | undefined): boolean =>
+ summary?.runs.some((run) => run.status === 'running') ?? false;
+
+/**
+ * The plan sizes its cases for the GPU memory free on the server when it is read and for the measurements stored by
+ * then. It is read again whenever the section opens and right before a calibration starts
+ * (`refreshWorkingMemoryPlan`, `fetchCurrentWorkingMemoryPlan`); in between it holds.
+ */
+export const workingMemoryPlanQueryOptions = (modelKey: string, owner = captureAccountScope()) =>
+ queryOptions({
+ queryFn: ({ signal }) => fenced(owner, (fencedSignal) => getWorkingMemoryPlan(modelKey, fencedSignal), signal),
+ queryKey: workingMemoryKeys.plan(owner, modelKey),
+ staleTime: 60_000,
+ });
+
+/** Null when the server has no current device class to summarise; the status then says why. */
+export const workingMemorySummaryQueryOptions = (
+ modelKey: string,
+ { isConnected, isSubmitting }: { isConnected: boolean; isSubmitting: boolean },
+ owner = captureAccountScope()
+) =>
+ queryOptions({
+ queryFn: ({ signal }) =>
+ fenced(
+ owner,
+ (fencedSignal) =>
+ getWorkingMemorySummary(modelKey, fencedSignal).catch((error: unknown) => {
+ if (error instanceof ApiError && error.status === 409) {
+ return null;
+ }
+ throw error;
+ }),
+ signal
+ ),
+ queryKey: workingMemoryKeys.summary(owner, modelKey),
+ refetchInterval: (query) =>
+ isSubmitting || hasRunningRun(query.state.data)
+ ? isConnected
+ ? WORKING_MEMORY_FALLBACK_POLL_MS
+ : WORKING_MEMORY_POLL_MS
+ : false,
+ staleTime: 5_000,
+ });
+
+export const workingMemoryStatusQueryOptions = (owner = captureAccountScope()) =>
+ queryOptions({
+ queryFn: ({ signal }) => fenced(owner, (fencedSignal) => getWorkingMemoryStatus(fencedSignal), signal),
+ queryKey: workingMemoryKeys.status(owner),
+ staleTime: 15_000,
+ });
diff --git a/invokeai/frontend/webv2/src/features/models/index.ts b/invokeai/frontend/webv2/src/features/models/index.ts
index 21cddf0c7b..e706ddb36e 100644
--- a/invokeai/frontend/webv2/src/features/models/index.ts
+++ b/invokeai/frontend/webv2/src/features/models/index.ts
@@ -30,7 +30,9 @@ export { useInstallActions } from './ui/add-models/useInstallActions';
export { getStarterModelInstallSources, type StarterInstallSource } from './ui/add-models/starterModelInstallSources';
export { ModelInstallRuntime } from './ui/ModelInstallRuntime';
export { ModelsPage } from './ui/ModelsPage';
+export type { CalibrationGraph, CalibrationGraphCompiler, WorkingMemoryCase } from './core/workingMemory';
export {
+ CalibrationGraphCompilerProvider,
ModelsUiProvider,
useModelsUi,
useOpenAddModelsSearch,
diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx
index d374a7cb58..fc8c867a92 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelsUiContext.tsx
@@ -1,4 +1,5 @@
import type { ModelConfig } from '@features/models/core/types';
+import type { CalibrationGraphCompiler } from '@features/models/core/workingMemory';
import type { ReactNode } from 'react';
import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';
@@ -81,6 +82,20 @@ export const ModelsUiProvider = ({ adapter, children }: { adapter: ModelsUiAdapt
export const useModelsUi = (): ModelsUiAdapter => use(ModelsUiContext);
+const CalibrationGraphCompilerContext = createContext<CalibrationGraphCompiler | null>(null);
+
+/** Supplies working-memory calibration with Generate's graph compiler, which App composes: Models cannot import it. */
+export const CalibrationGraphCompilerProvider = ({
+ children,
+ compile,
+}: {
+ children: ReactNode;
+ compile: CalibrationGraphCompiler;
+}) => <CalibrationGraphCompilerContext value={compile}>{children}</CalibrationGraphCompilerContext>;
+
+/** Null outside a provider; calibration is then unavailable. */
+export const useCalibrationGraphCompiler = (): CalibrationGraphCompiler | null => use(CalibrationGraphCompilerContext);
+
/**
* Opens the Model Manager on a model's details, returning to the manager's project like its other entry points; null
* when this session may not manage models. The manager's UI store loads on first use so editor boot does not carry it.
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.browser.test.tsx
new file mode 100644
index 0000000000..00d39cdac1
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.browser.test.tsx
@@ -0,0 +1,87 @@
+import type { ModelConfig } from '@features/models/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { setModelsSnapshotForTests } from '@features/models/data/modelsStore';
+import { type ModelsUiAdapter, ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/ModelsUiContext';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ModelDetail } from './ModelDetail';
+
+// The sections own their data; here they only mark where the page places them.
+const { section } = vi.hoisted(() => ({
+ section: (name: string) => () => <section data-section={name} />,
+}));
+
+vi.mock('./DefaultSettingsSection', () => ({ DefaultSettingsSection: section('default-settings') }));
+vi.mock('./RelatedModelsSection', () => ({ RelatedModelsSection: section('related-models') }));
+vi.mock('./TriggerPhrasesEditor', () => ({ MemoizedTriggerPhrasesEditor: section('trigger-phrases') }));
+vi.mock('./WorkingMemorySection', () => ({ WorkingMemorySection: section('working-memory') }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const MAIN = {
+ base: 'sdxl',
+ file_size: 1024,
+ format: 'checkpoint',
+ hash: 'hash-main',
+ key: 'main-1',
+ name: 'Main Model',
+ path: '/models/main.safetensors',
+ source: '/models/main.safetensors',
+ source_type: 'path',
+ trigger_phrases: [],
+ type: 'main',
+ variant: 'normal',
+} as unknown as ModelConfig;
+
+const ignoreConfirm = () => undefined;
+
+const MANAGER: ModelsUiAdapter = {
+ canManageModels: true,
+ enableModelDescriptions: true,
+ installInPlace: true,
+ isProjectActive: () => false,
+ managerProjectId: null,
+ schedulerPolicy: NO_SCHEDULER_POLICY,
+ setInstallInPlace: () => undefined,
+};
+
+describe('ModelDetail', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ accountLifecycle.activate('model-detail-test', ':user:model-detail-test');
+ setModelsSnapshotForTests({ models: [MAIN], status: 'loaded' });
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ setModelsSnapshotForTests({ models: [], status: 'idle' });
+ accountLifecycle.invalidate();
+ });
+
+ it('places working memory last, after the trigger phrases', async () => {
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <ModelsUiProvider adapter={MANAGER}>
+ <ModelDetail modelKey={MAIN.key} onRequestConfirm={ignoreConfirm} />
+ </ModelsUiProvider>
+ </ChakraProvider>
+ )
+ );
+
+ const order = [...host.querySelectorAll('[data-section]')].map((element) => element.getAttribute('data-section'));
+ expect(order).toEqual(['default-settings', 'related-models', 'trigger-phrases', 'working-memory']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
index b8fb328736..5056e1f2d4 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelDetail.tsx
@@ -11,6 +11,7 @@ import {
import { isLinkableType } from '@features/models/core/relationships';
import { isAbsoluteModelPath, resolveModelAbsolutePath } from '@features/models/core/schemas';
import { getModelSourceHref, getUnrecordedModelFact } from '@features/models/core/taxonomy';
+import { supportsWorkingMemoryCalibration } from '@features/models/core/workingMemory';
import { useModelsSelector, type ModelsSnapshot } from '@features/models/data/modelsStore';
import {
discardModelDraft,
@@ -42,6 +43,7 @@ import { RelatedModelsSection } from './RelatedModelsSection';
import { MemoizedTriggerPhrasesEditor } from './TriggerPhrasesEditor';
import { UnrecordedFactNotice } from './UnrecordedFactNotice';
import { UpdatePathDialog } from './UpdatePathDialog';
+import { WorkingMemorySection } from './WorkingMemorySection';
const TRIGGER_PHRASE_TYPES = new Set(['main', 'lora', 'embedding']);
const EMPTY_TRIGGER_PHRASES: readonly string[] = [];
@@ -182,6 +184,7 @@ export const ModelDetail = ({
}) => {
const { t } = useTranslation();
const model = useModelsSelector((snapshot) => selectModelShell(snapshot, modelKey));
+ const { canManageModels } = useModelsUi();
if (!model) {
return (
@@ -231,6 +234,14 @@ export const ModelDetail = ({
<TriggerPhrasesEditorContainer modelKey={model.key} />
</>
) : null}
+
+ {/* Last and collapsed: calibration is a rare, admin-only task. */}
+ {canManageModels && supportsWorkingMemoryCalibration(model) ? (
+ <>
+ <Separator borderColor="border.subtle" />
+ <WorkingMemorySection modelKey={model.key} />
+ </>
+ ) : null}
</Stack>
);
};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemoryCalibrateDialog.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemoryCalibrateDialog.tsx
new file mode 100644
index 0000000000..bf4fca47eb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemoryCalibrateDialog.tsx
@@ -0,0 +1,148 @@
+/* eslint-disable react-perf/jsx-no-new-function-as-prop */
+import type { WorkingMemoryPlan } from '@features/models/core/workingMemory';
+
+import { Alert, chakra, Portal, Stack, Text } from '@chakra-ui/react';
+import { planCalibrationSteps } from '@features/models/core/workingMemory';
+import { Button, CloseButton } from '@platform/ui/Button';
+import { Dialog } from '@platform/ui/Dialog';
+import { useCallback, type RefObject } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { SharedModelsList, useCaseLabel } from './WorkingMemoryParts';
+
+const SECONDS_PER_MINUTE = 60;
+
+/** Confirms a calibration: what it runs, where, for how long, and which other models it moves. */
+export const WorkingMemoryCalibrateDialog = ({
+ calibratedThroughName,
+ confirmRef,
+ deviceName,
+ getFinalFocus,
+ isConfirming,
+ isOpen,
+ onClose,
+ onConfirm,
+ onExitComplete,
+ plan,
+ planChanges,
+}: {
+ /** The main model a standalone VAE's cases generate with. */
+ calibratedThroughName: string | null;
+ /** The Calibrate button, which takes focus on opening and again after the plan changed on confirmation. */
+ confirmRef: RefObject<HTMLButtonElement | null>;
+ deviceName: string | null;
+ /** Where focus goes once the dialog closes; starting a calibration can disable the opener. */
+ getFinalFocus: () => HTMLElement | null;
+ /** The plan is read again before the start; closing meanwhile takes the confirmation back. */
+ isConfirming: boolean;
+ isOpen: boolean;
+ onClose: () => void;
+ onConfirm: () => void;
+ onExitComplete: () => void;
+ plan: WorkingMemoryPlan;
+ /** How often a confirmation found the runs changed; the dialog then shows the new plan, flagged. */
+ planChanges: number;
+}) => {
+ const { t } = useTranslation();
+ const getInitialFocus = useCallback(() => confirmRef.current, [confirmRef]);
+ const runCount = planCalibrationSteps(plan).length;
+ const minutes =
+ plan.estimated_seconds === null ? null : Math.max(1, Math.round(plan.estimated_seconds / SECONDS_PER_MINUTE));
+ const caseLabel = useCaseLabel();
+
+ return (
+ <Dialog.Root
+ finalFocusEl={getFinalFocus}
+ initialFocusEl={getInitialFocus}
+ open={isOpen}
+ size="md"
+ onExitComplete={onExitComplete}
+ onOpenChange={(event) => {
+ if (!event.open) {
+ onClose();
+ }
+ }}
+ >
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content>
+ <Dialog.Header borderBottomWidth="1px" borderColor="border.subtle">
+ <Stack gap="0.5">
+ <Dialog.Title>{t('models.workingMemory.dialogTitle')}</Dialog.Title>
+ {deviceName ? (
+ <Dialog.Description>
+ {t('models.workingMemory.dialogDescription', { device: deviceName })}
+ </Dialog.Description>
+ ) : null}
+ </Stack>
+ </Dialog.Header>
+ <Dialog.Body>
+ <Stack fontSize="sm" gap="3">
+ {/* Announced on insertion, keyed so each change is a new one: the click that confirmed started nothing. */}
+ {planChanges > 0 ? (
+ <Alert.Root key={planChanges} role="alert" status="warning" variant="surface">
+ <Alert.Indicator />
+ <Alert.Content>
+ <Alert.Title>{t('models.workingMemory.dialogChanged')}</Alert.Title>
+ </Alert.Content>
+ </Alert.Root>
+ ) : null}
+ <Stack gap="1">
+ {minutes === null ? null : (
+ <Text fontWeight="600">{t('models.workingMemory.dialogDuration', { minutes })}</Text>
+ )}
+ <Text color="fg.muted">{t('models.workingMemory.dialogQueueNote')}</Text>
+ {calibratedThroughName ? (
+ <Text color="fg.muted">
+ {t('models.workingMemory.dialogThrough', { model: calibratedThroughName })}
+ </Text>
+ ) : null}
+ </Stack>
+ <Stack gap="1">
+ <Text as="h3" fontWeight="600">
+ {t('models.workingMemory.dialogRuns', { count: runCount })}
+ </Text>
+ <chakra.ul display="flex" flexWrap="wrap" gap="1.5" listStyleType="none" m="0" p="0">
+ {plan.cases.map((item) => (
+ <chakra.li
+ key={item.id}
+ borderColor="border.subtle"
+ borderWidth="1px"
+ fontVariantNumeric="tabular-nums"
+ px="2"
+ py="0.5"
+ rounded="sm"
+ >
+ {caseLabel(item)}
+ </chakra.li>
+ ))}
+ </chakra.ul>
+ <Text color="fg.muted">
+ {t('models.workingMemory.dialogRepetitions', {
+ measured: plan.repetitions.measured,
+ warmUp: plan.repetitions.warm_up,
+ })}
+ </Text>
+ <Text color="fg.muted">{t('models.workingMemory.dialogSizesNote')}</Text>
+ </Stack>
+ {plan.shared_with.length > 0 ? <SharedModelsList models={plan.shared_with} /> : null}
+ </Stack>
+ </Dialog.Body>
+ <Dialog.Footer>
+ <Button variant="ghost" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button ref={confirmRef} loading={isConfirming} variant="solid" onClick={onConfirm}>
+ {t('models.workingMemory.calibrate')}
+ </Button>
+ </Dialog.Footer>
+ <Dialog.CloseTrigger asChild>
+ <CloseButton aria-label={t('common.close')} />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemoryParts.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemoryParts.tsx
new file mode 100644
index 0000000000..e233a7d0c2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemoryParts.tsx
@@ -0,0 +1,359 @@
+import type { SystemStyleObject } from '@chakra-ui/react';
+import type {
+ LineDisplayState,
+ WorkingMemoryCase,
+ WorkingMemoryLine,
+ WorkingMemoryLineSize,
+ WorkingMemoryPlan,
+} from '@features/models/core/workingMemory';
+
+import { Badge, chakra, HStack, Icon, Popover, Portal, Stack, Table, Text } from '@chakra-ui/react';
+import { getModelBaseLabel } from '@features/models/core/baseIdentity';
+import { describeFact, lineDisplayState, orderContributors, splitLine } from '@features/models/core/workingMemory';
+import { formatBytes, formatCount } from '@platform/i18n/languages';
+import { IconButton } from '@platform/ui/Button';
+import { PopoverContent } from '@platform/ui/Popover';
+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
+import { InfoIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+const STATE_PALETTES: Record<LineDisplayState, string> = {
+ in_use: 'green',
+ insufficient: 'gray',
+ interrupted: 'gray',
+ stale: 'orange',
+ unusable: 'red',
+};
+
+/** One state chip; the color repeats the text, never replaces it. */
+export const LineStateBadge = ({ state }: { state: LineDisplayState | null }) => {
+ const { t } = useTranslation();
+ const label =
+ state === 'in_use'
+ ? t('models.workingMemory.stateInUse')
+ : state === 'stale'
+ ? t('models.workingMemory.stateStale')
+ : state === 'unusable'
+ ? t('models.workingMemory.stateUnusable')
+ : state === 'insufficient'
+ ? t('models.workingMemory.stateInsufficient')
+ : state === 'interrupted'
+ ? t('models.workingMemory.stateInterrupted')
+ : t('models.workingMemory.stateNone');
+
+ return (
+ <Badge
+ colorPalette={state ? STATE_PALETTES[state] : 'gray'}
+ flexShrink={0}
+ fontSize="xs"
+ size="lg"
+ variant="surface"
+ >
+ {label}
+ </Badge>
+ );
+};
+
+/** A plan case as "768 × 768 · fp16". */
+export const useCaseLabel = () => {
+ const { t } = useTranslation();
+
+ return (item: Pick<WorkingMemoryCase, 'height' | 'line' | 'width'>): string =>
+ t('models.workingMemory.pair', {
+ detail: splitLine(item.line).dtype ?? item.line,
+ label: t('models.workingMemory.size', { height: item.height, width: item.width }),
+ });
+};
+
+/** `decode_fp16` → "Decode · fp16". An operation this version has no name for shows as the server sends it. */
+export const useLineLabel = () => {
+ const { t } = useTranslation();
+
+ return (line: string): string => {
+ const { dtype, operation } = splitLine(line);
+ const operationLabel =
+ operation === 'decode'
+ ? t('models.workingMemory.operationDecode')
+ : operation === 'encode'
+ ? t('models.workingMemory.operationEncode')
+ : operation;
+
+ return dtype ? t('models.workingMemory.pair', { detail: dtype, label: operationLabel }) : operationLabel;
+ };
+};
+
+const MEGAPIXEL = 1_000_000;
+
+const formatMegapixels = (pixels: number): string => formatCount(Math.round((pixels / MEGAPIXEL) * 100) / 100);
+
+const TABLE_SX: SystemStyleObject = {
+ '& td, & th': { borderColor: 'border.subtle', fontSize: 'sm', px: '2', py: '1' },
+ '& thead th': {
+ color: 'fg.muted',
+ fontSize: 'xs',
+ fontWeight: '700',
+ letterSpacing: 'wider',
+ textTransform: 'uppercase',
+ },
+ '& tbody th': { fontWeight: '400', textAlign: 'start' },
+ // Every row starts with its size as a `th`, so each `td` and every header after the first holds a number.
+ '& td, & thead th + th': { fontVariantNumeric: 'tabular-nums', textAlign: 'end' },
+};
+
+/** A changed environment fact by a readable name; see `describeFact`. */
+const useFactLabel = () => {
+ const { t } = useTranslation();
+
+ return (key: string): string => {
+ const fact = describeFact(key);
+
+ if ('name' in fact) {
+ return fact.name;
+ }
+
+ switch (fact.translated) {
+ case 'allocator':
+ return t('models.workingMemory.facts.allocator');
+ case 'driver':
+ return t('models.workingMemory.facts.driver');
+ case 'invokeai':
+ return t('models.workingMemory.facts.invokeai');
+ case 'osBuild':
+ return t('models.workingMemory.facts.osBuild');
+ case 'sdpaGuard':
+ return t('models.workingMemory.facts.sdpaGuard');
+ case 'torchBuild':
+ return t('models.workingMemory.facts.torchBuild');
+ }
+ };
+};
+
+/** The state help of a line: why it applies or not, naming the facts that changed or differ. */
+const LineStateHelp = ({ line }: { line: WorkingMemoryLine }) => {
+ const { t } = useTranslation();
+ const factLabel = useFactLabel();
+ const facts = line.changed_facts.map(factLabel).join(', ');
+ // The server explains a line only stopped attempts measured in English; this says the same in the user's language.
+ const text =
+ lineDisplayState(line) === 'interrupted'
+ ? t('models.workingMemory.helpInterrupted')
+ : line.state === 'in_use'
+ ? t('models.workingMemory.helpInUse')
+ : line.state === 'stale'
+ ? t('models.workingMemory.helpStale', { facts })
+ : line.state === 'unusable'
+ ? facts
+ ? t('models.workingMemory.helpUnusable', { facts })
+ : t('models.workingMemory.helpUnusableNoFacts')
+ : (line.problem ?? t('models.workingMemory.helpInsufficient'));
+
+ return (
+ <Text color="fg.muted" fontSize="xs">
+ {text}
+ </Text>
+ );
+};
+
+const HINT_POSITIONING = { placement: 'top' } as const;
+
+/** A column header with an info button after its label. */
+const HintedColumnHeader = ({ hint, label }: { hint: string; label: string }) => {
+ const { t } = useTranslation();
+ const name = t('models.workingMemory.aboutColumn', { column: label });
+ // The button stays on the line of the label's last word when a narrow column wraps the label.
+ const split = label.lastIndexOf(' ') + 1;
+
+ return (
+ <Table.ColumnHeader>
+ {label.slice(0, split)}
+ <chakra.span whiteSpace="nowrap">
+ {label.slice(split)}
+ <HintButton hint={hint} name={name} />
+ </chakra.span>
+ </Table.ColumnHeader>
+ );
+};
+
+/** The explanation opens in a popover, by click or keyboard, so it does not depend on hover. */
+const HintButton = ({ hint, name }: { hint: string; name: string }) => {
+ const ids = useTooltipTriggerIds();
+
+ return (
+ <Popover.Root ids={ids} lazyMount positioning={HINT_POSITIONING} unmountOnExit>
+ <Tooltip content={name} ids={ids}>
+ <Popover.Trigger asChild>
+ <IconButton
+ aria-label={name}
+ color="fg.subtle"
+ h="5"
+ minW="5"
+ ms="0.5"
+ size="sm"
+ variant="ghost"
+ verticalAlign="middle"
+ w="5"
+ >
+ <Icon as={InfoIcon} boxSize="3" />
+ </IconButton>
+ </Popover.Trigger>
+ </Tooltip>
+ <Portal>
+ <Popover.Positioner>
+ <PopoverContent aria-label={name} maxW="18rem" p="3">
+ <Text fontSize="xs">{hint}</Text>
+ </PopoverContent>
+ </Popover.Positioner>
+ </Portal>
+ </Popover.Root>
+ );
+};
+
+/** Why a measured size does not feed the line, or null for a size that does. */
+const useNotCountedLabel = () => {
+ const { t } = useTranslation();
+
+ return (size: Pick<WorkingMemoryLineSize, 'counted' | 'excluded_reason'>): string | null => {
+ if (size.counted) {
+ return null;
+ }
+
+ switch (size.excluded_reason) {
+ case 'fragmented':
+ return t('models.workingMemory.notCountedFragmented');
+ case 'partial_residency':
+ return t('models.workingMemory.notCountedPartial');
+ case 'aborted_attempt':
+ return t('models.workingMemory.notCountedAborted');
+ case null:
+ return t('models.workingMemory.notCounted');
+ }
+ };
+};
+
+/**
+ * One estimator line: its state, the models whose measurements it pools (named when another model is among them,
+ * this model first), the range the user line was fitted on, and every measured size.
+ */
+export const LineMeasurements = ({ line, modelKey }: { line: WorkingMemoryLine; modelKey: string }) => {
+ const { t } = useTranslation();
+ const lineLabel = useLineLabel()(line.line);
+ const notCountedLabel = useNotCountedLabel();
+ const isShared = line.measured_by.some((entry) => entry.model_key !== modelKey);
+ const contributors = orderContributors(line.measured_by, modelKey)
+ .map((entry) => entry.name ?? t('models.workingMemory.removedModel'))
+ .join(', ');
+
+ return (
+ <Stack gap="1.5" minW="0">
+ <HStack gap="2" wrap="wrap">
+ <Text as="h4" fontSize="sm" fontWeight="600">
+ {lineLabel}
+ </Text>
+ <LineStateBadge state={lineDisplayState(line)} />
+ </HStack>
+ <LineStateHelp line={line} />
+ {isShared ? (
+ <Text color="fg.muted" fontSize="xs" overflowWrap="anywhere">
+ {t('models.workingMemory.measuredBy', { models: contributors })}
+ </Text>
+ ) : null}
+ {line.measured_range ? (
+ <Text color="fg.muted" fontSize="xs">
+ {t('models.workingMemory.measuredRange', {
+ max: formatMegapixels(line.measured_range.max_pixels),
+ min: formatMegapixels(line.measured_range.min_pixels),
+ })}
+ </Text>
+ ) : null}
+ {line.sizes.length > 0 ? (
+ <chakra.div overflowX="auto">
+ <Table.Root
+ aria-label={t('models.workingMemory.tableLabel', { line: lineLabel })}
+ css={TABLE_SX}
+ // Fixed columns line the tables of a section up, whatever a row header's note adds; narrow panes scroll.
+ minW="26rem"
+ tableLayout="fixed"
+ variant="line"
+ >
+ <Table.ColumnGroup>
+ <Table.Column w="34%" />
+ <Table.Column w="22%" />
+ <Table.Column w="22%" />
+ <Table.Column w="22%" />
+ </Table.ColumnGroup>
+ <Table.Header>
+ <Table.Row>
+ <Table.ColumnHeader>{t('models.workingMemory.columnSize')}</Table.ColumnHeader>
+ <HintedColumnHeader
+ hint={t('models.workingMemory.hintMeasured')}
+ label={t('models.workingMemory.columnMeasured')}
+ />
+ <HintedColumnHeader
+ hint={t('models.workingMemory.hintShipped')}
+ label={t('models.workingMemory.columnShipped')}
+ />
+ <HintedColumnHeader
+ hint={t('models.workingMemory.hintCalibrated')}
+ label={t('models.workingMemory.columnCalibrated')}
+ />
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {line.sizes.map((size) => {
+ // A size the fit leaves out stays listed, muted, and names why in its row header.
+ const notCounted = notCountedLabel(size);
+ const color = notCounted ? 'fg.muted' : undefined;
+
+ return (
+ <Table.Row key={`${String(size.width)}x${String(size.height)}`}>
+ <Table.Cell as="th" color={color} scope="row" whiteSpace="nowrap">
+ {t('models.workingMemory.size', { height: size.height, width: size.width })}
+ {notCounted ? (
+ <chakra.span display="block" fontSize="xs" whiteSpace="normal">
+ {notCounted}
+ </chakra.span>
+ ) : null}
+ </Table.Cell>
+ <Table.Cell color={color} whiteSpace="nowrap">
+ {formatBytes(size.measured_bytes)}
+ </Table.Cell>
+ <Table.Cell color={color} whiteSpace="nowrap">
+ {formatBytes(size.shipped_bytes)}
+ </Table.Cell>
+ <Table.Cell color={color} whiteSpace="nowrap">
+ {formatBytes(size.user_bytes)}
+ </Table.Cell>
+ </Table.Row>
+ );
+ })}
+ </Table.Body>
+ </Table.Root>
+ </chakra.div>
+ ) : null}
+ </Stack>
+ );
+};
+
+/** Other installed models whose estimates the same lines price, so a calibration moves them too. */
+export const SharedModelsList = ({ models }: { models: WorkingMemoryPlan['shared_with'] }) => {
+ const { t } = useTranslation();
+ const lineLabel = useLineLabel();
+
+ return (
+ <Stack gap="1">
+ <Text as="h4" fontSize="sm" fontWeight="600">
+ {t('models.workingMemory.sharedWith', { count: models.length })}
+ </Text>
+ <chakra.ul display="flex" flexDirection="column" gap="0.5" listStyleType="none" m="0" p="0">
+ {models.map((model) => (
+ <chakra.li key={model.key} color="fg.muted" fontSize="xs" overflowWrap="anywhere">
+ {t('models.workingMemory.pair', {
+ detail: [getModelBaseLabel(model.base), ...model.lines.map(lineLabel)].join(', '),
+ label: model.name,
+ })}
+ </chakra.li>
+ ))}
+ </chakra.ul>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemorySection.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemorySection.browser.test.tsx
new file mode 100644
index 0000000000..ad09fe1e3c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemorySection.browser.test.tsx
@@ -0,0 +1,1889 @@
+import type { ModelConfig } from '@features/models/core/types';
+import type {
+ CalibrationGraphCompiler,
+ WorkingMemoryCase,
+ WorkingMemoryLine,
+ WorkingMemoryPlan,
+ WorkingMemoryRun,
+ WorkingMemoryStatus,
+ WorkingMemorySummary,
+} from '@features/models/core/workingMemory';
+import type * as ModelsApi from '@features/models/data/api';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { getModelsSnapshot, refreshModels } from '@features/models/data/modelsStore';
+import { WORKING_MEMORY_POLL_MS } from '@features/models/data/workingMemoryQueries';
+import { CalibrationGraphCompilerProvider } from '@features/models/ui/ModelsUiContext';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { ApiError } from '@platform/transport/http';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { system } from '@theme/system';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+const api = vi.hoisted(() => ({
+ acknowledgeCalibrationEnqueue: vi.fn((_idempotencyKey: string) => Promise.resolve()),
+ calibrateWorkingMemory: vi.fn(),
+ cancelCalibrationRun: vi.fn((_runId: string) => Promise.resolve()),
+ getWorkingMemoryPlan: vi.fn(),
+ getWorkingMemoryStatus: vi.fn(),
+ getWorkingMemorySummary: vi.fn(),
+ resetWorkingMemory: vi.fn((_modelKey: string, _signal?: AbortSignal) => Promise.resolve()),
+}));
+
+vi.mock('@features/models/data/workingMemoryApi', () => api);
+
+const notify = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));
+
+vi.mock('@features/models/ui/useModelsNotify', () => ({ useNotify: () => notify }));
+
+/** The model records the server holds; a compile reads them again first. */
+const library = vi.hoisted(() => ({ failNext: null as Error | null, models: [] as unknown[] }));
+
+// Spread over the real module: the models store imports the rest of this transport module.
+vi.mock('@features/models/data/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof ModelsApi>()),
+ getModelsDir: () => Promise.resolve(''),
+ listMissingModels: () => Promise.resolve([]),
+ listModels: () => {
+ const failure = library.failNext;
+ library.failNext = null;
+ return failure ? Promise.reject(failure) : Promise.resolve(library.models);
+ },
+}));
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options && Object.keys(options).length > 0
+ ? `${key}(${Object.entries(options)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([name, value]) => `${name}=${String(value)}`)
+ .join(',')})`
+ : key,
+ }),
+}));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+// Loaded with the file, after the mocks above: a first load inside a test spends that test's time budget, which a busy
+// machine can exhaust.
+const { WorkingMemorySection } = await import('./WorkingMemorySection');
+
+const MODEL_KEY = 'sdxl-main';
+const DEVICE = { id: '0123456789abcdef', name: 'Fixture GPU 24GB' };
+const T0 = Date.parse('2026-10-01T12:00:00.000Z');
+
+const planCase = (dtype: string, side: number): WorkingMemoryCase => ({
+ components: {},
+ estimator: 'sdxl_vae_decode',
+ height: side,
+ id: `sdxl_vae_decode-decode-${dtype}-${String(side)}x${String(side)}`,
+ line: `decode_${dtype}`,
+ mode: 'txt2img',
+ model_key: MODEL_KEY,
+ negative_prompt: '',
+ positive_prompt: 'a lake',
+ seed: 1,
+ settings: { vaePrecision: dtype },
+ steps: 2,
+ width: side,
+});
+
+const CASES = [planCase('fp16', 512), planCase('fp32', 512)];
+
+const supportedPlan = (): WorkingMemoryPlan => ({
+ calibrated_through: null,
+ cases: CASES,
+ device_class: DEVICE,
+ estimated_seconds: 150,
+ estimators: ['sdxl_vae_decode'],
+ model_key: MODEL_KEY,
+ not_covered: ['encode: not measured'],
+ reason: null,
+ repetitions: { measured: 2, warm_up: 1 },
+ shared_with: [{ base: 'sd-1', key: 'sd1', lines: ['decode_fp16'], name: 'Shared SD1', type: 'main' }],
+ supported: true,
+});
+
+const status = (overrides: Partial<WorkingMemoryStatus> = {}): WorkingMemoryStatus => ({
+ available: true,
+ current_device_class_id: DEVICE.id,
+ current_env_id: 'env',
+ device_classes: [],
+ unavailable_reason: null,
+ ...overrides,
+});
+
+const run = (
+ id: string,
+ offset: number,
+ runStatus: WorkingMemoryRun['status'],
+ error: string | null = null,
+ attemptId: string | null = 'earlier-attempt',
+ overrides: Partial<WorkingMemoryRun> = {}
+): WorkingMemoryRun => ({
+ attempt_id: attemptId,
+ attempt_steps: null,
+ created_at: new Date(T0 + offset * 1_000).toISOString(),
+ error,
+ error_code: null,
+ held_back: null,
+ // As the server counts: a failed or canceled decode leaves its window too, as an invalid one.
+ point_count: runStatus === 'running' ? 0 : 1,
+ run_id: id,
+ status: runStatus,
+ ...overrides,
+});
+
+/** How the server marks every run of an attempt it discarded. */
+const ABORTED = { held_back: 'aborted_attempt' } as const;
+
+/** The English text of a key, for what the user must read in it. */
+const english = (await fetch('/locales/en.json').then((response) => response.json())) as {
+ models: { workingMemory: Record<string, string> };
+};
+
+const OWN = { model_key: MODEL_KEY, name: 'This SDXL', windows: 6 };
+
+const line = (
+ state: WorkingMemoryLine['state'],
+ changedFacts: string[] = [],
+ overrides: Partial<WorkingMemoryLine> = {}
+): WorkingMemoryLine => ({
+ base_bytes: 400_000_000,
+ carrier: 'sdxl_vae_decode',
+ changed_facts: changedFacts,
+ env_id: 'env',
+ estimator: 'sdxl_vae_decode',
+ line: 'decode_fp16',
+ measured_by: [OWN],
+ measured_range: { max_pixels: 1_048_576, min_pixels: 262_144 },
+ problem: null,
+ sizes: [
+ {
+ counted: true,
+ excluded_reason: null,
+ height: 512,
+ measured_bytes: 1_234_000_000,
+ pixels: 262_144,
+ shipped_bytes: null,
+ user_bytes: null,
+ width: 512,
+ windows: 3,
+ },
+ {
+ counted: true,
+ excluded_reason: null,
+ height: 1024,
+ measured_bytes: 2_100_000_000,
+ pixels: 1_048_576,
+ shipped_bytes: 2_800_000_000,
+ user_bytes: 2_600_000_000,
+ width: 1024,
+ windows: 3,
+ },
+ ],
+ own_windows: 6,
+ slope_bytes_per_pixel: 1_100,
+ state,
+ version: 1,
+ ...overrides,
+});
+
+const summary = (overrides: Partial<WorkingMemorySummary> = {}): WorkingMemorySummary => ({
+ current_env_id: 'env',
+ device_class_id: DEVICE.id,
+ excluded_windows: 0,
+ lines: [],
+ measurement_method: 'allocator',
+ measurement_verified: true,
+ model_key: MODEL_KEY,
+ problem: null,
+ runs: [],
+ usable: true,
+ ...overrides,
+});
+
+let host: HTMLDivElement;
+let root: Root;
+let queryClient: QueryClient;
+let compile: ReturnType<typeof vi.fn<CalibrationGraphCompiler>>;
+let currentSummary: WorkingMemorySummary | Error;
+
+/** Renders the section, opened as a user would unless `expanded` is false: it starts collapsed. */
+const renderSection = async ({ expanded = true }: { expanded?: boolean } = {}) => {
+ host = document.createElement('div');
+ host.style.width = '720px';
+ document.body.append(host);
+ root = createRoot(host);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <CalibrationGraphCompilerProvider compile={compile}>
+ <WorkingMemorySection modelKey={MODEL_KEY} />
+ </CalibrationGraphCompilerProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ )
+ );
+
+ if (expanded) {
+ await act(() => userEvent.click(sectionToggle()));
+ }
+};
+
+/** The disclosure button inside the section heading. */
+const sectionToggle = () => host.querySelector<HTMLButtonElement>('h3 button')!;
+
+const buttonNamed = (name: string, within: ParentNode = document): HTMLButtonElement | undefined =>
+ [...within.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent.trim() === name);
+
+const openDialog = () => document.querySelector<HTMLElement>('[role="dialog"][data-state="open"]');
+const openAlertDialog = () => document.querySelector<HTMLElement>('[role="alertdialog"][data-state="open"]');
+const sectionText = () => host.textContent;
+
+/** The summary the section reads next; a poll or an invalidation picks it up. */
+const serveSummary = (next: WorkingMemorySummary | Error) => {
+ currentSummary = next;
+};
+
+const refreshSummary = () => act(() => queryClient.invalidateQueries());
+
+/** The calibrated main model's record as the server holds it. */
+const mainModel = (base: string): ModelConfig =>
+ ({
+ base,
+ description: null,
+ file_size: 1024,
+ format: 'checkpoint',
+ hash: 'hash',
+ key: MODEL_KEY,
+ name: 'This SDXL',
+ source: MODEL_KEY,
+ source_type: 'path',
+ type: 'main',
+ }) as ModelConfig;
+
+beforeEach(() => {
+ document.documentElement.lang = 'en';
+ accountLifecycle.activate('wm-section-test', ':user:wm-section-test');
+ library.models = [mainModel('sdxl')];
+ // Like Generate's compiler, it builds over the records it is given, rejecting with their read's error; each graph
+ // names the base it was built for, and its model in a loader as the record has it.
+ compile = vi.fn<CalibrationGraphCompiler>(async (cases, models) => {
+ const records = await models;
+
+ return cases.map((item) => {
+ const model = records.find((record) => record.key === item.model_key);
+ const loader = model
+ ? {
+ id: 'loader',
+ model: { base: model.base, hash: model.hash, key: model.key, name: model.name, type: model.type },
+ }
+ : null;
+
+ return {
+ caseId: item.id,
+ data: [],
+ graph: { base: model?.base ?? null, edges: [], id: item.id, nodes: loader ? { loader } : {} },
+ };
+ });
+ });
+ currentSummary = summary();
+ api.getWorkingMemoryPlan.mockImplementation(() => Promise.resolve(supportedPlan()));
+ api.getWorkingMemoryStatus.mockImplementation(() => Promise.resolve(status()));
+ api.getWorkingMemorySummary.mockImplementation(() =>
+ currentSummary instanceof Error ? Promise.reject(currentSummary) : Promise.resolve(currentSummary)
+ );
+ let runNumber = 0;
+ api.calibrateWorkingMemory.mockImplementation(() => {
+ runNumber += 1;
+ return Promise.resolve({ device_class_id: DEVICE.id, item_ids: [runNumber], run_id: `run-${String(runNumber)}` });
+ });
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ vi.clearAllMocks();
+});
+
+describe('WorkingMemorySection', () => {
+ it('calibrates a model that was never calibrated: dialog, queued runs, progress, then the measurements', async () => {
+ // The summary polls on an interval while a run is running: the test steps that interval rather than wait it out.
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+
+ const section = host.querySelector('section')!;
+ expect(section.getAttribute('aria-labelledby')).toBe(host.querySelector('h3')!.id);
+ expect(host.querySelector('h3')!.textContent).toBe('models.workingMemory.title');
+ expect(sectionText()).toContain(DEVICE.name);
+ expect(sectionText()).toContain('models.workingMemory.stateNone');
+ // The compiler loads only once Calibrate is clicked.
+ expect(compile).not.toHaveBeenCalled();
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ // The dialog opens only on a plan that compiles.
+ expect(compile).toHaveBeenCalledTimes(1);
+ const dialog = openDialog()!;
+ expect(dialog.textContent).toContain('models.workingMemory.dialogDuration(minutes=3)');
+ expect(dialog.textContent).toContain('models.workingMemory.dialogQueueNote');
+ expect(dialog.textContent).toContain('models.workingMemory.dialogSizesNote');
+ expect(dialog.textContent).toContain(
+ 'models.workingMemory.pair(detail=fp16,label=models.workingMemory.size(height=512,width=512))'
+ );
+ expect(dialog.textContent).toContain(
+ 'models.workingMemory.pair(detail=fp32,label=models.workingMemory.size(height=512,width=512))'
+ );
+ expect(dialog.textContent).toContain('models.workingMemory.dialogRuns(count=6)');
+ expect(dialog.textContent).toContain('Shared SD1');
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+
+ // Compiled to open the dialog, and again on confirmation over the model records read then.
+ expect(compile).toHaveBeenCalledTimes(2);
+ expect(compile).toHaveBeenLastCalledWith(CASES, expect.any(Promise), expect.any(AbortSignal));
+ const requests = api.calibrateWorkingMemory.mock.calls.map(
+ ([key, request]) => [key, (request as { graph: { id: string } }).graph.id] as const
+ );
+ // Each precision warms up first: fp16 warm-up, two measured, then the same in fp32.
+ expect(requests).toEqual([
+ [MODEL_KEY, CASES[0]!.id],
+ [MODEL_KEY, CASES[0]!.id],
+ [MODEL_KEY, CASES[0]!.id],
+ [MODEL_KEY, CASES[1]!.id],
+ [MODEL_KEY, CASES[1]!.id],
+ [MODEL_KEY, CASES[1]!.id],
+ ]);
+ const keys = api.calibrateWorkingMemory.mock.calls.map(
+ ([, request]) => (request as { idempotencyKey: string }).idempotencyKey
+ );
+ expect(new Set(keys).size).toBe(6);
+ // One attempt id for the click, on every step and inside every retry key.
+ const attemptIds = new Set(
+ api.calibrateWorkingMemory.mock.calls.map(([, request]) => (request as { attemptId: string }).attemptId)
+ );
+ expect(attemptIds.size).toBe(1);
+ const [attemptId] = [...attemptIds];
+ expect(keys.every((key) => key.includes(attemptId!))).toBe(true);
+ expect(api.acknowledgeCalibrationEnqueue.mock.calls.map(([key]) => key)).toEqual(keys);
+
+ serveSummary(
+ summary({
+ runs: [
+ run('run-1', 0, 'completed', null, attemptId),
+ run('run-2', 1, 'completed', null, attemptId),
+ ...[3, 4, 5, 6].map((number) => run(`run-${String(number)}`, number, 'running', null, attemptId)),
+ ],
+ })
+ );
+ await refreshSummary();
+ await expect.poll(sectionText).toContain('models.workingMemory.running(done=2,total=6)');
+ expect(host.querySelector('[role="progressbar"]')?.getAttribute('aria-label')).toBe(
+ 'models.workingMemory.progressLabel'
+ );
+ expect(sectionText()).toContain(
+ 'models.workingMemory.pair(detail=fp16,label=models.workingMemory.size(height=512,width=512))'
+ );
+ expect(buttonNamed('models.workingMemory.recalibrate')?.disabled).toBe(true);
+ expect(sectionText()).toContain('models.workingMemory.blockedRunning');
+ // Reset names the same reason it is disabled for.
+ const reset = buttonNamed('common.reset')!;
+ expect(reset.disabled).toBe(true);
+ expect(document.getElementById(reset.getAttribute('aria-describedby')!)?.textContent).toBe(
+ 'models.workingMemory.blockedRunning'
+ );
+
+ serveSummary(
+ summary({
+ lines: [line('in_use')],
+ // An earlier attempt failed; the newest attempt is the one that counts.
+ runs: [
+ run('old', -600, 'failed', 'old failure'),
+ ...[1, 2, 3, 4, 5, 6].map((number) => run(`run-${String(number)}`, number, 'completed', null, attemptId)),
+ ],
+ })
+ );
+ // Polling picks the end up without any other trigger, one poll interval later.
+ await act(() => vi.advanceTimersByTimeAsync(WORKING_MEMORY_POLL_MS));
+ await expect.poll(() => host.querySelector('table')).not.toBeNull();
+
+ const table = host.querySelector('table')!;
+ expect(table.getAttribute('aria-label')).toBe(
+ 'models.workingMemory.tableLabel(line=models.workingMemory.pair(detail=fp16,label=models.workingMemory.operationDecode))'
+ );
+ const rows = [...table.querySelectorAll('tbody tr')].map((row) =>
+ [...row.querySelectorAll('th, td')].map((cell) => cell.textContent)
+ );
+ expect([...table.querySelectorAll('tbody th')].map((cell) => cell.getAttribute('scope'))).toEqual(['row', 'row']);
+ expect(table.querySelectorAll('thead th')[3]?.textContent).toBe('models.workingMemory.columnCalibrated');
+ // The size labels its row on the left; every value sits right-aligned under its header.
+ const alignments = (selector: string) =>
+ [...table.querySelectorAll(selector)].map((cell) => getComputedStyle(cell).textAlign);
+ expect(alignments('thead th')).toEqual(['start', 'end', 'end', 'end']);
+ expect(alignments('tbody tr:first-child > *')).toEqual(['start', 'end', 'end', 'end']);
+ // Missing estimates show a dash; sizes format like the rest of the app.
+ expect(rows).toEqual([
+ ['models.workingMemory.size(height=512,width=512)', '1.2 GB', '—', '—'],
+ ['models.workingMemory.size(height=1024,width=1024)', '2.1 GB', '2.8 GB', '2.6 GB'],
+ ]);
+ expect(sectionText()).toContain('models.workingMemory.measuredRange(max=1.05,min=0.26)');
+ expect(sectionText()).toContain('models.workingMemory.stateInUse');
+ expect(host.querySelector('[role="progressbar"]')).toBeNull();
+ });
+
+ it('operates the dialog by keyboard and returns focus to its opener', async () => {
+ await renderSection();
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')).toBeDefined();
+
+ const opener = buttonNamed('models.workingMemory.calibrate')!;
+ opener.focus();
+ await act(() => userEvent.keyboard('{Enter}'));
+ await expect.poll(openDialog).not.toBeNull();
+ await expect
+ .poll(() => openDialog()?.contains(document.activeElement) && document.activeElement?.textContent)
+ .toBe('models.workingMemory.calibrate');
+ expect(openDialog()!.querySelector('h2, [id$="title"]')?.textContent).toBe('models.workingMemory.dialogTitle');
+
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(openDialog).toBeNull();
+ await expect.poll(() => document.activeElement).toBe(opener);
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+
+ await act(() => userEvent.keyboard('{Enter}'));
+ await expect
+ .poll(() => openDialog()?.contains(document.activeElement) && document.activeElement?.textContent)
+ .toBe('models.workingMemory.calibrate');
+ // Hold the first step's response so the attempt stays in its running state while focus settles.
+ let releasePost = () => undefined as void;
+ const held = new Promise<void>((resolve) => {
+ releasePost = resolve;
+ });
+ const post = api.calibrateWorkingMemory.getMockImplementation()!;
+ api.calibrateWorkingMemory.mockImplementationOnce(async (...args: unknown[]) => {
+ await held;
+ return post(...args);
+ });
+ await act(() => userEvent.keyboard('{Enter}'));
+ await expect.poll(openDialog).toBeNull();
+ // Starting disables the opener; focus moves to the action that is available now instead of the page.
+ await expect.poll(() => document.activeElement?.textContent).toBe('models.workingMemory.stop');
+ expect(host.contains(document.activeElement)).toBe(true);
+
+ await act(() => releasePost());
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+ });
+
+ it('stops a running calibration after confirmation, newest run first', async () => {
+ serveSummary(
+ summary({ runs: [run('run-1', 0, 'completed'), run('run-2', 1, 'running'), run('run-3', 2, 'running')] })
+ );
+ await renderSection();
+ await expect.poll(() => buttonNamed('models.workingMemory.stop')).toBeDefined();
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.stop')!));
+ await expect.poll(openAlertDialog).not.toBeNull();
+ // The warning describes the dialog, so a screen reader reads it as the dialog opens.
+ const describedBy = openAlertDialog()!.getAttribute('aria-describedby') ?? '';
+ expect(document.getElementById(describedBy)?.textContent).toBe('models.workingMemory.stopBody');
+ // Stop discards the whole attempt, its finished runs too; the user reads that before confirming.
+ expect(english.models.workingMemory.stopBody).toMatch(/measurements are discarded, finished runs included/);
+ expect(api.cancelCalibrationRun).not.toHaveBeenCalled();
+
+ api.cancelCalibrationRun.mockImplementation(() => {
+ serveSummary(
+ summary({
+ runs: [
+ run('run-1', 0, 'completed', null, 'earlier-attempt', ABORTED),
+ run('run-2', 1, 'partial', null, 'earlier-attempt', ABORTED),
+ run('run-3', 2, 'canceled', null, 'earlier-attempt', ABORTED),
+ ],
+ })
+ );
+ return Promise.resolve();
+ });
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.stop', openAlertDialog()!)!));
+ await expect.poll(openAlertDialog).toBeNull();
+
+ expect(api.cancelCalibrationRun.mock.calls.map(([runId]) => runId)).toEqual(['run-3', 'run-2']);
+ await expect.poll(sectionText).toContain('models.workingMemory.partial');
+ expect(sectionText()).toContain('models.workingMemory.discarded');
+ // The Stop button is gone; focus lands on the action that is available now.
+ await expect.poll(() => document.activeElement?.textContent).toBe('common.retry');
+ });
+
+ it('reports an attempt stopped while queuing as canceled, not as queued short', async () => {
+ await renderSection();
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')).toBeDefined();
+
+ // The third step's response arrives only once the stop is under way.
+ let releasePost = () => undefined as void;
+ const held = new Promise<void>((resolve) => {
+ releasePost = resolve;
+ });
+ const post = api.calibrateWorkingMemory.getMockImplementation()!;
+ api.calibrateWorkingMemory.mockImplementation(async (...args: unknown[]) => {
+ if (api.calibrateWorkingMemory.mock.calls.length === 3) {
+ await held;
+ }
+ return post(...args);
+ });
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(3);
+
+ const attemptId = (api.calibrateWorkingMemory.mock.calls[0]![1] as { attemptId: string }).attemptId;
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.stop')!));
+ await expect.poll(openAlertDialog).not.toBeNull();
+ serveSummary(
+ summary({
+ runs: [1, 2, 3].map((number) =>
+ run(`run-${String(number)}`, number, 'completed', null, attemptId, { ...ABORTED, attempt_steps: 6 })
+ ),
+ })
+ );
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.stop', openAlertDialog()!)!));
+ await act(() => releasePost());
+ await expect.poll(openAlertDialog).toBeNull();
+
+ expect(api.calibrateWorkingMemory).toHaveBeenCalledTimes(3);
+ await expect.poll(sectionText).toContain('models.workingMemory.partialCanceled');
+ expect(sectionText()).not.toContain('models.workingMemory.partialQueued');
+ // Stopped after three of six steps: the server holds the attempt back, and its three finished steps are lost.
+ expect(sectionText()).toContain('models.workingMemory.discarded');
+ });
+
+ it('says the measurements of an attempt the server discarded are gone, offering to calibrate again', async () => {
+ // After a reload: a queue clear canceled the attempt's later runs, so the server holds all of them back.
+ const planned = { ...ABORTED, attempt_steps: 6 };
+ serveSummary(
+ summary({
+ runs: [
+ run('run-1', 0, 'completed', null, 'attempt', planned),
+ run('run-2', 1, 'completed', null, 'attempt', planned),
+ ...[3, 4, 5, 6].map((number) => run(`run-${String(number)}`, number, 'canceled', null, 'attempt', planned)),
+ ],
+ })
+ );
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.partial');
+
+ expect(sectionText()).toContain('models.workingMemory.partialCanceled');
+ expect(sectionText()).toContain('models.workingMemory.discarded');
+ expect(english.models.workingMemory.discarded).toMatch(/discarded/);
+ expect(buttonNamed('common.retry')?.disabled).toBe(false);
+
+ // A step that failed out of memory ends its run, not the attempt: the other steps' measurements still count.
+ const ranOn = { attempt_steps: 6 };
+ serveSummary(
+ summary({
+ runs: [
+ run('run-1', 0, 'completed', null, 'attempt', ranOn),
+ run('run-2', 1, 'failed', 'CUDA out of memory', 'attempt', ranOn),
+ ...[3, 4, 5, 6].map((number) => run(`run-${String(number)}`, number, 'completed', null, 'attempt', ranOn)),
+ ],
+ })
+ );
+ await refreshSummary();
+ await expect.poll(sectionText).toContain('models.workingMemory.failed');
+ expect(sectionText()).not.toContain('models.workingMemory.discarded');
+ expect(sectionText()).toContain('models.workingMemory.failedKept');
+ });
+
+ it('claims no loss for an attempt canceled before it measured anything', async () => {
+ // Stop canceled the first step during its decode, which left an invalid window, and the rest while they waited:
+ // the server holds the attempt back, but nothing usable was measured.
+ const planned = { ...ABORTED, attempt_steps: 6 };
+ serveSummary(
+ summary({
+ runs: [
+ run('run-1', 1, 'canceled', null, 'attempt', planned),
+ ...[2, 3, 4, 5, 6].map((number) =>
+ run(`run-${String(number)}`, number, 'canceled', null, 'attempt', { ...planned, point_count: 0 })
+ ),
+ ],
+ })
+ );
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.canceled');
+
+ expect(sectionText()).not.toContain('models.workingMemory.discarded');
+ });
+
+ it('says nothing still counts when every step failed', async () => {
+ // Every decode ran out of memory; each left an invalid window.
+ const planned = { attempt_steps: 6 };
+ serveSummary(
+ summary({
+ runs: [1, 2, 3, 4, 5, 6].map((number) =>
+ run(`run-${String(number)}`, number, 'failed', 'CUDA out of memory', 'attempt', planned)
+ ),
+ })
+ );
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.failed');
+
+ expect(sectionText()).toContain('CUDA out of memory');
+ expect(sectionText()).not.toContain('models.workingMemory.failedKept');
+ expect(sectionText()).not.toContain('models.workingMemory.discarded');
+ });
+
+ it('says a submission that failed partway discarded the measurements of the runs it queued', async () => {
+ await renderSection();
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')).toBeDefined();
+ expect(host.querySelector('[role="status"]')?.textContent).toBe('');
+ const post = api.calibrateWorkingMemory.getMockImplementation()!;
+ api.calibrateWorkingMemory.mockImplementation((...args: unknown[]) =>
+ api.calibrateWorkingMemory.mock.calls.length === 3
+ ? Promise.reject(new ApiError('{"detail":"The queue has no room for the run"}', 409))
+ : post(...args)
+ );
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(3);
+
+ // The server lists the two runs queued before the refusal.
+ const attemptId = (api.calibrateWorkingMemory.mock.calls[0]![1] as { attemptId: string }).attemptId;
+ serveSummary(
+ summary({
+ runs: [1, 2].map((number) =>
+ run(`run-${String(number)}`, number, 'completed', null, attemptId, { ...ABORTED, attempt_steps: 6 })
+ ),
+ })
+ );
+ await refreshSummary();
+ await expect.poll(sectionText).toContain('models.workingMemory.partial');
+ expect(sectionText()).toContain('The queue has no room for the run');
+ expect(sectionText()).toContain('models.workingMemory.discarded');
+ // The outcome appears inside a live region that was there before, so it is announced.
+ expect(host.querySelector('[role="status"]')?.textContent).toContain('The queue has no room for the run');
+ expect(buttonNamed('common.retry')?.disabled).toBe(false);
+ });
+
+ it('heads the section with the current environment’s state, not an old environment’s', async () => {
+ serveSummary(
+ summary({
+ lines: [line('unusable', ['torch'], { env_id: 'old-env' }), line('in_use')],
+ runs: [run('run-1', 0, 'completed')],
+ })
+ );
+ await renderSection();
+ await expect.poll(() => host.querySelectorAll('table').length).toBe(2);
+
+ const header = [...host.querySelectorAll('p')].find(
+ (element) => element.textContent === DEVICE.name
+ )!.parentElement!;
+ expect(header.textContent).toBe(`${DEVICE.name}models.workingMemory.stateInUse`);
+ expect(sectionText()).not.toContain('models.workingMemory.neverCalibrated');
+
+ // With only an old environment's lines, they head it, and this GPU counts as not calibrated.
+ serveSummary(summary({ lines: [line('unusable', ['torch'], { env_id: 'old-env' })] }));
+ await refreshSummary();
+ await expect.poll(() => header.textContent).toBe(`${DEVICE.name}models.workingMemory.stateUnusable`);
+ expect(sectionText()).toContain('models.workingMemory.neverCalibrated');
+ });
+
+ it('shows lines other models measured as in use, naming them, with nothing of this model to reset', async () => {
+ const other = { model_key: 'other', name: 'Other SDXL', windows: 6 };
+ serveSummary(summary({ lines: [line('in_use', [], { measured_by: [other], own_windows: 0 })] }));
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.usesOthers');
+
+ expect(sectionText()).toContain('models.workingMemory.measuredBy(models=Other SDXL)');
+ expect(sectionText()).not.toContain('models.workingMemory.neverCalibrated');
+ expect(buttonNamed('common.reset')).toBeUndefined();
+ expect(buttonNamed('models.workingMemory.calibrate')?.disabled).toBe(false);
+
+ // Once this model measured too, it is listed first and has measurements to reset.
+ serveSummary(
+ summary({
+ lines: [line('in_use', [], { measured_by: [other, OWN], own_windows: 6 })],
+ runs: [run('run-1', 0, 'completed')],
+ })
+ );
+ await refreshSummary();
+ await expect.poll(sectionText).toContain('models.workingMemory.measuredBy(models=This SDXL, Other SDXL)');
+ expect(sectionText()).not.toContain('models.workingMemory.usesOthers');
+ expect(buttonNamed('common.reset')).toBeDefined();
+ });
+
+ it('keeps a finished attempt completed through a lost connection to the server', async () => {
+ await renderSection();
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')).toBeDefined();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+
+ const attemptId = (api.calibrateWorkingMemory.mock.calls[0]![1] as { attemptId: string }).attemptId;
+ const finished = summary({
+ lines: [line('in_use')],
+ runs: [1, 2, 3, 4, 5, 6].map((number) => run(`run-${String(number)}`, number, 'completed', null, attemptId)),
+ });
+ serveSummary(finished);
+ await refreshSummary();
+ await expect.poll(() => buttonNamed('models.workingMemory.recalibrate')).toBeDefined();
+
+ // The server goes away: every read fails as the browser reports an unreachable host.
+ const unreachable = () => Promise.reject(new TypeError('Failed to fetch'));
+ api.getWorkingMemoryPlan.mockImplementation(unreachable);
+ api.getWorkingMemoryStatus.mockImplementation(unreachable);
+ serveSummary(new TypeError('Failed to fetch'));
+ await refreshSummary();
+ await expect.poll(sectionText).toContain('models.workingMemory.loadFailed');
+
+ // It comes back with the same runs.
+ api.getWorkingMemoryPlan.mockImplementation(() => Promise.resolve(supportedPlan()));
+ api.getWorkingMemoryStatus.mockImplementation(() => Promise.resolve(status()));
+ serveSummary(finished);
+ await refreshSummary();
+ await expect.poll(() => buttonNamed('models.workingMemory.recalibrate')).toBeDefined();
+ expect(sectionText()).not.toContain('models.workingMemory.failed');
+ expect(sectionText()).not.toContain('Failed to fetch');
+ });
+
+ it('lets an attempt the server refused before it queued anything give way to one that ran after it', async () => {
+ const earlier = run('old', 0, 'completed', null, 'old');
+ serveSummary(summary({ lines: [line('in_use')], runs: [earlier] }));
+ api.calibrateWorkingMemory.mockImplementationOnce(() =>
+ Promise.reject(new ApiError('{"detail":"The queue has no room for the run"}', 409))
+ );
+ await renderSection();
+ await expect.poll(() => buttonNamed('models.workingMemory.recalibrate')).toBeDefined();
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.recalibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(sectionText).toContain('models.workingMemory.failed');
+ expect(sectionText()).toContain('The queue has no room for the run');
+
+ // Another tab, or a script, then calibrated to the end: that attempt is the latest one now.
+ serveSummary(
+ summary({
+ lines: [line('in_use')],
+ runs: [
+ earlier,
+ ...[1, 2, 3, 4, 5, 6].map((number) => run(`theirs-${String(number)}`, 100 + number, 'completed')),
+ ],
+ })
+ );
+ await refreshSummary();
+ await expect.poll(sectionText).not.toContain('models.workingMemory.failed');
+ expect(sectionText()).not.toContain('The queue has no room for the run');
+ expect(buttonNamed('models.workingMemory.recalibrate')?.disabled).toBe(false);
+ });
+
+ it('keeps a size the fit leaves out in the table, muted, naming why, in columns the other tables share', async () => {
+ const counted = line('in_use').sizes;
+ serveSummary(
+ summary({
+ lines: [
+ // Its row headers are narrower than the other table's, as a size note makes them in any language.
+ line('in_use', [], { sizes: counted.map((size) => ({ ...size, height: 64, width: 64 })) }),
+ line('in_use', [], {
+ line: 'decode_fp32',
+ sizes: [
+ ...counted,
+ {
+ counted: false,
+ excluded_reason: 'fragmented',
+ height: 1216,
+ measured_bytes: 5_900_000_000,
+ pixels: 1_478_656,
+ shipped_bytes: 4_100_000_000,
+ user_bytes: 3_300_000_000,
+ width: 1216,
+ windows: 3,
+ },
+ ],
+ }),
+ // Only an aborted attempt measured this line: none of its sizes counts, and the server says why.
+ line('insufficient', [], {
+ line: 'decode_bf16',
+ problem: 'Stop or an interrupted submission discarded the measurements of this line.',
+ sizes: counted.map((size) => ({ ...size, counted: false, excluded_reason: 'aborted_attempt' as const })),
+ }),
+ ],
+ runs: [run('run-1', 0, 'completed')],
+ })
+ );
+ await renderSection();
+ await expect.poll(() => host.querySelectorAll('table').length).toBe(3);
+
+ const [plain, mixed, discarded] = [...host.querySelectorAll('table')];
+ const [first, , excluded] = [...mixed!.querySelectorAll('tbody tr')];
+ expect([...discarded!.querySelectorAll('tbody th')].map((cell) => cell.textContent)).toEqual([
+ 'models.workingMemory.size(height=512,width=512)models.workingMemory.notCountedAborted',
+ 'models.workingMemory.size(height=1024,width=1024)models.workingMemory.notCountedAborted',
+ ]);
+ const stoppedLine = discarded!.closest('table')!.parentElement!.parentElement!;
+ expect(stoppedLine.textContent).toContain('models.workingMemory.stateInterrupted');
+ expect(stoppedLine.textContent).toContain('models.workingMemory.helpInterrupted');
+ expect(stoppedLine.textContent).not.toContain('models.workingMemory.stateInsufficient');
+ expect(sectionText()).not.toContain('Stop or an interrupted submission discarded the measurements of this line.');
+ // The reason is part of the row header, so it is read with the size.
+ expect(excluded!.querySelector('th')!.textContent).toBe(
+ 'models.workingMemory.size(height=1216,width=1216)models.workingMemory.notCountedFragmented'
+ );
+ expect(first!.querySelector('th')!.textContent).toBe('models.workingMemory.size(height=512,width=512)');
+ const colors = (row: Element) => [...row.children].map((cell) => getComputedStyle(cell).color);
+ expect(new Set(colors(excluded!)).size).toBe(1);
+ expect(colors(excluded!)[0]).not.toBe(colors(first!)[0]);
+ expect([...excluded!.children].map((cell) => getComputedStyle(cell).textAlign)).toEqual([
+ 'start',
+ 'end',
+ 'end',
+ 'end',
+ ]);
+ // The note under the size does not widen its column: both tables' columns start at the same place.
+ const columnEdges = (table: Element) =>
+ [...table.querySelectorAll('thead th')].map((cell) => Math.round(cell.getBoundingClientRect().left));
+ expect(columnEdges(mixed!)).toEqual(columnEdges(plain!));
+ });
+
+ it('explains each value column from an info button that opens by keyboard', async () => {
+ serveSummary(summary({ lines: [line('in_use')], runs: [run('run-1', 0, 'completed')] }));
+ await renderSection();
+ await expect.poll(() => host.querySelector('table')).not.toBeNull();
+
+ const headers = [...host.querySelectorAll('thead th')];
+ // The size column needs no explanation.
+ expect(headers[0]!.querySelector('button')).toBeNull();
+
+ for (const [index, column, hint] of [
+ [1, 'columnMeasured', 'hintMeasured'],
+ [2, 'columnShipped', 'hintShipped'],
+ [3, 'columnCalibrated', 'hintCalibrated'],
+ ] as const) {
+ const button = headers[index]!.querySelector('button')!;
+ const name = `models.workingMemory.aboutColumn(column=models.workingMemory.${column})`;
+ expect(button.getAttribute('aria-label')).toBe(name);
+
+ button.focus();
+ await act(() => userEvent.keyboard('{Enter}'));
+ await expect.poll(openDialog).not.toBeNull();
+ expect(openDialog()!.getAttribute('aria-label')).toBe(name);
+ expect(openDialog()!.textContent).toBe(`models.workingMemory.${hint}`);
+
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(openDialog).toBeNull();
+ await expect.poll(() => document.activeElement).toBe(button);
+ }
+ });
+
+ it('starts collapsed, keeps its panel out of the tab order, and asks for the plan only once opened', async () => {
+ serveSummary(summary({ lines: [line('in_use')], runs: [run('run-1', 0, 'completed')] }));
+ await renderSection({ expanded: false });
+
+ const toggle = sectionToggle();
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ const panel = document.getElementById(toggle.getAttribute('aria-controls')!)!;
+ expect(panel.hidden).toBe(true);
+ expect(buttonNamed('models.workingMemory.recalibrate')).toBeUndefined();
+ // The plan reads the GPU's free memory on the server; a collapsed section never asks for it.
+ await expect.poll(() => api.getWorkingMemorySummary.mock.calls.length).toBeGreaterThan(0);
+ expect(api.getWorkingMemoryPlan).not.toHaveBeenCalled();
+
+ toggle.focus();
+ await act(() => userEvent.keyboard('{Enter}'));
+ await expect.poll(() => buttonNamed('models.workingMemory.recalibrate')).toBeDefined();
+ expect(toggle.getAttribute('aria-expanded')).toBe('true');
+ expect(panel.hidden).toBe(false);
+ expect(api.getWorkingMemoryPlan).toHaveBeenCalledTimes(1);
+
+ await act(() => userEvent.keyboard('[Space]'));
+ await expect.poll(() => panel.hidden).toBe(true);
+ expect(toggle.getAttribute('aria-expanded')).toBe('false');
+ expect([...panel.querySelectorAll('button')].every((button) => button.getClientRects().length === 0)).toBe(true);
+ await act(() => userEvent.tab());
+ expect(panel.contains(document.activeElement)).toBe(false);
+ });
+
+ it('names the GPU and the state in the collapsed header, and the progress while a calibration runs', async () => {
+ api.getWorkingMemoryStatus.mockImplementation(() =>
+ Promise.resolve(
+ status({
+ device_classes: [
+ {
+ device_class: {
+ arch: null,
+ backend: 'cuda',
+ id: DEVICE.id,
+ name: DEVICE.name,
+ total_mib: 24_576,
+ vendor: 'x',
+ },
+ device_class_id: DEVICE.id,
+ envs: [],
+ is_current: true,
+ measurement_method: 'allocator',
+ measurement_verified: true,
+ point_counts: [],
+ problem: null,
+ runs: [],
+ usable: true,
+ },
+ ],
+ })
+ )
+ );
+ serveSummary(summary({ lines: [line('in_use')], runs: [run('run-1', 0, 'completed')] }));
+ await renderSection({ expanded: false });
+
+ const header = sectionToggle().closest('h3')!.parentElement!;
+ await expect
+ .poll(() => header.textContent)
+ .toBe(`models.workingMemory.title${DEVICE.name}models.workingMemory.stateInUse`);
+
+ // The server stores the attempt's step count with its runs, so the header counts the steps not yet queued too
+ // without a plan.
+ const planned = { attempt_steps: 6 };
+ serveSummary(
+ summary({
+ runs: [
+ run('run-1', 1, 'completed', null, 'attempt', planned),
+ run('run-2', 2, 'completed', null, 'attempt', planned),
+ run('run-3', 3, 'running', null, 'attempt', planned),
+ run('run-4', 4, 'running', null, 'attempt', planned),
+ ],
+ })
+ );
+ await refreshSummary();
+ await expect.poll(() => header.textContent).toContain('models.workingMemory.running(done=2,total=6)');
+ expect(header.textContent).not.toContain('models.workingMemory.stateInUse');
+ // A running calibration does not open the section.
+ expect(sectionToggle().getAttribute('aria-expanded')).toBe('false');
+ expect(api.getWorkingMemoryPlan).not.toHaveBeenCalled();
+ });
+
+ it('says the model was removed when the server no longer knows it', async () => {
+ serveSummary(new ApiError('{"detail":"The model could not be found"}', 404));
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.modelRemoved');
+
+ expect(sectionText()).not.toContain('models.workingMemory.loadFailed');
+ expect(buttonNamed('common.retry')).toBeUndefined();
+ });
+
+ it('resets after confirmation and restores focus', async () => {
+ serveSummary(summary({ lines: [line('in_use')], runs: [run('run-1', 0, 'completed')] }));
+ await renderSection();
+ await expect.poll(() => buttonNamed('common.reset')).toBeDefined();
+
+ await act(() => userEvent.click(buttonNamed('common.reset')!));
+ await expect.poll(openAlertDialog).not.toBeNull();
+ // A destructive confirmation opens on Cancel.
+ expect(document.activeElement?.textContent).toBe('Cancel');
+
+ api.resetWorkingMemory.mockImplementation(() => {
+ serveSummary(summary());
+ return Promise.resolve();
+ });
+ await act(() => userEvent.click(buttonNamed('common.reset', openAlertDialog()!)!));
+ await expect.poll(openAlertDialog).toBeNull();
+
+ expect(api.resetWorkingMemory).toHaveBeenCalledWith(MODEL_KEY, expect.anything());
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await expect.poll(() => document.activeElement?.textContent).toBe('models.workingMemory.calibrate');
+ });
+
+ it('disables Calibrate for an unsupported model, naming the reason', async () => {
+ api.getWorkingMemoryPlan.mockImplementation(() =>
+ Promise.resolve({
+ ...supportedPlan(),
+ cases: [],
+ reason: 'The inpaint variant does not generate from text alone.',
+ supported: false,
+ })
+ );
+ await renderSection();
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')).toBeDefined();
+
+ const button = buttonNamed('models.workingMemory.calibrate')!;
+ expect(button.disabled).toBe(true);
+ expect(document.getElementById(button.getAttribute('aria-describedby')!)?.textContent).toBe(
+ 'The inpaint variant does not generate from text alone.'
+ );
+ expect(sectionText()).not.toContain('models.workingMemory.neverCalibrated');
+ });
+
+ it('disables Calibrate without exactly one GPU, naming the status reason', async () => {
+ api.getWorkingMemoryStatus.mockImplementation(() =>
+ Promise.resolve(
+ status({
+ available: false,
+ current_device_class_id: null,
+ unavailable_reason: 'Calibration needs exactly one generation device; this machine has two.',
+ })
+ )
+ );
+ serveSummary(new ApiError('{"detail":"No device_class_id was given and there is no current one"}', 409));
+ await renderSection();
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')).toBeDefined();
+
+ const button = buttonNamed('models.workingMemory.calibrate')!;
+ expect(button.disabled).toBe(true);
+ expect(document.getElementById(button.getAttribute('aria-describedby')!)?.textContent).toBe(
+ 'Calibration needs exactly one generation device; this machine has two.'
+ );
+ // A missing device class is a state, not a load failure.
+ expect(sectionText()).not.toContain('models.workingMemory.loadFailed');
+ });
+
+ it('names an unusable store and flags hardware the method was not verified on', async () => {
+ serveSummary(
+ summary({
+ measurement_verified: false,
+ problem: 'schema_version 9 is newer than this version reads',
+ usable: false,
+ })
+ );
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.notVerified');
+
+ expect(buttonNamed('models.workingMemory.calibrate')?.disabled).toBe(true);
+ expect(sectionText()).toContain(
+ 'models.workingMemory.blockedStoreUnusable(problem=schema_version 9 is newer than this version reads)'
+ );
+ });
+
+ it('explains stale measurements and offers to recalibrate', async () => {
+ serveSummary(
+ summary({ lines: [line('stale', ['driver', 'setting.attention_type'])], runs: [run('run-1', 0, 'completed')] })
+ );
+ await renderSection();
+ await expect
+ .poll(sectionText)
+ .toContain('models.workingMemory.helpStale(facts=models.workingMemory.facts.driver, attention_type)');
+
+ expect(sectionText()).toContain('models.workingMemory.stateStale');
+ expect(buttonNamed('models.workingMemory.recalibrate')?.disabled).toBe(false);
+ });
+
+ it('reports a failed attempt with its error and offers Retry', async () => {
+ serveSummary(summary({ runs: [run('run-1', 0, 'completed'), run('run-2', 1, 'failed', 'CUDA out of memory')] }));
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.failed');
+
+ expect(sectionText()).toContain('CUDA out of memory');
+ expect(buttonNamed('common.retry')?.disabled).toBe(false);
+
+ // Retry is a new attempt: a new id, and retry keys that cannot collide with the failed attempt's.
+ await act(() => userEvent.click(buttonNamed('common.retry')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+ const requests = api.calibrateWorkingMemory.mock.calls.map(
+ ([, request]) => request as { attemptId: string; idempotencyKey: string }
+ );
+ expect(new Set(requests.map((request) => request.attemptId)).size).toBe(1);
+ expect(requests[0]!.attemptId).not.toBe('earlier-attempt');
+ expect(requests.every((request) => request.idempotencyKey.includes(requests[0]!.attemptId))).toBe(true);
+ });
+
+ it('shows no notice where the method is verified and leaves runs without an attempt id on their own', async () => {
+ serveSummary(
+ summary({
+ lines: [line('in_use')],
+ runs: [run('legacy-1', 0, 'failed', 'old failure', null), run('legacy-2', 1, 'completed', null, null)],
+ })
+ );
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.stateInUse');
+
+ expect(sectionText()).not.toContain('models.workingMemory.notVerified');
+ // Only the newest legacy run is the latest attempt, so the older failure is not reported.
+ expect(sectionText()).not.toContain('models.workingMemory.failed');
+ });
+
+ it('shows a skeleton while loading and a retryable error when a read fails', async () => {
+ let resolvePlan: (plan: WorkingMemoryPlan) => void = () => undefined;
+ api.getWorkingMemoryPlan.mockImplementationOnce(
+ () =>
+ new Promise<WorkingMemoryPlan>((resolve) => {
+ resolvePlan = resolve;
+ })
+ );
+ let failStatus: (error: Error) => void = () => undefined;
+ api.getWorkingMemoryStatus.mockImplementationOnce(
+ () =>
+ new Promise<WorkingMemoryStatus>((_resolve, reject) => {
+ failStatus = reject;
+ })
+ );
+ await renderSection();
+
+ // Opened for the first time, the panel waits for the plan.
+ await expect.poll(() => host.querySelector('[aria-busy="true"]')).not.toBeNull();
+ await act(() => {
+ resolvePlan(supportedPlan());
+ failStatus(new ApiError('{"detail":"store locked"}', 503));
+ });
+ await expect.poll(sectionText).toContain('models.workingMemory.loadFailed');
+ expect(sectionText()).toContain('store locked');
+
+ await act(() => userEvent.click(buttonNamed('common.retry')!));
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ });
+});
+
+describe('WorkingMemorySection plan freshness', () => {
+ /** One line instead of two, in fewer runs. */
+ const LARGER = [planCase('fp16', 768)];
+ const largerPlan = (): WorkingMemoryPlan => ({ ...supportedPlan(), cases: LARGER });
+ /** The lines and runs of `CASES`, at other sizes. */
+ const RESIZED = [planCase('fp16', 768), planCase('fp32', 768)];
+ const resizedPlan = (): WorkingMemoryPlan => ({ ...supportedPlan(), cases: RESIZED });
+ const FP32_ONLY = [planCase('fp32', 640)];
+
+ /** Holds the first step's response, so the attempt stays queuing; returns its release. */
+ const holdPost = () => {
+ let release = () => undefined as void;
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const post = api.calibrateWorkingMemory.getMockImplementation()!;
+ api.calibrateWorkingMemory.mockImplementationOnce(async (...args: unknown[]) => {
+ await held;
+ return post(...args);
+ });
+ return () => release();
+ };
+
+ const postedGraphs = () =>
+ api.calibrateWorkingMemory.mock.calls.map(([, request]) => (request as { graph: { id: string } }).graph.id);
+
+ const deferPlan = () => {
+ let settle: { resolve: (plan: WorkingMemoryPlan) => void; reject: (error: Error) => void } = {
+ reject: () => undefined,
+ resolve: () => undefined,
+ };
+ api.getWorkingMemoryPlan.mockImplementationOnce(
+ () =>
+ new Promise<WorkingMemoryPlan>((resolve, reject) => {
+ settle = { reject, resolve };
+ })
+ );
+ return () => settle;
+ };
+
+ it('reads the plan again on every opening, keeping the panel on the plan it has meanwhile', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ expect(api.getWorkingMemoryPlan).toHaveBeenCalledTimes(1);
+
+ await act(() => userEvent.click(sectionToggle()));
+ const pending = deferPlan();
+ await act(() => userEvent.click(sectionToggle()));
+
+ await expect.poll(() => api.getWorkingMemoryPlan.mock.calls.length).toBe(2);
+ // No skeleton while the second read runs: the panel keeps what it showed.
+ expect(host.querySelector('[aria-busy="true"]')).toBeNull();
+ expect(buttonNamed('models.workingMemory.calibrate')?.disabled).toBe(false);
+ await act(() => pending().resolve(largerPlan()));
+ });
+
+ it('reads the plan again before a start and on confirmation, busy meanwhile, and runs the plan it read', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ // The server plans larger sizes from now on.
+ api.getWorkingMemoryPlan.mockImplementation(() => Promise.resolve(largerPlan()));
+ const pending = deferPlan();
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')?.hasAttribute('data-loading')).toBe(true);
+ expect(openDialog()).toBeNull();
+
+ await act(() => pending().resolve(largerPlan()));
+ await expect.poll(openDialog).not.toBeNull();
+ expect(openDialog()!.textContent).toContain('models.workingMemory.size(height=768,width=768)');
+ expect(openDialog()!.textContent).not.toContain('models.workingMemory.size(height=512,width=512)');
+ expect(compile).toHaveBeenCalledTimes(1);
+ expect(compile).toHaveBeenCalledWith(LARGER, expect.any(Promise), expect.any(AbortSignal));
+
+ const confirming = deferPlan();
+ const start = buttonNamed('models.workingMemory.calibrate', openDialog()!)!;
+ // A second click before the first one rendered asks for no second read and starts no second attempt.
+ await act(() => {
+ start.click();
+ start.click();
+ });
+ await expect.poll(() => start.hasAttribute('data-loading')).toBe(true);
+ expect(api.getWorkingMemoryPlan).toHaveBeenCalledTimes(3);
+
+ await act(() => confirming().resolve(largerPlan()));
+ await expect.poll(openDialog).toBeNull();
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(3);
+ expect(compile).toHaveBeenCalledTimes(2);
+ expect(compile).toHaveBeenLastCalledWith(LARGER, expect.any(Promise), expect.any(AbortSignal));
+ });
+
+ it('starts new sizes read on confirmation without asking again, and names them in the progress', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ // A generation ended meanwhile: more memory is free, so the same lines run at larger sizes.
+ api.getWorkingMemoryPlan.mockImplementation(() => Promise.resolve(resizedPlan()));
+ const holdFirstPost = holdPost();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(openDialog).toBeNull();
+ expect(compile).toHaveBeenCalledTimes(2);
+ expect(compile).toHaveBeenLastCalledWith(RESIZED, expect.any(Promise), expect.any(AbortSignal));
+ await expect.poll(sectionText).toContain('models.workingMemory.queuing(done=0,total=6)');
+ expect(sectionText()).toContain(
+ 'models.workingMemory.pair(detail=fp16,label=models.workingMemory.size(height=768,width=768))'
+ );
+
+ await act(() => holdFirstPost());
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+ expect(postedGraphs()).toEqual([
+ RESIZED[0]!.id,
+ RESIZED[0]!.id,
+ RESIZED[0]!.id,
+ RESIZED[1]!.id,
+ RESIZED[1]!.id,
+ RESIZED[1]!.id,
+ ]);
+ });
+
+ it('compiles a confirmed calibration over the model record the server holds now, though its cases stayed', async () => {
+ // The tab loaded its models before the section opened, as the app does on start.
+ library.models = [mainModel('sd-1')];
+ await refreshModels();
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ expect(getModelsSnapshot().modelsByKey.get(MODEL_KEY)?.base).toBe('sd-1');
+
+ // Another tab changes the model's base while the dialog stands open. SD1 and SDXL decode alike, so the plan's
+ // cases stay the same, but the queue runs the model as the record now says.
+ library.models = [mainModel('sdxl')];
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+
+ const bases = api.calibrateWorkingMemory.mock.calls.map(
+ ([, request]) => (request as { graph: { base: string } }).graph.base
+ );
+ expect(new Set(bases)).toEqual(new Set(['sdxl']));
+ // Each step states the model as that compile read it, which the server compares with the record it holds then.
+ const identities = api.calibrateWorkingMemory.mock.calls.map(
+ ([, request]) => (request as { graphModels: Record<string, { base: string }> }).graphModels
+ );
+ expect(identities).toEqual(
+ identities.map(() => ({
+ [MODEL_KEY]: { base: 'sdxl', format: 'checkpoint', hash: 'hash', type: 'main', variant: null },
+ }))
+ );
+ });
+
+ it('starts nothing when the plan read on confirmation is no longer supported, naming why', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ // Another process took the GPU's memory while the dialog stood open.
+ api.getWorkingMemoryPlan.mockImplementationOnce(() =>
+ Promise.resolve({ ...supportedPlan(), cases: [], reason: 'Only 3 GB of the GPU are free now.', supported: false })
+ );
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(openDialog).toBeNull();
+ await expect.poll(sectionText).toContain('Only 3 GB of the GPU are free now.');
+ expect(buttonNamed('models.workingMemory.calibrate')?.disabled).toBe(true);
+ expect(compile).toHaveBeenCalledTimes(1);
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ // Calibrate is disabled now; focus returns to the section's toggle rather than the page.
+ await expect.poll(() => document.activeElement).toBe(sectionToggle());
+ });
+
+ it('shows runs read on confirmation that change what was confirmed, and starts them once confirmed again', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ expect(openDialog()!.textContent).not.toContain('models.workingMemory.dialogChanged');
+
+ // fp32 no longer fits: the plan measures one line, in fewer runs.
+ api.getWorkingMemoryPlan.mockImplementation(() => Promise.resolve(largerPlan()));
+ const pending = deferPlan();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ // The busy button is disabled, which drops its focus.
+ await expect.poll(() => document.activeElement).toBe(document.body);
+ await act(() => pending().resolve(largerPlan()));
+
+ await expect
+ .poll(() => openDialog()?.querySelector('[role="alert"]')?.textContent)
+ .toBe('models.workingMemory.dialogChanged');
+ const dialog = openDialog()!;
+ const notice = dialog.querySelector('[role="alert"]');
+ expect(dialog.textContent).toContain('models.workingMemory.size(height=768,width=768)');
+ expect(dialog.textContent).not.toContain('models.workingMemory.size(height=512,width=512)');
+ expect(dialog.textContent).toContain('models.workingMemory.dialogRuns(count=3)');
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ // Focus stays on the action that confirms what the dialog shows now.
+ await expect
+ .poll(() => dialog.contains(document.activeElement) && document.activeElement?.textContent)
+ .toBe('models.workingMemory.calibrate');
+
+ // It changes once more before the next confirmation: the notice is a new one, which is announced again.
+ api.getWorkingMemoryPlan.mockImplementation(() => Promise.resolve({ ...supportedPlan(), cases: FP32_ONLY }));
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', dialog)!));
+ await expect.poll(() => dialog.textContent).toContain('models.workingMemory.size(height=640,width=640)');
+ const secondNotice = dialog.querySelector('[role="alert"]');
+ expect(secondNotice?.textContent).toBe('models.workingMemory.dialogChanged');
+ expect(secondNotice).not.toBe(notice);
+ expect(notice?.isConnected).toBe(false);
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+
+ // Confirmed as shown: it starts.
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', dialog)!));
+ await expect.poll(openDialog).toBeNull();
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(3);
+ expect(postedGraphs()).toEqual([FP32_ONLY[0]!.id, FP32_ONLY[0]!.id, FP32_ONLY[0]!.id]);
+ });
+
+ it('aborts the compiler and queues nothing when the dialog closes while new sizes compile', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ api.getWorkingMemoryPlan.mockImplementation(() => Promise.resolve(resizedPlan()));
+ let compiling: AbortSignal | null = null;
+ compile.mockImplementationOnce(
+ (_cases, _models, signal) =>
+ new Promise((_resolve, reject) => {
+ compiling = signal;
+ signal.addEventListener('abort', () => reject(new Error('Compiling was stopped.')), { once: true });
+ })
+ );
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => compile.mock.calls.length).toBe(2);
+
+ await act(() => userEvent.keyboard('{Escape}'));
+ await expect.poll(openDialog).toBeNull();
+ expect(compiling!.aborted).toBe(true);
+ // The aborted compile is no reason to show: Calibrate is available as before.
+ expect(sectionText()).not.toContain('models.workingMemory.blockedCompile');
+ expect(buttonNamed('models.workingMemory.calibrate')?.disabled).toBe(false);
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ });
+
+ it('starts nothing when the dialog closes while the plan is read on confirmation', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ const opener = buttonNamed('models.workingMemory.calibrate')!;
+ await act(() => userEvent.click(opener));
+ await expect.poll(openDialog).not.toBeNull();
+
+ const pending = deferPlan();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect
+ .poll(() => buttonNamed('models.workingMemory.calibrate', openDialog()!)?.hasAttribute('data-loading'))
+ .toBe(true);
+ await act(() => userEvent.click(buttonNamed('common.cancel', openDialog()!)!));
+ await expect.poll(openDialog).toBeNull();
+ await expect.poll(() => document.activeElement).toBe(opener);
+
+ await act(() => pending().resolve(supportedPlan()));
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+
+ // The next opening compiles and confirms afresh.
+ await act(() => userEvent.click(opener));
+ await expect.poll(openDialog).not.toBeNull();
+ expect(compile).toHaveBeenCalledTimes(2);
+ const start = buttonNamed('models.workingMemory.calibrate', openDialog()!)!;
+ expect(start.hasAttribute('data-loading')).toBe(false);
+ await act(() => userEvent.click(start));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+ });
+
+ it('starts a confirmed calibration whose plan still holds after the section unmounted during the read', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ const pending = deferPlan();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ // Leaving the model's details does not take the confirmation back; only closing the dialog does.
+ await act(() => root.unmount());
+ await act(() => pending().resolve(supportedPlan()));
+
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+ expect(compile).toHaveBeenCalledTimes(2);
+ expect(compile).toHaveBeenLastCalledWith(CASES, expect.any(Promise), expect.any(AbortSignal));
+ });
+
+ it('shows a plan read that fails on confirmation as an error with a retry, starting nothing', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ api.getWorkingMemoryPlan.mockImplementationOnce(() => Promise.reject(new ApiError('{"detail":"GPU lost"}', 503)));
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(sectionText).toContain('models.workingMemory.loadFailed');
+ expect(sectionText()).toContain('GPU lost');
+ await expect.poll(openDialog).toBeNull();
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ // The panel holding the dialog's opener is gone; focus returns to the section's toggle rather than the page.
+ await expect.poll(() => document.activeElement).toBe(sectionToggle());
+ await act(() => userEvent.click(buttonNamed('common.retry')!));
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')?.disabled).toBe(false);
+ });
+
+ /** Another tab's attempt of the model, two of six steps done. */
+ const theirs = () =>
+ summary({
+ runs: [1, 2, 3, 4, 5, 6].map((number) =>
+ run(`theirs-${String(number)}`, number, number <= 2 ? 'completed' : 'running', null, 'theirs', {
+ attempt_steps: 6,
+ held_back: 'running',
+ })
+ ),
+ });
+
+ /**
+ * The GPU's status, a run of `modelKey` running on it: the server takes one attempt per GPU. With `isCurrent` false
+ * it runs on another device class.
+ */
+ const gpuBusyWith = (modelKey: string, { isCurrent = true }: { isCurrent?: boolean } = {}): WorkingMemoryStatus =>
+ status({
+ device_classes: [
+ {
+ device_class: {
+ arch: null,
+ backend: 'cuda',
+ id: DEVICE.id,
+ name: DEVICE.name,
+ total_mib: 24_576,
+ vendor: 'x',
+ },
+ device_class_id: DEVICE.id,
+ envs: [],
+ is_current: isCurrent,
+ measurement_method: 'allocator',
+ measurement_verified: true,
+ point_counts: [],
+ problem: null,
+ runs: [
+ {
+ attempt_id: 'theirs',
+ attempt_steps: 6,
+ created_at: new Date(T0).toISOString(),
+ env_id: 'env',
+ error: null,
+ error_code: null,
+ item_ids: [1],
+ model_hash: null,
+ model_key: modelKey,
+ point_count: 0,
+ run_id: 'theirs-1',
+ status: 'running',
+ user_id: 'other',
+ },
+ ],
+ usable: true,
+ },
+ ],
+ });
+
+ it('starts nothing when another tab started a calibration on this GPU while the dialog stood open', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ // Another model's calibration took the GPU: this section's summary cannot know, only a fresh status read can.
+ api.getWorkingMemoryStatus.mockImplementation(() => Promise.resolve(gpuBusyWith('other-model')));
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(openDialog).toBeNull();
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ // Beside Calibrate, naming the model that holds the GPU; no toast, which only the server's refusal raises.
+ await expect.poll(sectionText).toContain('models.workingMemory.busyOnGpu(model=other-model)');
+ expect(notify.info).not.toHaveBeenCalled();
+ expect(notify.error).not.toHaveBeenCalled();
+ // Nothing of this model runs: Calibrate stays available, and focus returns to it.
+ expect(sectionText()).not.toContain('models.workingMemory.failed');
+ await expect.poll(() => document.activeElement?.textContent).toBe('models.workingMemory.calibrate');
+ });
+
+ it('names the model that holds the GPU when Calibrate finds it busy, and keeps focus on Calibrate', async () => {
+ library.models = [mainModel('sdxl'), { ...mainModel('sd-1'), key: 'other-model', name: 'Other SD1' }];
+ await refreshModels();
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ // The status read right before the start answers late, so the busy Calibrate has dropped its focus by then.
+ let answer = () => undefined as void;
+ api.getWorkingMemoryStatus.mockImplementation(
+ () =>
+ new Promise<WorkingMemoryStatus>((resolve) => {
+ answer = () => resolve(gpuBusyWith('other-model'));
+ })
+ );
+
+ const opener = buttonNamed('models.workingMemory.calibrate')!;
+ await act(() => userEvent.click(opener));
+ await expect.poll(() => document.activeElement).toBe(document.body);
+ await act(() => answer());
+
+ const reason = 'models.workingMemory.busyOnGpu(model=Other SD1)';
+ await expect.poll(sectionText).toContain(reason);
+ expect(openDialog()).toBeNull();
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ expect(notify.info).not.toHaveBeenCalled();
+ expect(opener.disabled).toBe(false);
+ // Announced politely: a wait, not an error.
+ const described = document.getElementById(opener.getAttribute('aria-describedby')!);
+ expect(described?.textContent).toBe(reason);
+ expect(described?.getAttribute('role')).toBe('status');
+ await expect.poll(() => document.activeElement).toBe(opener);
+ });
+
+ it('shows this model’s own attempt with Stop when Calibrate finds it running, focusing Stop', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ serveSummary(theirs());
+ api.getWorkingMemoryStatus.mockImplementation(() => Promise.resolve(gpuBusyWith(MODEL_KEY)));
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+
+ await expect.poll(sectionText).toContain('models.workingMemory.running(done=2,total=6)');
+ expect(openDialog()).toBeNull();
+ expect(sectionText()).not.toContain('models.workingMemory.busyOnGpu');
+ await expect.poll(() => document.activeElement?.textContent).toBe('models.workingMemory.stop');
+ });
+
+ it('starts while another device class calibrates: the GPU this section names is free', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ api.getWorkingMemoryStatus.mockImplementation(() =>
+ Promise.resolve(gpuBusyWith('other-model', { isCurrent: false }))
+ );
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(6);
+ expect(sectionText()).not.toContain('models.workingMemory.busyOnGpu');
+ });
+
+ it('starts nothing when the status cannot be read right before the start, offering a retry', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ api.getWorkingMemoryStatus.mockImplementation(() =>
+ Promise.reject(new ApiError('{"detail":"The calibration store is locked"}', 503))
+ );
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(sectionText).toContain('models.workingMemory.loadFailed');
+ expect(sectionText()).toContain('The calibration store is locked');
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ expect(buttonNamed('common.retry')).toBeDefined();
+ });
+
+ it('says the model changed when the server refuses a later step for it, in its own words', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ const post = api.calibrateWorkingMemory.getMockImplementation()!;
+ const serverText = 'This SDXL changed after this calibration was planned (base). Calibrate again.';
+ api.calibrateWorkingMemory.mockImplementation((...args: unknown[]) =>
+ api.calibrateWorkingMemory.mock.calls.length === 3
+ ? Promise.reject(new ApiError(JSON.stringify({ detail: { code: 'model_changed', message: serverText } }), 409))
+ : post(...args)
+ );
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(3);
+
+ // The server lists the two runs queued before the refusal.
+ const attemptId = (api.calibrateWorkingMemory.mock.calls[0]![1] as { attemptId: string }).attemptId;
+ serveSummary(
+ summary({
+ runs: [1, 2].map((number) =>
+ run(`run-${String(number)}`, number, 'completed', null, attemptId, { ...ABORTED, attempt_steps: 6 })
+ ),
+ })
+ );
+ await refreshSummary();
+ await expect.poll(sectionText).toContain('models.workingMemory.partial');
+ expect(sectionText()).toContain('models.workingMemory.modelChanged');
+ expect(sectionText()).not.toContain(serverText);
+ });
+
+ it('stops posting when another calibration ran on the GPU between its steps, saying so in its own words', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ const post = api.calibrateWorkingMemory.getMockImplementation()!;
+ const serverText =
+ 'Another calibration ran on this GPU after this calibration started, so its measurements can no longer be combined. Calibrate again.';
+ api.calibrateWorkingMemory.mockImplementation((...args: unknown[]) =>
+ api.calibrateWorkingMemory.mock.calls.length === 2
+ ? Promise.reject(
+ new ApiError(JSON.stringify({ detail: { code: 'calibration_interleaved', message: serverText } }), 409)
+ )
+ : post(...args)
+ );
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+ await expect.poll(() => api.calibrateWorkingMemory.mock.calls.length).toBe(2);
+
+ // The server lists the one run queued before the refusal, held back with its short attempt.
+ const attemptId = (api.calibrateWorkingMemory.mock.calls[0]![1] as { attemptId: string }).attemptId;
+ serveSummary(summary({ runs: [run('run-1', 1, 'completed', null, attemptId, { ...ABORTED, attempt_steps: 6 })] }));
+ await refreshSummary();
+ await expect.poll(sectionText).toContain('models.workingMemory.interleaved');
+ expect(sectionText()).toContain('models.workingMemory.discarded');
+ expect(sectionText()).not.toContain(serverText);
+ expect(buttonNamed('common.retry')).toBeDefined();
+ // The refused step ends the attempt: no later step is posted.
+ expect(api.calibrateWorkingMemory).toHaveBeenCalledTimes(2);
+ expect(notify.info).not.toHaveBeenCalled();
+ });
+
+ it('follows an attempt of this model another tab started, found right before the start', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ serveSummary(theirs());
+ api.getWorkingMemoryStatus.mockImplementation(() => Promise.resolve(gpuBusyWith(MODEL_KEY)));
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(openDialog).toBeNull();
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ expect(notify.info).not.toHaveBeenCalled();
+ await expect.poll(sectionText).toContain('models.workingMemory.running(done=2,total=6)');
+ // Its own attempt shows as running, not as a reason naming it.
+ expect(sectionText()).not.toContain('models.workingMemory.busyOnGpu');
+ await expect.poll(() => document.activeElement?.textContent).toBe('models.workingMemory.stop');
+ });
+
+ it('says the model changed when its queued steps failed for it, offering to calibrate again', async () => {
+ // The record changed after queuing: the server failed the items as it admitted them.
+ const changed = { attempt_steps: 6, error_code: 'model_changed' as const };
+ serveSummary(
+ summary({
+ runs: [1, 2, 3, 4, 5, 6].map((number) =>
+ run(
+ `run-${String(number)}`,
+ number,
+ 'failed',
+ 'This SDXL changed after this calibration was planned (hash). Calibrate again.',
+ 'attempt',
+ changed
+ )
+ ),
+ })
+ );
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.failed');
+
+ expect(sectionText()).toContain('models.workingMemory.modelChanged');
+ expect(sectionText()).not.toContain('This SDXL changed after this calibration was planned');
+ expect(buttonNamed('common.retry')?.disabled).toBe(false);
+ });
+
+ it('follows the attempt the server says is already running, reading its refusal as no failure', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ // Another tab started one between the fresh read and the first step: the server refuses this attempt.
+ api.calibrateWorkingMemory.mockImplementationOnce(() => {
+ serveSummary(theirs());
+ return Promise.reject(
+ new ApiError(
+ '{"detail":{"code":"calibration_running","message":"Another calibration is still running on this GPU. Wait until it has finished, or stop it, then calibrate again."}}',
+ 409
+ )
+ );
+ });
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(() => notify.info.mock.calls).toEqual([['models.workingMemory.alreadyRunning']]);
+ expect(api.calibrateWorkingMemory).toHaveBeenCalledTimes(1);
+ await expect.poll(sectionText).toContain('models.workingMemory.running(done=2,total=6)');
+ expect(sectionText()).not.toContain('models.workingMemory.failed');
+ expect(sectionText()).not.toContain('models.workingMemory.partial');
+ });
+
+ it('says the model changed when the server refuses a step for it, offering to calibrate again', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ api.calibrateWorkingMemory.mockImplementationOnce(() =>
+ Promise.reject(
+ new ApiError(
+ '{"detail":{"code":"model_changed","message":"This SDXL changed after this calibration was planned (hash). Calibrate again."}}',
+ 409
+ )
+ )
+ );
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(sectionText).toContain('models.workingMemory.modelChanged');
+ expect(sectionText()).toContain('models.workingMemory.failed');
+ expect(api.calibrateWorkingMemory).toHaveBeenCalledTimes(1);
+ expect(buttonNamed('common.retry')?.disabled).toBe(false);
+ });
+
+ it('opens nothing when the model records cannot be read, naming why, and checks again on the next click', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('neverCalibrated');
+ // Compiling over the records the tab loaded earlier could build for a model the server has changed since.
+ library.failNext = new ApiError('{"detail":"The model records cannot be read"}', 503);
+
+ const opener = buttonNamed('models.workingMemory.calibrate')!;
+ await act(() => userEvent.click(opener));
+
+ await expect
+ .poll(sectionText)
+ .toContain('models.workingMemory.blockedCompile(problem=The model records cannot be read)');
+ expect(openDialog()).toBeNull();
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ expect(opener.disabled).toBe(false);
+
+ await act(() => userEvent.click(opener));
+ await expect.poll(openDialog).not.toBeNull();
+ expect(sectionText()).not.toContain('models.workingMemory.blockedCompile');
+ });
+
+ it('opens nothing for a plan that does not compile here, naming why, and checks again on the next click', async () => {
+ // The server plans a FLUX.1 decode; Generate cannot build it without a T5 encoder installed.
+ const flux = {
+ ...planCase('bf16', 768),
+ estimator: 'flux_vae_decode',
+ id: 'flux_vae_decode-decode-bf16-768x768',
+ settings: {},
+ };
+ api.getWorkingMemoryPlan.mockImplementation(() =>
+ Promise.resolve({ ...supportedPlan(), cases: [flux], estimators: ['flux_vae_decode'] })
+ );
+ const missing = `Case ${flux.id}: FLUX needs a T5 encoder; install one.`;
+ let refuse = () => undefined as void;
+ compile.mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ refuse = () => reject(new Error(missing));
+ })
+ );
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+
+ const opener = buttonNamed('models.workingMemory.calibrate')!;
+ await act(() => userEvent.click(opener));
+ // Busy while it compiles, which drops the button's focus.
+ await expect.poll(() => document.activeElement).toBe(document.body);
+ await act(() => refuse());
+
+ const reason = `models.workingMemory.blockedCompile(problem=${missing})`;
+ await expect.poll(sectionText).toContain(reason);
+ const alert = host.querySelector('[role="alert"]')!;
+ expect(alert.textContent).toBe(reason);
+ expect(openDialog()).toBeNull();
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ // Installing the encoder happens elsewhere: Calibrate stays available and names the reason.
+ expect(opener.disabled).toBe(false);
+ expect(document.getElementById(opener.getAttribute('aria-describedby')!)).toBe(alert);
+ await expect.poll(() => document.activeElement).toBe(opener);
+
+ await act(() => userEvent.click(opener));
+ await expect.poll(openDialog).not.toBeNull();
+ expect(sectionText()).not.toContain('models.workingMemory.blockedCompile');
+ });
+
+ it('closes the dialog naming why the plan read on confirmation does not compile, starting nothing', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(openDialog).not.toBeNull();
+
+ // New sizes are compiled again, and the encoder they need was removed meanwhile.
+ api.getWorkingMemoryPlan.mockImplementation(() => Promise.resolve(resizedPlan()));
+ compile.mockImplementationOnce(() => Promise.reject(new Error('The text encoder is not installed.')));
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate', openDialog()!)!));
+
+ await expect.poll(openDialog).toBeNull();
+ await expect
+ .poll(sectionText)
+ .toContain('models.workingMemory.blockedCompile(problem=The text encoder is not installed.)');
+ expect(api.calibrateWorkingMemory).not.toHaveBeenCalled();
+ await expect.poll(() => document.activeElement?.textContent).toBe('models.workingMemory.calibrate');
+ });
+
+ it('starts nothing when the plan read before a start is no longer supported, naming why', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ const pending = deferPlan();
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(() => document.activeElement).toBe(document.body);
+ await act(() =>
+ pending().resolve({
+ ...supportedPlan(),
+ cases: [],
+ reason: 'Only 3 GB of the GPU are free now.',
+ supported: false,
+ })
+ );
+
+ await expect.poll(sectionText).toContain('Only 3 GB of the GPU are free now.');
+ expect(buttonNamed('models.workingMemory.calibrate')?.disabled).toBe(true);
+ expect(openDialog()).toBeNull();
+ expect(compile).not.toHaveBeenCalled();
+ // Calibrate is disabled now; focus returns to the section's toggle rather than the page.
+ await expect.poll(() => document.activeElement).toBe(sectionToggle());
+ });
+
+ it('shows a plan read that fails before a start as an error with a retry', async () => {
+ await renderSection();
+ await expect.poll(sectionText).toContain('models.workingMemory.neverCalibrated');
+ const pending = deferPlan();
+
+ await act(() => userEvent.click(buttonNamed('models.workingMemory.calibrate')!));
+ await expect.poll(() => document.activeElement).toBe(document.body);
+ await act(() => pending().reject(new ApiError('{"detail":"GPU lost"}', 503)));
+
+ await expect.poll(sectionText).toContain('models.workingMemory.loadFailed');
+ expect(sectionText()).toContain('GPU lost');
+ expect(openDialog()).toBeNull();
+ // The panel holding Calibrate is gone; focus returns to the section's toggle rather than the page.
+ await expect.poll(() => document.activeElement).toBe(sectionToggle());
+ await act(() => userEvent.click(buttonNamed('common.retry')!));
+ await expect.poll(() => buttonNamed('models.workingMemory.calibrate')?.disabled).toBe(false);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemorySection.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemorySection.tsx
new file mode 100644
index 0000000000..a567b2bcbe
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/WorkingMemorySection.tsx
@@ -0,0 +1,692 @@
+/* eslint-disable react-perf/jsx-no-new-function-as-prop */
+import type {
+ CalibrationActivity,
+ CalibrationBlocker,
+ CalibrationCoverage,
+ CalibrationGraphCompiler,
+ CalibrationOutcome,
+ CompiledCalibration,
+ WorkingMemoryPlan,
+ WorkingMemoryStatus,
+ WorkingMemorySummary,
+} from '@features/models/core/workingMemory';
+
+import { Alert, Box, Collapsible, HStack, Progress, Skeleton, Stack, Text } from '@chakra-ui/react';
+import {
+ changesCalibration,
+ deriveCalibrationProgress,
+ describeCoverage,
+ getCalibrationBlocker,
+ isMeasurementMethodVerified,
+ modelCalibratingOnGpu,
+ planCalibrationSteps,
+} from '@features/models/core/workingMemory';
+import { useModelsSelector } from '@features/models/data/modelsStore';
+import {
+ attachWorkingMemoryRealtime,
+ compileWorkingMemoryPlan,
+ fetchCurrentWorkingMemoryPlan,
+ calibrationOnGpuNow,
+ refreshWorkingMemoryPlan,
+ resetCalibration,
+ startCalibration,
+ stopCalibration,
+ useLocalAttempt,
+} from '@features/models/data/workingMemoryCalibration';
+import {
+ workingMemoryPlanQueryOptions,
+ workingMemoryStatusQueryOptions,
+ workingMemorySummaryQueryOptions,
+} from '@features/models/data/workingMemoryQueries';
+import { useCalibrationGraphCompiler } from '@features/models/ui/ModelsUiContext';
+import { useNotify } from '@features/models/ui/useModelsNotify';
+import { useExitPresence } from '@platform/react/useExitRetainedValue';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { useConnectionStatusSelector } from '@platform/transport/connectionStore';
+import { ApiError, getApiErrorMessage } from '@platform/transport/http';
+import { Button } from '@platform/ui/Button';
+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { ChevronRightIcon } from 'lucide-react';
+import { useId, useRef, useState, type RefObject } from 'react';
+import { flushSync } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { WorkingMemoryCalibrateDialog } from './WorkingMemoryCalibrateDialog';
+import { LineMeasurements, LineStateBadge, SharedModelsList, useCaseLabel } from './WorkingMemoryParts';
+
+const INDICATOR_OPEN_STYLES = { transform: 'rotate(90deg)' } as const;
+const EMPTY_LIVE_REGION = { position: 'absolute' } as const;
+/** How long a Calibrate that found this model's own attempt running waits for Stop to render, in frames. */
+const STOP_WAIT_FRAMES = 30;
+
+/**
+ * Working-memory calibration of one model on this machine's GPU: what was measured and whether estimates use it,
+ * and the runs that measure it. Every read is the server's; the section keeps no copy of a run's state, so a reload or
+ * a reconnect shows the same thing.
+ *
+ * Collapsed on every visit; its header still names the GPU and the state, or the progress of a running calibration.
+ */
+export const WorkingMemorySection = ({ modelKey }: { modelKey: string }) => {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const headingId = useId();
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const [isOpen, setIsOpen] = useState(false);
+ // The plan measures the GPU's free memory on the server, so it loads only once the panel was opened.
+ const [wasOpened, setWasOpened] = useState(false);
+ const local = useLocalAttempt(modelKey);
+ const plan = useQuery({ ...workingMemoryPlanQueryOptions(modelKey), enabled: wasOpened });
+ const isConnected = useConnectionStatusSelector((snapshot) => snapshot.status === 'connected');
+ const summary = useQuery(
+ workingMemorySummaryQueryOptions(modelKey, { isConnected, isSubmitting: local?.submitting ?? false })
+ );
+ const status = useQuery(workingMemoryStatusQueryOptions());
+ const activityCaption = useActivityCaption();
+
+ useMountEffect(() => attachWorkingMemoryRealtime(queryClient));
+
+ // Without the plan, an attempt's step count comes from this tab's record or the attempt id.
+ const progress = deriveCalibrationProgress({
+ local,
+ runs: summary.data?.runs ?? [],
+ steps: plan.data ? planCalibrationSteps(plan.data) : [],
+ });
+ const coverage = describeCoverage(summary.data ?? null);
+ const deviceName = plan.data?.device_class?.name ?? (status.data ? currentDeviceName(status.data) : null);
+ const failed = [plan, summary, status].find((query) => query.isError);
+ let body;
+
+ // The plan and the summary know only installed models: this one was removed while its details were open.
+ if (failed?.error instanceof ApiError && failed.error.status === 404) {
+ body = (
+ <Text color="fg.muted" fontSize="sm">
+ {t('models.workingMemory.modelRemoved')}
+ </Text>
+ );
+ } else if (failed) {
+ body = (
+ <Stack align="start" gap="2" role="alert">
+ <Text color="fg.error" fontSize="sm">
+ {t('models.workingMemory.loadFailed')}
+ {': '}
+ {getApiErrorMessage(failed.error, t('common.unknownError'))}
+ </Text>
+ <Button
+ variant="outline"
+ onClick={() => {
+ for (const query of [plan, summary, status]) {
+ if (query.isError) {
+ void query.refetch();
+ }
+ }
+ }}
+ >
+ {t('common.retry')}
+ </Button>
+ </Stack>
+ );
+ } else if (!wasOpened) {
+ body = null;
+ } else if (plan.data === undefined || summary.data === undefined || status.data === undefined) {
+ body = (
+ <Stack aria-busy="true" aria-label={t('common.loading')} gap="2">
+ <Skeleton h="4" w="60%" />
+ <Skeleton h="16" w="full" />
+ </Stack>
+ );
+ } else {
+ body = (
+ <WorkingMemoryBody
+ coverage={coverage}
+ deviceName={deviceName}
+ focusFallbackRef={triggerRef}
+ modelKey={modelKey}
+ plan={plan.data}
+ progress={progress}
+ status={status.data}
+ summary={summary.data}
+ />
+ );
+ }
+
+ return (
+ <Collapsible.Root
+ open={isOpen}
+ onOpenChange={({ open }) => {
+ setIsOpen(open);
+ if (open) {
+ setWasOpened(true);
+ // Every opening reads the plan again: the GPU's free memory may have moved since the last one. The table
+ // keeps the plan it has meanwhile.
+ void refreshWorkingMemoryPlan(queryClient, modelKey);
+ }
+ }}
+ >
+ <Stack aria-labelledby={headingId} as="section" gap="3">
+ <Stack gap="0.5">
+ <HStack align="center" gap="2" justify="space-between" wrap="wrap">
+ <Text as="h3" fontSize="md" fontWeight="600" id={headingId}>
+ <Collapsible.Trigger ref={triggerRef} alignItems="center" display="flex" gap="1" rounded="sm">
+ <Collapsible.Indicator
+ _open={INDICATOR_OPEN_STYLES}
+ transition="transform var(--wb-motion-duration-medium)"
+ >
+ <ChevronRightIcon size="14" />
+ </Collapsible.Indicator>
+ {t('models.workingMemory.title')}
+ </Collapsible.Trigger>
+ </Text>
+ {/* Collapsed, the header says what the open panel would; open, the panel's own row does. */}
+ {!isOpen ? (
+ <HStack gap="2" minW="0" wrap="wrap">
+ {deviceName ? (
+ <Text color="fg.muted" fontSize="sm" overflowWrap="anywhere">
+ {deviceName}
+ </Text>
+ ) : null}
+ {progress.activity.kind === 'running' ? (
+ <Text color="fg.muted" fontSize="xs">
+ {activityCaption(progress.activity)}
+ </Text>
+ ) : summary.data?.usable ? (
+ <LineStateBadge state={coverage.state} />
+ ) : null}
+ </HStack>
+ ) : null}
+ </HStack>
+ <Text color="fg.subtle" fontSize="xs">
+ {t('models.workingMemory.description')}
+ </Text>
+ </Stack>
+ <Collapsible.Content>{body}</Collapsible.Content>
+ </Stack>
+ </Collapsible.Root>
+ );
+};
+
+const currentDeviceName = (status: WorkingMemoryStatus): string | null =>
+ status.device_classes.find((entry) => entry.is_current)?.device_class?.name ?? null;
+
+const WorkingMemoryBody = ({
+ coverage,
+ deviceName,
+ focusFallbackRef,
+ modelKey,
+ plan,
+ progress: { activity, outcome },
+ status,
+ summary,
+}: {
+ coverage: CalibrationCoverage;
+ deviceName: string | null;
+ /** Takes focus back when a confirmation's opener is gone or disabled. */
+ focusFallbackRef: RefObject<HTMLButtonElement | null>;
+ modelKey: string;
+ plan: WorkingMemoryPlan;
+ progress: ReturnType<typeof deriveCalibrationProgress>;
+ status: WorkingMemoryStatus;
+ summary: WorkingMemorySummary | null;
+}) => {
+ const { t } = useTranslation();
+ const notify = useNotify();
+ const queryClient = useQueryClient();
+ const compile = useCalibrationGraphCompiler();
+ const reasonId = useId();
+ const primaryRef = useRef<HTMLButtonElement>(null);
+ const stopRef = useRef<HTMLButtonElement>(null);
+ const [isCalibrateOpen, setIsCalibrateOpen] = useState(false);
+ const [isPreparing, setIsPreparing] = useState(false);
+ const [isConfirming, setIsConfirming] = useState(false);
+ // How often a confirmation found the plan changed in this dialog; each change is announced anew.
+ const [planChanges, setPlanChanges] = useState(0);
+ // Why the plan read last could not compile; shown as the reason Calibrate opened nothing.
+ const [compileError, setCompileError] = useState<string | null>(null);
+ // The confirmation under way; closing the dialog aborts it, which takes it back.
+ const confirmation = useRef<AbortController | null>(null);
+ const confirmRef = useRef<HTMLButtonElement>(null);
+ const [isStopOpen, setIsStopOpen] = useState(false);
+ const [isResetOpen, setIsResetOpen] = useState(false);
+ const calibrateDialog = useExitPresence(isCalibrateOpen);
+ const throughName = useModelsSelector((snapshot) =>
+ plan.calibrated_through ? (snapshot.modelsByKey.get(plan.calibrated_through)?.name ?? null) : null
+ );
+ // Another model's attempt holds this GPU: the server refuses a second one. This model's own shows as running.
+ const gpuHolderKey = modelCalibratingOnGpu(status);
+ const gpuHolder = gpuHolderKey !== null && gpuHolderKey !== modelKey ? gpuHolderKey : null;
+ const gpuHolderName = useModelsSelector((snapshot) =>
+ gpuHolder ? (snapshot.modelsByKey.get(gpuHolder)?.name ?? gpuHolder) : null
+ );
+
+ const isRunning = activity.kind === 'running';
+ const blocker: CalibrationBlocker | { kind: 'noCompiler' } | null =
+ compile === null ? { kind: 'noCompiler' } : getCalibrationBlocker({ isRunning, plan, status, summary });
+ const lines = summary?.lines ?? [];
+ const verified = isMeasurementMethodVerified(summary, status);
+ const primaryLabel =
+ outcome.kind === 'failed' || outcome.kind === 'partial'
+ ? t('common.retry')
+ : coverage.hasOwnMeasurements
+ ? t('models.workingMemory.recalibrate')
+ : t('models.workingMemory.calibrate');
+ const blockerText = useBlockerText(blocker);
+ // A plan that does not compile leaves Calibrate enabled: installing what is missing is fixed outside this section,
+ // and the next click checks again.
+ const compileReason = compileError ? t('models.workingMemory.blockedCompile', { problem: compileError }) : null;
+ // Calibrate stays enabled beside it: the next click checks again, and the model is named so it can be found.
+ const busyReason = gpuHolderName ? t('models.workingMemory.busyOnGpu', { model: gpuHolderName }) : null;
+ const reasonText = blockerText ?? compileReason ?? busyReason;
+
+ // The opener of a confirmation can disappear or be disabled once it is done; the section's toggle stays.
+ const getFinalFocus = () =>
+ primaryRef.current && !primaryRef.current.disabled ? primaryRef.current : focusFallbackRef.current;
+ // Starting records the attempt synchronously, so Stop has rendered by the time the closing dialog restores focus.
+ const getCalibrateFinalFocus = () => stopRef.current ?? getFinalFocus();
+
+ // Reads the plan as the server builds it now (its sizes follow the GPU's free memory and the stored measurements) and
+ // compiles its cases over the model records the server holds now. Graphs compiled earlier are never reused: equal
+ // cases can name a model whose record changed meanwhile. The section renders the plan read. A plan that no longer
+ // holds is `unavailable`: the section shows the new reason, or the read's error with a retry. A plan the server
+ // supports can still fail to compile here, say for a text encoder that is not installed. Last, the running check
+ // is made again on the fresh status of this GPU, which takes one attempt at a time: this section's summary knows
+ // only this model's runs, and may predate an attempt another tab started meanwhile.
+ const readCalibration = async (
+ compiler: CalibrationGraphCompiler,
+ signal?: AbortSignal
+ ): Promise<
+ | { kind: 'unavailable' }
+ | { kind: 'running'; own: boolean }
+ | { kind: 'uncompilable'; message: string }
+ | { graphs: CompiledCalibration[]; kind: 'ready'; plan: WorkingMemoryPlan }
+ > => {
+ const current = await fetchCurrentWorkingMemoryPlan(queryClient, modelKey).catch(() => null);
+
+ if (current === null || getCalibrationBlocker({ isRunning, plan: current, status, summary }) !== null) {
+ return { kind: 'unavailable' };
+ }
+
+ let graphs: CompiledCalibration[];
+
+ try {
+ graphs = await compileWorkingMemoryPlan(compiler, current, signal);
+ } catch (error) {
+ return { kind: 'uncompilable', message: getApiErrorMessage(error, t('common.unknownError')) };
+ }
+
+ // A failed read leaves its error in the status query, which the section shows with a retry. A busy GPU shows
+ // as this model's running attempt, or as the reason beside Calibrate naming the model that holds it.
+ const busy = await calibrationOnGpuNow(queryClient).catch(() => undefined);
+
+ if (busy === undefined) {
+ return { kind: 'unavailable' };
+ }
+
+ return busy === null ? { graphs, kind: 'ready', plan: current } : { kind: 'running', own: busy === modelKey };
+ };
+
+ // Only for an attempt the server refused at its first step, which slipped past that check: not a failure.
+ const notifyAlreadyRunning = () => notify.info(t('models.workingMemory.alreadyRunning'));
+
+ // The plan shown so far may be minutes old. Only a plan that still holds and compiles opens the dialog.
+ const prepareCalibration = async () => {
+ if (!compile) {
+ return;
+ }
+
+ setIsPreparing(true);
+ setCompileError(null);
+ const readiness = await readCalibration(compile);
+
+ if (readiness.kind === 'ready') {
+ setIsPreparing(false);
+ setPlanChanges(0);
+ setIsCalibrateOpen(true);
+ return;
+ }
+
+ if (readiness.kind === 'running' && readiness.own) {
+ // This model's attempt runs: Stop appears once the refreshed summary reaches the section, and Calibrate turns
+ // disabled then, which drops its focus. Wait a bounded number of frames for Stop, then move focus there.
+ flushSync(() => setIsPreparing(false));
+ for (let frame = 0; frame < STOP_WAIT_FRAMES && !stopRef.current; frame += 1) {
+ await new Promise<void>((resolve) => {
+ requestAnimationFrame(() => resolve());
+ });
+ }
+ if (document.activeElement === document.body || document.activeElement === primaryRef.current) {
+ (stopRef.current ?? focusFallbackRef.current)?.focus();
+ }
+ return;
+ }
+
+ // The busy Calibrate dropped focus and no dialog takes it, so return it unless it moved on meanwhile: to Calibrate,
+ // enabled again, beside a compile error or the model that holds the GPU; else to the section's toggle, since the plan read is about to disable Calibrate for its reason, or
+ // replace this panel with its error (the query tells the section a tick later).
+ flushSync(() => {
+ setIsPreparing(false);
+ setCompileError(readiness.kind === 'uncompilable' ? readiness.message : null);
+ });
+ if (document.activeElement === document.body) {
+ const target =
+ readiness.kind === 'running' || readiness.kind === 'uncompilable'
+ ? primaryRef.current
+ : focusFallbackRef.current;
+ target?.focus();
+ }
+ };
+
+ const closeCalibrate = () => {
+ confirmation.current?.abort();
+ confirmation.current = null;
+ setIsConfirming(false);
+ setIsCalibrateOpen(false);
+ };
+
+ // The dialog may have stood open while the GPU's free memory or the stored measurements moved: read the plan once
+ // more, and start what that read returns. A plan that no longer holds or compiles closes the dialog for the
+ // section's reason. One that changes what was confirmed (`changesCalibration`) starts nothing: the dialog shows it,
+ // flagged, to be confirmed again. New sizes alone start: a running generation moves them, and the dialog says sizes
+ // follow free memory. An unmount meanwhile does not take the confirmation back; only closing the dialog does.
+ const confirmCalibration = async () => {
+ if (!compile || confirmation.current) {
+ return;
+ }
+
+ const controller = new AbortController();
+ const confirmed = plan;
+ confirmation.current = controller;
+ setIsConfirming(true);
+ const readiness = await readCalibration(compile, controller.signal);
+
+ if (confirmation.current !== controller) {
+ return;
+ }
+
+ confirmation.current = null;
+
+ if (readiness.kind === 'ready' && changesCalibration(confirmed, readiness.plan)) {
+ // The busy Calibrate dropped focus: enable it first, then return focus to it unless focus moved on meanwhile.
+ flushSync(() => {
+ setIsConfirming(false);
+ setPlanChanges((count) => count + 1);
+ });
+ if (document.activeElement === document.body) {
+ confirmRef.current?.focus();
+ }
+ return;
+ }
+
+ setIsConfirming(false);
+ setIsCalibrateOpen(false);
+
+ if (readiness.kind === 'uncompilable') {
+ setCompileError(readiness.message);
+ } else if (readiness.kind === 'ready') {
+ // The server still refuses a second attempt that slipped past the check: its first step answers 409.
+ void startCalibration({ graphs: readiness.graphs, modelKey, plan: readiness.plan, queryClient }).then(
+ ({ alreadyRunning }) => {
+ if (alreadyRunning) {
+ notifyAlreadyRunning();
+ }
+ }
+ );
+ }
+ };
+
+ return (
+ <Stack gap="3">
+ <HStack align="center" gap="2" justify="space-between" wrap="wrap">
+ <HStack gap="2" minW="0" wrap="wrap">
+ {deviceName ? (
+ <Text fontSize="sm" fontWeight="600" overflowWrap="anywhere">
+ {deviceName}
+ </Text>
+ ) : null}
+ {/* Without a current device class or a readable store nothing can be said about this GPU's measurements. */}
+ {summary?.usable ? <LineStateBadge state={coverage.state} /> : null}
+ </HStack>
+ <HStack gap="1" wrap="wrap">
+ {isRunning ? (
+ <Button ref={stopRef} variant="outline" onClick={() => setIsStopOpen(true)}>
+ {t('models.workingMemory.stop')}
+ </Button>
+ ) : null}
+ {coverage.hasOwnMeasurements ? (
+ <Button
+ aria-describedby={isRunning && blockerText ? reasonId : undefined}
+ disabled={isRunning}
+ variant="ghost"
+ onClick={() => setIsResetOpen(true)}
+ >
+ {t('common.reset')}
+ </Button>
+ ) : null}
+ <Button
+ ref={primaryRef}
+ aria-describedby={reasonText ? reasonId : undefined}
+ disabled={blocker !== null}
+ loading={isPreparing}
+ variant="solid"
+ onClick={() => void prepareCalibration()}
+ >
+ {primaryLabel}
+ </Button>
+ </HStack>
+ </HStack>
+
+ {blockerText ? (
+ <Text color="fg.muted" fontSize="xs" id={reasonId}>
+ {blockerText}
+ </Text>
+ ) : compileReason ? (
+ // Announced: the click that asked for the dialog opened nothing.
+ <Text color="fg.error" fontSize="xs" id={reasonId} overflowWrap="anywhere" role="alert">
+ {compileReason}
+ </Text>
+ ) : busyReason ? (
+ <Text color="fg.muted" fontSize="xs" id={reasonId} overflowWrap="anywhere" role="status">
+ {busyReason}
+ </Text>
+ ) : null}
+
+ <ActivityPanel activity={activity} />
+ {/* Always present, so an outcome that appears (a stop, a failed submission) is announced; one already shown when
+ the section opens is part of the page and is not. Empty, it leaves the stack's flow and adds no gap. */}
+ <Box _empty={EMPTY_LIVE_REGION} role="status">
+ <OutcomePanel outcome={outcome} />
+ </Box>
+
+ {verified === false ? (
+ <Alert.Root status="warning" variant="surface">
+ <Alert.Indicator />
+ <Alert.Content>
+ <Alert.Title>{t('models.workingMemory.notVerified')}</Alert.Title>
+ </Alert.Content>
+ </Alert.Root>
+ ) : null}
+
+ {!coverage.hasCurrentLines && activity.kind === 'idle' && plan.supported && summary?.usable ? (
+ <Text color="fg.muted" fontSize="sm">
+ {t('models.workingMemory.neverCalibrated')}
+ </Text>
+ ) : null}
+ {coverage.usesOthersOnly ? (
+ <Text color="fg.muted" fontSize="sm">
+ {t('models.workingMemory.usesOthers')}
+ </Text>
+ ) : null}
+
+ {lines.length > 0 ? (
+ <Stack gap="4">
+ {lines.map((line) => (
+ <LineMeasurements
+ key={`${line.estimator}\u0000${line.line}\u0000${line.env_id}`}
+ line={line}
+ modelKey={modelKey}
+ />
+ ))}
+ </Stack>
+ ) : null}
+
+ {plan.shared_with.length > 0 ? <SharedModelsList models={plan.shared_with} /> : null}
+
+ <Stack color="fg.subtle" fontSize="xs" gap="1">
+ {plan.not_covered.length > 0 ? <Text>{t('models.workingMemory.encodeNotCovered')}</Text> : null}
+ <Text>{t('models.workingMemory.floorNote')}</Text>
+ </Stack>
+
+ {calibrateDialog.isMounted ? (
+ <WorkingMemoryCalibrateDialog
+ key={calibrateDialog.generation}
+ calibratedThroughName={throughName}
+ confirmRef={confirmRef}
+ deviceName={deviceName}
+ getFinalFocus={getCalibrateFinalFocus}
+ isConfirming={isConfirming}
+ isOpen={calibrateDialog.isOpen}
+ plan={plan}
+ planChanges={planChanges}
+ onClose={closeCalibrate}
+ onConfirm={() => void confirmCalibration()}
+ onExitComplete={calibrateDialog.release}
+ />
+ ) : null}
+ <ConfirmDialog
+ body={t('models.workingMemory.stopBody')}
+ confirmLabel={t('models.workingMemory.stop')}
+ finalFocusEl={getFinalFocus}
+ isOpen={isStopOpen}
+ title={t('models.workingMemory.stopTitle')}
+ onClose={() => setIsStopOpen(false)}
+ onConfirm={async () => {
+ try {
+ await stopCalibration({ modelKey, queryClient });
+ } catch (error) {
+ notify.error(t('models.workingMemory.stopFailed'), getApiErrorMessage(error, ''));
+ }
+ }}
+ />
+ <ConfirmDialog
+ body={t('models.workingMemory.resetBody')}
+ confirmLabel={t('common.reset')}
+ finalFocusEl={getFinalFocus}
+ isOpen={isResetOpen}
+ title={t('models.workingMemory.resetTitle')}
+ onClose={() => setIsResetOpen(false)}
+ onConfirm={async () => {
+ try {
+ await resetCalibration({ modelKey, queryClient });
+ notify.success(t('models.workingMemory.resetDone'));
+ } catch (error) {
+ notify.error(t('models.workingMemory.resetFailed'), getApiErrorMessage(error, ''));
+ }
+ }}
+ />
+ </Stack>
+ );
+};
+
+const useBlockerText = (blocker: CalibrationBlocker | { kind: 'noCompiler' } | null): string | null => {
+ const { t } = useTranslation();
+
+ switch (blocker?.kind) {
+ case undefined:
+ return null;
+ case 'unsupported':
+ return blocker.reason ?? t('models.workingMemory.blockedUnsupported');
+ case 'unavailable':
+ return blocker.reason ?? t('models.workingMemory.blockedUnavailable');
+ case 'storeUnusable':
+ return t('models.workingMemory.blockedStoreUnusable', { problem: blocker.reason ?? '' });
+ case 'running':
+ return t('models.workingMemory.blockedRunning');
+ case 'noCompiler':
+ return t('models.workingMemory.blockedUnavailable');
+ }
+};
+
+/** "Queuing: 2/18" while steps are posted, then "Calibrating: 5/18 runs". */
+const useActivityCaption = () => {
+ const { t } = useTranslation();
+
+ return ({ done, queuing, total }: Extract<CalibrationActivity, { kind: 'running' }>): string =>
+ queuing ? t('models.workingMemory.queuing', { done, total }) : t('models.workingMemory.running', { done, total });
+};
+
+const ActivityPanel = ({ activity }: { activity: CalibrationActivity }) => {
+ const { t } = useTranslation();
+ const caseLabel = useCaseLabel();
+ const activityCaption = useActivityCaption();
+
+ if (activity.kind !== 'running') {
+ return null;
+ }
+
+ const { currentCase, done, total } = activity;
+ const caption = activityCaption(activity);
+
+ return (
+ <Stack gap="1">
+ <Progress.Root colorPalette="accent" max={Math.max(total, 1)} value={done}>
+ {/* The track is the progressbar; without a name of its own it would be announced by its percentage. */}
+ <Progress.Track aria-label={t('models.workingMemory.progressLabel')} rounded="full">
+ <Progress.Range rounded="full" transition="width var(--wb-motion-duration-fast) ease" />
+ </Progress.Track>
+ </Progress.Root>
+ <Text aria-live="polite" color="fg.muted" fontSize="xs">
+ {caption}
+ {currentCase ? ` · ${caseLabel(currentCase)}` : null}
+ </Text>
+ </Stack>
+ );
+};
+
+const OutcomePanel = ({ outcome }: { outcome: CalibrationOutcome }) => {
+ const { t } = useTranslation();
+
+ if (outcome.kind === 'none' || outcome.kind === 'completed') {
+ return null;
+ }
+
+ // Canceled before anything was measured: nothing is lost.
+ if (outcome.kind === 'canceled') {
+ return (
+ <Text color="fg.muted" fontSize="sm">
+ {t('models.workingMemory.canceled')}
+ </Text>
+ );
+ }
+
+ // An aborted attempt feeds no fit, the steps it finished included; Calibrate starts a new one.
+ const discarded = outcome.discarded ? t('models.workingMemory.discarded') : null;
+ // A step that failed ends its run, not the attempt: what the other steps measured still counts.
+ const kept = outcome.kind === 'failed' && outcome.kept ? t('models.workingMemory.failedKept') : null;
+
+ const isFailed = outcome.kind === 'failed';
+ // A model whose record changed after its graphs compiled is calibrated again over the new record; an attempt another
+ // calibration ran in between of is calibrated again from its first step.
+ const detail =
+ (outcome.refusal === 'modelChanged'
+ ? t('models.workingMemory.modelChanged')
+ : outcome.refusal === 'interleaved'
+ ? t('models.workingMemory.interleaved')
+ : null) ||
+ outcome.error ||
+ (outcome.kind === 'partial'
+ ? !outcome.canceled && outcome.queued < outcome.total
+ ? t('models.workingMemory.partialQueued', { queued: outcome.queued, total: outcome.total })
+ : t('models.workingMemory.partialCanceled')
+ : null);
+
+ return (
+ <Alert.Root status={isFailed ? 'error' : 'warning'} variant="surface">
+ <Alert.Indicator />
+ <Alert.Content>
+ <Alert.Title>{isFailed ? t('models.workingMemory.failed') : t('models.workingMemory.partial')}</Alert.Title>
+ {detail ? <Alert.Description overflowWrap="anywhere">{detail}</Alert.Description> : null}
+ {discarded ? <Alert.Description>{discarded}</Alert.Description> : null}
+ {kept ? <Alert.Description>{kept}</Alert.Description> : null}
+ </Alert.Content>
+ </Alert.Root>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx
index 7b08e2da72..406c17e817 100644
--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.browser.test.tsx
@@ -1,6 +1,6 @@
-import { ChakraProvider } from '@chakra-ui/react';
+import { ChakraProvider, Text } from '@chakra-ui/react';
import { system } from '@theme/system';
-import { act, useCallback, useState } from 'react';
+import { act, useCallback, useState, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, describe, expect, it } from 'vitest';
import { userEvent } from 'vitest/browser';
@@ -109,6 +109,59 @@ describe('ConfirmDialog', () => {
}
});
+ it('is described by a text body, which looks as the plain paragraph it was before', async () => {
+ // Long enough to wrap in the dialog, so a line height of its own shows in the box too.
+ const BODY =
+ 'Queued runs are canceled, and all of this calibration’s measurements are discarded, finished runs included.';
+ /** Opens a dialog with `body` and reads how the paragraph holding BODY renders. */
+ const readParagraph = async (body: ReactNode) => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root?.render(
+ <ChakraProvider value={system}>
+ <ConfirmDialog body={body} confirmLabel="Stop" isOpen title="Stop?" onClose={noop} onConfirm={noop} />
+ </ChakraProvider>
+ )
+ );
+ await expect.poll(() => document.querySelector('[role="alertdialog"]')?.getAttribute('data-state')).toBe('open');
+ const dialog = document.querySelector('[role="alertdialog"]')!;
+ const paragraph = [...dialog.querySelectorAll('*')].find(
+ (element) => element.childElementCount === 0 && element.textContent === BODY
+ )!;
+ const style = getComputedStyle(paragraph);
+ const read = {
+ describes: dialog.getAttribute('aria-describedby') === paragraph.id,
+ style: {
+ color: style.color,
+ fontSize: style.fontSize,
+ fontWeight: style.fontWeight,
+ height: paragraph.getBoundingClientRect().height,
+ letterSpacing: style.letterSpacing,
+ lineHeight: style.lineHeight,
+ margin: style.margin,
+ },
+ };
+
+ await act(() => root?.unmount());
+ host.remove();
+ host = null;
+ root = null;
+ return read;
+ };
+
+ const described = await readParagraph(BODY);
+ // What a text body rendered before it described the dialog.
+ const plain = await readParagraph(<Text fontSize="md">{BODY}</Text>);
+
+ expect(described.describes).toBe(true);
+ expect(plain.describes).toBe(false);
+ expect(described.style).toEqual(plain.style);
+ // It wraps, so the comparison covers the lines' spacing.
+ expect(described.style.height).toBeGreaterThan(Number.parseFloat(described.style.lineHeight) * 1.5);
+ });
+
const renderDialog = async (isDestructive: boolean) => {
host = document.createElement('div');
document.body.append(host);
diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
index c81c8607d4..6ad4a7017f 100644
--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx
@@ -1,4 +1,4 @@
-import { Portal, Stack, Text } from '@chakra-ui/react';
+import { Portal, Stack } from '@chakra-ui/react';
import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';
import { useCallback, useMemo, useRef, useState, type ReactNode } from 'react';
@@ -109,7 +109,16 @@ export const ConfirmDialog = ({
</Dialog.Header>
<Dialog.Body>
<Stack gap="2">
- {typeof text.body === 'string' ? <Text fontSize="md">{text.body}</Text> : text.body}
+ {/* A text body describes the dialog (`aria-describedby`), so the consequence is read when it opens. It
+ keeps the body's look, not the description recipe's muted color and tighter `md` line height. A
+ composed body names its own description. */}
+ {typeof text.body === 'string' ? (
+ <Dialog.Description color="fg" fontSize="md" lineHeight="inherit">
+ {text.body}
+ </Dialog.Description>
+ ) : (
+ text.body
+ )}
</Stack>
</Dialog.Body>
<Dialog.Footer>
diff --git a/scripts/family_e2e/__main__.py b/scripts/family_e2e/__main__.py
index e9fd859831..7ae1b434bf 100644
--- a/scripts/family_e2e/__main__.py
+++ b/scripts/family_e2e/__main__.py
@@ -15,10 +15,11 @@ from datetime import datetime, timezone
from pathlib import Path
from scripts.family_e2e.bundle import write_bundle
+from scripts.family_e2e.calibration import PROBE_REASON, CalibrationError, read_store_files
from scripts.family_e2e.detach import RUNNER_LOG, DetachError, spawn_runner
from scripts.family_e2e.gpu_memory import UnsupportedPlatformError
from scripts.family_e2e.graphs import ExportError
-from scripts.family_e2e.manifest import Manifest, ManifestError, load_manifest
+from scripts.family_e2e.manifest import DEFAULT_ARM, Manifest, ManifestError, load_manifest
from scripts.family_e2e.metrics import MB
from scripts.family_e2e.records import RUN_INFO_FILE, load_records, load_run_info, run_id_profile, write_run_info
from scripts.family_e2e.references import AcceptError, accept
@@ -30,19 +31,20 @@ from scripts.family_e2e.runner import (
finish_run,
gpu_lock,
is_alive,
- kill_identified,
+ kill_recorded,
load_run_manifest,
new_run,
open_gpu,
preflight,
read_heartbeat,
remaining_steps,
- remove_scratch_roots,
run,
run_lock,
+ save_calibration,
+ scratch_root,
wait_for_runner,
)
-from scripts.family_e2e.server import ServerError
+from scripts.family_e2e.server import ServerError, remove_tree
logger = logging.getLogger("family_e2e")
# Windows refuses to open heartbeat.json for a moment while the runner replaces it.
@@ -56,6 +58,7 @@ EXPECTED_ERRORS = (
AcceptError,
DetachError,
UnsupportedPlatformError,
+ CalibrationError,
# load_records names the malformed line of a damaged records.jsonl.
ValueError,
)
@@ -114,7 +117,7 @@ def _start_runner(run_dir: Path) -> int:
def cmd_start(args: argparse.Namespace) -> int:
_check_startable(load_manifest(args.manifest))
- run_dir = new_run(args.manifest, args.family, args.case)
+ run_dir = new_run(args.manifest, args.family, args.case, calibrate=args.calibrate)
_print_started(run_dir, _start_runner(run_dir))
return 0
@@ -161,8 +164,14 @@ def cmd_status(args: argparse.Namespace) -> int:
print(f"run {info.run_id} ({info.status})")
print(f"dir {run_dir}")
print(f"progress {len(info.plan) - len(left)}/{len(info.plan)} steps final, {len(records)} records")
- print(f"invalid {sum(1 for r in records if r.invalid_reasons)} records with invalid reasons")
+ # Every step of a calibration run carries the probe's reason; only the others make a record invalid there.
+ invalid = sum(1 for r in records if set(r.invalid_reasons) - {PROBE_REASON})
+ print(f"invalid {invalid} records with invalid reasons")
print(f"errors {sum(1 for r in records if r.status != 'completed')} records not completed")
+ if info.calibrate:
+ print(
+ f"calibrate time and VRAM not rated; {len(info.calibration_exports)} store exports in {run_dir / 'calibration'}"
+ )
if heartbeat:
updated = datetime.fromisoformat(heartbeat["updated_at"])
age = (datetime.now(timezone.utc) - updated).total_seconds()
@@ -178,8 +187,9 @@ def cmd_status(args: argparse.Namespace) -> int:
def cmd_stop(args: argparse.Namespace) -> int:
run_dir = _resolve_run(args.run, args.manifest)
- # Marked before the heartbeat is read, under the run lock a runner registers under: a runner registered before is
- # in the heartbeat and is killed, one that registers after finds the run stopped and leaves it untouched.
+ # Marked before the heartbeat is read, under the run lock a runner registers and spawns each server under: a runner
+ # or server that came before is in the heartbeat and is killed, and none comes after (the runner finds the run
+ # stopped and leaves it untouched).
was_running = finish_run(run_dir, "stopped")
heartbeat = read_heartbeat(run_dir)
# A running run has a registered runner, so an empty read is most likely one that met the runner's replace.
@@ -188,15 +198,39 @@ def cmd_stop(args: argparse.Namespace) -> int:
time.sleep(STOP_HEARTBEAT_POLL_S)
heartbeat = read_heartbeat(run_dir)
# The runner first: it would otherwise notice its server dying and record a crash.
- for role in ("runner", *SERVER_ROLES):
- if kill_identified(heartbeat.get(role)):
- print(f"killed {role} (pid {int(heartbeat[role][0])}) and its descendants")
+ killed, survivors = kill_recorded([("runner", heartbeat.get("runner"))])
+ killed_servers, left = kill_recorded([(role, heartbeat.get(role)) for role in SERVER_ROLES])
+ killed += killed_servers
+ survivors = ", ".join(s for s in (survivors, left) if s)
+ if survivors:
+ # What still runs may still write to its scratch root and the calibration store in it.
+ raise RunnerError(
+ f"the run's processes survived the kill: {survivors}. {run_dir.name} is marked stopped; its scratch roots "
+ "stay as they are. End them, then `stop` again"
+ )
+ for role, pid in killed:
+ print(f"killed {role} (pid {pid}) and its descendants")
info = load_run_info(run_dir)
- # Nothing of the run is alive any more, so its scratch roots are unused.
- for leftover in remove_scratch_roots(_data_dir(run_dir), info):
- print(f"could not remove {leftover}")
+ unsaved = []
+ for arm in sorted({DEFAULT_ARM, *info.environments}):
+ root = scratch_root(_data_dir(run_dir), info.run_id, arm)
+ if info.calibrate:
+ # The killed server left its calibration store in the scratch root; the root goes next.
+ try:
+ exports = save_calibration(run_dir, read_store_files(root))
+ except OSError as e:
+ # The root holds the only copy of the lifetime's windows; `resume` saves it first.
+ unsaved.append(f"could not save the calibration store ({e}); kept the scratch root {root} with it")
+ continue
+ for export in exports:
+ print(f"saved the calibration store {run_dir / export.export}")
+ # Nothing of the run is alive any more, so its scratch roots are unused.
+ for leftover in remove_tree(root):
+ print(f"could not remove {leftover}")
print(f"{info.run_id} stopped; continue with: python -m scripts.family_e2e resume {run_dir}")
- return 0
+ for message in unsaved:
+ print(f"error: {message}. Fix the cause and `resume`, which saves it first", file=sys.stderr)
+ return 2 if unsaved else 0
def cmd_accept(args: argparse.Namespace) -> int:
@@ -239,6 +273,11 @@ def _parser() -> argparse.ArgumentParser:
start.add_argument("--manifest", type=Path, required=True)
start.add_argument("--family", action="append", default=[], help="only this family (repeatable)")
start.add_argument("--case", action="append", default=[], help="only this case id (repeatable)")
+ start.add_argument(
+ "--calibrate",
+ action="store_true",
+ help="measure working memory: submit every step through the server's calibrate route and save its exports",
+ )
start.set_defaults(handler=cmd_start)
runner = commands.add_parser("run", help="run the remaining steps of a run in the foreground (what start launches)")
diff --git a/scripts/family_e2e/calibration.py b/scripts/family_e2e/calibration.py
new file mode 100644
index 0000000000..5ccc552e30
--- /dev/null
+++ b/scripts/family_e2e/calibration.py
@@ -0,0 +1,141 @@
+"""Calibration runs: each step goes through the server's working-memory calibrate route instead of enqueue_batch.
+
+The server measures every model operation of such a queue item with its working-memory probe and keeps the windows in
+its calibration store, one file per device class under `<db_dir>/working_memory/` of the scratch root. The scratch root
+goes at the end of each server lifetime, so every lifetime saves its store into the run's `calibration/` first: the
+export route's bytes and the status while the server still runs, or the store file itself when the server died or was
+stopped. `scripts/working_memory/build_shipped.py` turns the exports into shipped working-memory data.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Literal
+from urllib.parse import quote
+
+from scripts.family_e2e.client import ApiError, InvokeClient
+from scripts.family_e2e.records import (
+ CalibrationExport,
+ CalibrationSubmission,
+ ModelIdentity,
+ RunInfo,
+ write_bytes_atomic,
+ write_run_info,
+)
+from scripts.family_e2e.server import SCRATCH_PATHS
+
+CALIBRATION_DIR = "calibration"
+STATUS_PATH = "/api/v2/models/working_memory/status"
+EXPORT_PATH = "/api/v2/models/working_memory/export"
+# The store's directory under the root's db_dir (invokeai/app/api/dependencies.py) and its file names
+# (working_memory_calibration_store.py). Copied, not imported: the tool must not import invokeai, which imports torch.
+STORE_DIR = "working_memory"
+STORE_FILE = re.compile(r"^[0-9a-f]{16}\.json$")
+PROBE_REASON = "calibration run: the probe synchronizes and empties the allocator cache around every model operation"
+
+
+CASE_REFUSALS = (404, 422)
+"""Calibrate refusals that concern one case (an unknown model, a graph the run cannot measure); the step gets an error
+record and the run goes on. Any other error response would refuse every later step too."""
+
+
+class CalibrationError(RuntimeError):
+ """The server cannot run a calibration run, or refused one."""
+
+
+class CaseRefused(CalibrationError):
+ """The server refused one case's calibration run (`CASE_REFUSALS`)."""
+
+
+def check_available(client: InvokeClient) -> None:
+ status = client.get(STATUS_PATH)
+ if not status.get("available"):
+ raise CalibrationError(f"the server cannot calibrate: {status.get('unavailable_reason')}")
+
+
+def submit(
+ client: InvokeClient, model_key: str, batch: dict[str, Any], models: Iterable[ModelIdentity]
+) -> tuple[int, CalibrationSubmission]:
+ """Starts a calibration run of the batch's graph and data; returns its one queue item and the run.
+
+ `models` are the graph's models as the configs it was compiled from have them (`RunInfo.case_models`): the server
+ refuses the run when a model's record differs from that now, so the graph measures what was compiled.
+ A refusal raises `CaseRefused` for a `CASE_REFUSALS` status and CalibrationError for any other error response.
+ Each server lifetime has a fresh queue and store and the tool submits each attempt once, so it sends no retry key.
+ """
+ graph_models = {
+ model.key: {
+ "hash": model.hash,
+ "base": model.base,
+ "type": model.type,
+ "format": model.format,
+ "variant": model.variant,
+ }
+ for model in models
+ }
+ body: dict[str, Any] = {"graph": batch["graph"], "graph_models": graph_models}
+ if batch.get("data"):
+ body["data"] = batch["data"]
+ try:
+ created = client.post(f"/api/v2/models/i/{quote(model_key, safe='')}/working_memory/calibrate", body)
+ except ApiError as e:
+ refused = CaseRefused if e.status_code in CASE_REFUSALS else CalibrationError
+ raise refused(f"the server refused the calibration run: {e}") from e
+ if len(created["item_ids"]) != 1:
+ raise CalibrationError(f"expected one queue item from the calibration run, got {len(created['item_ids'])}")
+ submission = CalibrationSubmission(run_id=created["run_id"], device_class_id=created["device_class_id"])
+ return created["item_ids"][0], submission
+
+
+Stores = list[tuple[str, bytes]]
+"""(device class id, store bytes) per saved store."""
+
+
+def save(run_dir: Path, info: RunInfo, stores: Stores, status: bytes | None) -> list[CalibrationExport]:
+ """Writes one lifetime's stores into the run's `calibration/` and lists them in `info`, which it writes to run.json.
+ Stores from the export routes come with the status; store files copied from a scratch root come without one. Hold
+ the run lock with `info` read under it: `runner.save_calibration` does."""
+ source: Literal["api", "store_file"] = "store_file" if status is None else "api"
+ lifetime = max((e.lifetime for e in info.calibration_exports), default=0) + 1
+ (run_dir / CALIBRATION_DIR).mkdir(exist_ok=True)
+ status_path = None
+ if status is not None:
+ status_path = f"{CALIBRATION_DIR}/{info.run_id}-{lifetime}-status.json"
+ write_bytes_atomic(run_dir / status_path, status)
+ saved_at = datetime.now(timezone.utc).isoformat(timespec="seconds")
+ exports = []
+ for device_class_id, raw in stores:
+ path = f"{CALIBRATION_DIR}/{info.run_id}-{lifetime}-{device_class_id}.json"
+ write_bytes_atomic(run_dir / path, raw)
+ exports.append(
+ CalibrationExport(
+ lifetime=lifetime,
+ device_class_id=device_class_id,
+ export=path,
+ status=status_path,
+ source=source,
+ saved_at=saved_at,
+ )
+ )
+ info.calibration_exports.extend(exports)
+ write_run_info(run_dir, info)
+ return exports
+
+
+def fetch_exports(client: InvokeClient, device_class_ids: Iterable[str]) -> tuple[Stores, bytes]:
+ """The store of every device class the lifetime's runs were created for, and the status, from the export routes."""
+ stores = [
+ (device_class_id, client.get_bytes(EXPORT_PATH, device_class_id=device_class_id))
+ for device_class_id in sorted(set(device_class_ids))
+ ]
+ return stores, client.get_bytes(STATUS_PATH)
+
+
+def read_store_files(scratch_root: Path) -> Stores:
+ """The store files of a scratch root whose server is gone; none when it has none."""
+ store_dir = scratch_root / SCRATCH_PATHS["db_dir"] / STORE_DIR
+ files = sorted(p for p in store_dir.glob("*.json") if STORE_FILE.match(p.name)) if store_dir.is_dir() else []
+ return [(path.stem, path.read_bytes()) for path in files]
diff --git a/scripts/family_e2e/client.py b/scripts/family_e2e/client.py
index ed5949c1f1..441fde0593 100644
--- a/scripts/family_e2e/client.py
+++ b/scripts/family_e2e/client.py
@@ -45,7 +45,10 @@ PREVIEW_INTERVAL_S = 0.1
class ApiError(RuntimeError):
- pass
+ def __init__(self, message: str, status_code: int | None = None) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+ """The HTTP status of an error response; None for an accepted response the client cannot use."""
class InvokeClient:
@@ -56,12 +59,15 @@ class InvokeClient:
def _request(self, method: str, path: str, **kwargs: Any) -> requests.Response:
response = self._http.request(method, self.base_url + path, timeout=REQUEST_TIMEOUT_S, **kwargs)
if response.status_code >= 400:
- raise ApiError(f"{method} {path} -> {response.status_code}: {response.text[:2000]}")
+ raise ApiError(f"{method} {path} -> {response.status_code}: {response.text[:2000]}", response.status_code)
return response
def get(self, path: str, **params: Any) -> Any:
return self._request("GET", path, params=params or None).json()
+ def get_bytes(self, path: str, **params: Any) -> bytes:
+ return self._request("GET", path, params=params or None).content
+
def post(self, path: str, body: Any = None) -> Any:
return self._request("POST", path, json=body).json()
diff --git a/scripts/family_e2e/graphs.py b/scripts/family_e2e/graphs.py
index 4313ed85ac..77e2e9d0b0 100644
--- a/scripts/family_e2e/graphs.py
+++ b/scripts/family_e2e/graphs.py
@@ -41,7 +41,7 @@ class PreparedGraph:
"""The `batch` body for enqueue_batch."""
graph_hash: str
model_keys: frozenset[str]
- """Keys of every model identifier in the graph (main model, components, LoRAs, control models)."""
+ """Keys of every model the graph names (main model, components, LoRAs, control models; `graph_model_keys`)."""
components: dict[str, str]
"""The exporter's resolved component choice, for provenance."""
@@ -128,9 +128,11 @@ def run_pnpm_exporter(request: dict[str, Any], work_dir: Path) -> dict[str, Any]
def model_identifiers(value: Any) -> Iterator[dict[str, Any]]:
- """Every model identifier in a graph: a ModelIdentifierField {"key", "hash", "name", "base", "type", ...}.
+ """Every model config anywhere in a value: a mapping with a string key, a base and a type, such as a graph's
+ ModelIdentifierField {"key", "hash", "name", "base", "type", ...} or an export request's model list.
- The webv2 builders put the model's whole config there, path and source included.
+ The webv2 builders put the model's whole config in a graph's identifiers, path and source included. Broad on
+ purpose: the bundle scrubs every config this finds. `graph_model_keys` is the server's narrower reading.
"""
if isinstance(value, dict):
if isinstance(value.get("key"), str) and "base" in value and "type" in value:
@@ -142,6 +144,29 @@ def model_identifiers(value: Any) -> Iterator[dict[str, Any]]:
yield from model_identifiers(item)
+def graph_model_keys(graph: dict[str, Any]) -> frozenset[str]:
+ """The keys of the models a graph names, as the server finds them (`graph_model_identifiers`): a mapping in a
+ node's field, or nested in one, with a string key, hash, name, base and type, without looking inside it. The
+ calibrate route takes the identity of exactly these models."""
+ keys: set[str] = set()
+
+ def visit(value: Any) -> None:
+ if isinstance(value, dict):
+ if all(isinstance(value.get(fact), str) for fact in ("key", "hash", "name", "base", "type")):
+ keys.add(value["key"])
+ else:
+ for item in value.values():
+ visit(item)
+ elif isinstance(value, list):
+ for item in value:
+ visit(item)
+
+ for node in graph["nodes"].values():
+ for value in node.values():
+ visit(value)
+ return frozenset(keys)
+
+
def is_public_url(value: object) -> bool:
"""An http(s) URL of a public host, without the places a download token would hide: credentials, `;params`,
query or fragment."""
@@ -201,7 +226,7 @@ def prepare_batch(batch: dict[str, Any], components: dict[str, str], input_ids:
return PreparedGraph(
batch=batch,
graph_hash=hashlib.sha256(canonical.encode("utf-8")).hexdigest(),
- model_keys=frozenset(identifier["key"] for identifier in model_identifiers(batch["graph"])),
+ model_keys=graph_model_keys(batch["graph"]),
components=components,
)
diff --git a/scripts/family_e2e/records.py b/scripts/family_e2e/records.py
index 63cc2622bf..59721b3f55 100644
--- a/scripts/family_e2e/records.py
+++ b/scripts/family_e2e/records.py
@@ -95,6 +95,13 @@ class Residency(_Model):
percent: float
+class CalibrationSubmission(_Model):
+ """How a calibration run's step reached the server: the run the calibrate route created for it."""
+
+ run_id: str
+ device_class_id: str
+
+
class Record(_Model):
record_id: str
"""`<case_key>.<arm>.<kind>.<rep>.<attempt>`."""
@@ -128,6 +135,8 @@ class Record(_Model):
valid_memory: bool
valid_psnr: bool
invalid_reasons: list[str]
+ calibration: CalibrationSubmission | None = None
+ """Set for a step of a calibration run that the server accepted."""
class Environment(_Model):
@@ -183,6 +192,22 @@ class ModelIdentity(_Model):
network, or a URL that may carry a token."""
+class CalibrationExport(_Model):
+ """A calibration store saved from one server lifetime of a calibration run."""
+
+ lifetime: int
+ """Counts the run's server lifetimes that saved a store, from 1. Each lifetime has its own scratch store."""
+ device_class_id: str
+ export: str
+ """calibration/<run_id>-<lifetime>-<device_class_id>.json: the store file byte for byte."""
+ status: str | None
+ """calibration/<run_id>-<lifetime>-status.json, the server's calibration status; None for a `store_file` copy."""
+ source: Literal["api", "store_file"]
+ """`api`: GET working_memory/export at the end of the lifetime. `store_file`: copied from the scratch root after the
+ server died or was stopped, which leaves no server to ask."""
+ saved_at: str
+
+
class RunInfo(_Model):
run_id: str
profile: str
@@ -201,6 +226,9 @@ class RunInfo(_Model):
"""Keyed by case_key."""
case_models: dict[str, list[ModelIdentity]] = {}
"""Keyed by case_key: the models its graph uses, main model first. Absent in runs written before the field."""
+ calibrate: bool = False
+ """Steps go through the working-memory calibrate route instead of enqueue_batch."""
+ calibration_exports: list[CalibrationExport] = []
class Reference(_Model):
diff --git a/scripts/family_e2e/references.py b/scripts/family_e2e/references.py
index 9b004efa2f..fe0202a704 100644
--- a/scripts/family_e2e/references.py
+++ b/scripts/family_e2e/references.py
@@ -50,6 +50,9 @@ def accept(data_dir: Path, run_dir: Path, case_keys: list[str] | None) -> list[R
arms = sorted(set(info.environments) | {r.arm for r in records})
if arms != [DEFAULT_ARM]:
raise AcceptError(f"run {info.run_id} has arms {', '.join(arms)}; references come only from normal runs")
+ if info.calibrate:
+ # The probe changes time and VRAM; a reference from such a run would be rated against normal runs.
+ raise AcceptError(f"run {info.run_id} is a calibration run; references come only from normal runs")
environment = info.environments.get(DEFAULT_ARM)
if environment is None:
raise AcceptError(f"run {info.run_id} has no recorded environment")
diff --git a/scripts/family_e2e/report.py b/scripts/family_e2e/report.py
index 2df7689159..1e59b20e5a 100644
--- a/scripts/family_e2e/report.py
+++ b/scripts/family_e2e/report.py
@@ -166,6 +166,9 @@ def render_report(
for (arm, case_key), case_records in _group(info, records).items()
]
notes = [scrubber.text(note) for note in context.history.notes]
+ if info.calibrate:
+ exports = ", ".join(export.export for export in info.calibration_exports) or "none saved"
+ notes.insert(0, f"Calibration run: time and VRAM are not rated. Store exports: {exports}.")
run_status = status or info.status
return RenderedReport(
html=_render_html(context, cases, notes, href, run_status),
@@ -239,7 +242,7 @@ class _History:
"""The latest earlier normal run with completed measured records of `case_key`."""
for run_dir in self._candidates:
run = self._load(run_dir)
- if run is None:
+ if run is None or run.info.calibrate:
continue
case_records = [r for r in run.records if r.case_key == case_key and r.arm == DEFAULT_ARM]
records = [r for r in _final_records(case_records) if r.kind == "measure" and r.status == "completed"]
diff --git a/scripts/family_e2e/runner.py b/scripts/family_e2e/runner.py
index da0060cbd8..f0fa55bc23 100644
--- a/scripts/family_e2e/runner.py
+++ b/scripts/family_e2e/runner.py
@@ -9,8 +9,18 @@ every case key with measures left, because the new server starts with a cold mod
`stop` and the runner agree through run.json under the run lock (`run_lock`): the runner names itself in the heartbeat
before anything else (`register_runner`), and `stop` marks the run stopped before it reads the heartbeat. So `stop`
-either finds the runner and kills it, or the runner finds the run stopped and leaves it untouched. The runner checks
-again before every server and every step (`ensure_running`), and never overwrites a status other than `running`.
+either finds the runner and kills it, or the runner finds the run stopped and leaves it untouched. The same holds for
+every server: the runner checks the status, spawns the server and records its launcher in the heartbeat under one hold
+of the run lock (`_Session.server_registration`), so a server spawned before the mark is in the heartbeat `stop` reads,
+and none is spawned after it. The runner checks again before every server and every step (`ensure_running`), and
+never overwrites a status other than `running`.
+
+A calibration run also checks that the server can calibrate, submits each step through the working-memory calibrate
+route, and saves the lifetime's calibration store before the scratch root goes (`calibration.py`). It records the
+store under the run lock and keeps whatever status run.json has (`save_calibration`), so a runner the stop has not
+killed yet still saves its store. A store that cannot be saved fails the run (or leaves a stop a stop) and keeps the
+root that holds it; the next `resume` saves a store an earlier runner left in a root before anything rebuilds it, once
+that runner's server is stopped (it may still write the store), and refuses to go on when that save fails.
"""
from __future__ import annotations
@@ -24,7 +34,7 @@ import logging
import os
import sys
import time
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Iterator, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -34,7 +44,7 @@ from typing import Any, BinaryIO, Protocol
import psutil
from PIL import Image
-from scripts.family_e2e import gpu_memory, nvml_memory
+from scripts.family_e2e import calibration, gpu_memory, nvml_memory
from scripts.family_e2e.client import (
ApiError,
EventRecorder,
@@ -62,6 +72,7 @@ from scripts.family_e2e.manifest import (
resolve_cases,
)
from scripts.family_e2e.records import (
+ CalibrationExport,
Environment,
ForeignProcess,
Memory,
@@ -98,7 +109,8 @@ logger = logging.getLogger("family_e2e")
HEARTBEAT_FILE = "heartbeat.json"
RUN_LOCK_FILE = "run.lock"
-# Holders keep the run lock for one read and one write of a small JSON file.
+# Holders keep the run lock for one read and one write of a small JSON file, a calibration run's store files, or the
+# spawn of a server process (not its startup; a spawn that could not be recorded also waits there for its kill).
RUN_LOCK_TIMEOUT_S = 30.0
RUN_LOCK_POLL_S = 0.01
# A started runner registers once its interpreter has imported the tool, which takes seconds on a busy machine.
@@ -227,8 +239,12 @@ def _step_id(step: PlannedStep | Record) -> tuple[str, str, str, int]:
def needs_retry(record: Record) -> bool:
- return record.status == "completed" and any(
- reason.startswith((FOREIGN_GPU_LOAD, FOREIGN_QUEUE_ITEM)) for reason in record.invalid_reasons
+ """Whether foreign load spoiled a completed run. A calibration step is not repeated: the server keeps every window
+ it measured, and the builder of shipped data takes the largest."""
+ return (
+ record.status == "completed"
+ and record.calibration is None
+ and any(reason.startswith((FOREIGN_GPU_LOAD, FOREIGN_QUEUE_ITEM)) for reason in record.invalid_reasons)
)
@@ -276,9 +292,10 @@ def gpu_lock(adapter: gpu_memory.Adapter) -> Iterator[None]:
@contextmanager
def run_lock(run_dir: Path) -> Iterator[None]:
- """Holds `<run_dir>/run.lock`, which orders status changes of run.json and the runner's registration between the
- runner, `stop` and `resume`. Waits while another process holds it; the operating system releases the lock of a
- killed holder."""
+ """Holds `<run_dir>/run.lock`, which orders status changes of run.json, the runner's registration and the spawn
+ of its servers between the runner, `stop` and `resume`. Waits while another process holds it; the operating system
+ releases the lock of a killed holder. The lock's handle is not inheritable, so a server spawned under it does not
+ keep it."""
with open(run_dir / RUN_LOCK_FILE, "a+b") as f:
deadline = time.monotonic() + RUN_LOCK_TIMEOUT_S
while True:
@@ -351,7 +368,7 @@ def _led_group(process: psutil.Process) -> list[int]:
return living_members(process.pid)
-def _still_running(identity: list[float] | None) -> list[int]:
+def still_running(identity: list[float] | None) -> list[int]:
"""The pids that still run of the process named by `identity`: itself unless it is a zombie, and the living
members of the group it leads."""
process = _identified(identity)
@@ -361,8 +378,8 @@ def _still_running(identity: list[float] | None) -> list[int]:
def kill_identified(identity: list[float] | None) -> bool:
- """Kills what still runs of the process named by [pid, create time] and its descendants, and waits until it has
- exited. Returns whether anything ran.
+ """Kills what still runs of the process named by [pid, create time] and its descendants, and waits up to
+ KILL_WAIT_S until it has exited. Returns whether anything ran, not whether it exited: `kill_recorded` checks that.
Descendants come from psutil, which drops processes older than their supposed parent; a raw parent-pid walk
(taskkill /T) can follow a reused pid into an unrelated tree. On POSIX the groups that processes of the tree lead
@@ -400,16 +417,31 @@ def kill_identified(identity: list[float] | None) -> bool:
return True
-def scratch_root(data_dir: Path, run_id: str, arm: str) -> Path:
- return data_dir / "scratch-roots" / f"{run_id}-{arm}"
+def kill_recorded(processes: Sequence[tuple[str, list[float] | None]]) -> tuple[list[tuple[str, int]], str]:
+ """Kills the processes given as (role, identity), in that order, then checks that each has exited.
+
+ Returns the roles and pids of the processes that ran, and what still runs, per pid with the cause; empty once all
+ exited. A process stuck in the GPU driver outlives SIGKILL until it leaves the kernel, and another user's refuses it.
+ """
+ ran: list[tuple[str, int]] = []
+ refused: dict[int, str] = {}
+ for role, identity in processes:
+ try:
+ if kill_identified(identity):
+ ran.append((role, int(identity[0])))
+ except psutil.Error as e:
+ refused[int(identity[0])] = f"the kill was refused: {type(e).__name__} {e}"
+ left = {int(identity[0]): running for _, identity in processes if (running := still_running(identity))}
+ waited = f"{KILL_WAIT_S:g}s after the kill"
+ survivors = ", ".join(
+ f"pid {pid} ({refused.get(pid, waited)}; still running: {', '.join(str(p) for p in running)})"
+ for pid, running in left.items()
+ )
+ return ran, survivors
-def remove_scratch_roots(data_dir: Path, info: RunInfo) -> list[str]:
- """Deletes the scratch roots of the run's arms; returns the paths that could not be deleted."""
- leftovers: list[str] = []
- for arm in sorted({DEFAULT_ARM, *info.environments}):
- leftovers.extend(remove_tree(scratch_root(data_dir, info.run_id, arm)))
- return leftovers
+def scratch_root(data_dir: Path, run_id: str, arm: str) -> Path:
+ return data_dir / "scratch-roots" / f"{run_id}-{arm}"
def read_heartbeat(run_dir: Path) -> dict[str, Any]:
@@ -448,6 +480,17 @@ def finish_run(run_dir: Path, status: str) -> bool:
return True
+def save_calibration(run_dir: Path, stores: calibration.Stores, status: bytes | None = None) -> list[CalibrationExport]:
+ """Saves a lifetime's calibration stores into the run: from the export routes with their status, or the store files
+ of a scratch root (no status). Under the run lock on run.json as it is then: the stores belong to the run whatever
+ its status, and a status `stop` set meanwhile stays."""
+ if not stores:
+ return []
+ with run_lock(run_dir):
+ info = load_run_info(run_dir)
+ return calibration.save(run_dir, info, stores, status)
+
+
def register_runner(run_dir: Path) -> None:
"""Names this process as the run's runner in heartbeat.json, before the runner does anything else.
@@ -504,25 +547,15 @@ def stop_surviving_server(run_dir: Path) -> None:
"""
heartbeat = read_heartbeat(run_dir)
survivors = {
- int(heartbeat[role][0]): heartbeat[role] for role in SERVER_ROLES if _still_running(heartbeat.get(role))
+ int(heartbeat[role][0]): running for role in SERVER_ROLES if (running := still_running(heartbeat.get(role)))
}
- refused: dict[int, str] = {}
- for pid, identity in survivors.items():
- running = ", ".join(str(p) for p in _still_running(identity))
- logger.warning("an earlier runner of this run left its server running (pid %d: %s); stopping it", pid, running)
- try:
- kill_identified(identity)
- except psutil.Error as e:
- refused[pid] = f"the kill was refused: {type(e).__name__} {e}"
- left = {pid: running for pid, identity in survivors.items() if (running := _still_running(identity))}
+ for pid, running in survivors.items():
+ pids = ", ".join(str(p) for p in running)
+ logger.warning("an earlier runner of this run left its server running (pid %d: %s); stopping it", pid, pids)
+ _, left = kill_recorded([(role, heartbeat.get(role)) for role in SERVER_ROLES])
if left:
- waited = f"{KILL_WAIT_S:g}s after the kill"
- details = ", ".join(
- f"pid {pid} ({refused.get(pid, waited)}; still running: {', '.join(str(p) for p in running)})"
- for pid, running in left.items()
- )
raise RunnerError(
- f"the server an earlier runner left running cannot be stopped: {details}. heartbeat.json and the scratch "
+ f"the server an earlier runner left running cannot be stopped: {left}. heartbeat.json and the scratch "
f"roots stay as they are; end it, e.g. with `python -m scripts.family_e2e stop {run_dir}`, then resume"
)
@@ -666,8 +699,9 @@ def build_memory(
)
-def new_run(manifest_path: Path, families: list[str], case_ids: list[str]) -> Path:
- """Creates the run directory and its run.json with the expanded plan."""
+def new_run(manifest_path: Path, families: list[str], case_ids: list[str], calibrate: bool = False) -> Path:
+ """Creates the run directory and its run.json with the expanded plan. A calibration run submits its steps through
+ the working-memory calibrate route (`calibration.py`)."""
manifest = load_manifest(manifest_path)
cases = resolve_cases(manifest, families, case_ids)
run_id = f"{datetime.now():%Y%m%d-%H%M%S}-{manifest.profile}"
@@ -689,6 +723,7 @@ def new_run(manifest_path: Path, families: list[str], case_ids: list[str]) -> Pa
plan=plan_steps(cases, manifest.defaults.warmup, manifest.defaults.repeats),
case_thresholds={case.case_key: case.thresholds for case in cases},
graph_hashes={},
+ calibrate=calibrate,
)
write_run_info(run_dir, info)
return run_dir
@@ -749,8 +784,14 @@ class _Session:
self.records = load_records(run_dir)
self.tracker = ResidencyTracker()
self.server: ServerProcess | None = None
+ # Recorded once at the spawn: a pid read again later could belong to a process that reused it.
+ self.launcher: list[float] | None = None
self.step_label = "starting"
self.last_beat = 0.0
+ # Per server lifetime: the device classes its calibration runs were created for, and whether their stores
+ # were saved through the export route.
+ self.device_class_ids: set[str] = set()
+ self.store_saved = False
all_cases = {case.case_key: case for case in resolve_cases(manifest)}
self.cases = {step.case_key: all_cases[step.case_key] for step in self.info.plan}
@@ -759,8 +800,9 @@ class _Session:
self.step_label = step_label
data = {
"runner": process_identity(os.getpid()),
- "server": process_identity(self.server.pid) if self.server else None,
- "server_launcher": process_identity(self.server.process.pid) if self.server else None,
+ # The create time captured with the serving process, as for the launcher.
+ "server": [self.server.pid, self.server.serving.create_time()] if self.server else None,
+ "server_launcher": self.launcher,
"step": self.step_label,
"updated_at": now_iso(),
}
@@ -773,6 +815,8 @@ class _Session:
def run(self) -> None:
self.heartbeat("preflight")
+ if self.info.calibrate:
+ self.recover_stores()
todo = remaining_steps(self.info.plan, self.records)
if not todo:
logger.info("every planned step has a final record")
@@ -784,43 +828,107 @@ class _Session:
return
todo = remaining_steps(self.info.plan, self.records)
+ def recover_stores(self) -> None:
+ """Saves the calibration store an earlier runner left in a scratch root, as `stop` does: one whose save failed,
+ or one a hard kill left. The next server lifetime would rebuild the root over it."""
+ for arm in sorted({DEFAULT_ARM, *self.info.environments}):
+ root = scratch_root(self.manifest.data_dir, self.info.run_id, arm)
+ if not root.exists():
+ continue
+ try:
+ exports = self.save_calibration(calibration.read_store_files(root))
+ except OSError as e:
+ raise RunnerError(
+ f"could not save the calibration store an earlier server left in {root} ({e}); not resuming, as "
+ "the next server's scratch root would replace it. Fix the cause or move the store away first"
+ ) from e
+ for export in exports:
+ logger.info("saved the calibration store %s left in %s", export.export, root)
+ leftovers = remove_tree(root)
+ if leftovers:
+ logger.warning("could not remove the scratch root %s: %s", root, ", ".join(leftovers))
+
def serve_once(self, todo: list[PlannedStep]) -> bool:
"""One server lifetime over `todo`. Returns True when the server crashed in a step."""
root = scratch_root(self.manifest.data_dir, self.info.run_id, self.arm)
log_path = self.run_dir / f"server-{self.arm}.log"
+ self.device_class_ids, self.store_saved = set(), False
+ stopping = False
try:
pin = device_env(self.gpu.adapter, self.manifest.server.env)
build_scratch_root(self.manifest.server.template_root, root, log_path, free_port(), bool(pin))
self.heartbeat("starting the server")
- self.server = launch_server(
- self.manifest.server,
- root,
- log_path,
- self.run_dir / f"server-{self.arm}.console.log",
- pin,
- )
try:
+ self.server = launch_server(
+ self.manifest.server,
+ root,
+ log_path,
+ self.run_dir / f"server-{self.arm}.console.log",
+ pin,
+ registration=self.server_registration(),
+ )
self.heartbeat("server ready")
self.serve(self.server, todo)
except ServerCrashed as e:
logger.error("%s; starting a new server", e)
return True
finally:
- self.server.stop()
- self.server = None
+ # A launch that failed has stopped its server itself.
+ if self.server is not None:
+ self.server.stop()
+ self.server, self.launcher = None, None
+ except (KeyboardInterrupt, RunStopped):
+ stopping = True
+ raise
finally:
# stop() returns once the server tree has exited, so its database files are closed by now.
- leftovers = remove_tree(root)
- if leftovers:
- logger.warning("could not remove the scratch root %s: %s", root, ", ".join(leftovers))
+ kept = False
+ if self.info.calibrate and not self.store_saved:
+ try:
+ self.save_calibration(calibration.read_store_files(root))
+ except OSError as e:
+ # The root holds the only copy of the lifetime's windows; `recover_stores` saves it on `resume`.
+ kept = True
+ message = (
+ f"could not save the calibration store ({e}); kept the scratch root {root} with it. Fix the "
+ "cause and `resume`, which saves it first"
+ )
+ if not stopping:
+ raise RunnerError(message) from e
+ # A stop stays a stop (an interrupt ends the run stopped, RunStopped keeps `stop`'s mark); the save
+ # error is logged.
+ logger.error(message)
+ if not kept:
+ leftovers = remove_tree(root)
+ if leftovers:
+ logger.warning("could not remove the scratch root %s: %s", root, ", ".join(leftovers))
return False
+ @contextmanager
+ def server_registration(self) -> Iterator[Callable[[int], None]]:
+ """Where `launch_server` spawns the server: under the run lock, and only while the run is still running.
+
+ `stop` marks the run stopped under the same lock before it reads the heartbeat, so a server is either in that
+ heartbeat (the launcher's identity is recorded before the lock is released) or never spawned. Without it, a
+ server spawned between `stop`'s capture of the runner's tree and the kill would be in neither on POSIX, where
+ it runs in a session of its own, and `stop` would remove the scratch root it still uses.
+ """
+ with run_lock(self.run_dir):
+ _raise_unless_running(self.run_dir)
+ yield self.server_spawned
+
+ def server_spawned(self, pid: int) -> None:
+ self.launcher = process_identity(pid)
+ self.heartbeat()
+
def serve(self, server: ServerProcess, todo: list[PlannedStep]) -> None:
client = InvokeClient(server.base_url)
recorder = EventRecorder(server.base_url)
recorder.connect()
try:
runtime_config = self.record_environment(server, client)
+ if self.info.calibrate:
+ calibration.check_available(client)
models = client.get("/api/v2/models/")["models"]
capabilities = client.get("/api/v2/models/capabilities")
configs = {model["key"]: model for model in models}
@@ -849,6 +957,9 @@ class _Session:
if not adapter_checked and record.status == "completed":
self.check_server_on_adapter(server)
adapter_checked = True
+ if self.device_class_ids:
+ self.save_calibration(*calibration.fetch_exports(client, self.device_class_ids))
+ self.store_saved = True
finally:
recorder.close()
@@ -893,6 +1004,12 @@ class _Session:
self.save_info()
return runtime_config
+ def save_calibration(self, stores: calibration.Stores, status: bytes | None = None) -> list[CalibrationExport]:
+ exports = save_calibration(self.run_dir, stores, status)
+ # save_info writes self.info whole.
+ self.info.calibration_exports.extend(exports)
+ return exports
+
def save_info(self) -> None:
"""Writes the session's run.json while the run is still running; `stop` owns it otherwise."""
with run_lock(self.run_dir):
@@ -1113,7 +1230,17 @@ class _Session:
log_offset = server.log_size()
mark = recorder.mark()
t_enqueue = time.perf_counter()
- item_id = client.enqueue(graph.batch)
+ if self.info.calibrate:
+ try:
+ item_id, fields["calibration"] = calibration.submit(
+ client, self.cases[step.case_key].spec.model, graph.batch, self.info.case_models[step.case_key]
+ )
+ except calibration.CaseRefused as e:
+ fields.update(error=str(e), invalid_reasons=[str(e)])
+ return Record(**fields)
+ self.device_class_ids.add(fields["calibration"].device_class_id)
+ else:
+ item_id = client.enqueue(graph.batch)
fields["queue_item_id"] = item_id
try:
item, t_done = wait_for_item(
@@ -1169,6 +1296,9 @@ class _Session:
reasons.append(f"{FOREIGN_GPU_LOAD}: {_describe(foreign)}")
if any(r.startswith((FOREIGN_GPU_LOAD, FOREIGN_QUEUE_ITEM)) for r in reasons):
valid_timing = valid_memory = False
+ if self.info.calibrate:
+ reasons.append(calibration.PROBE_REASON)
+ valid_timing = valid_memory = False
fields.update(
valid_timing=valid_timing, valid_memory=valid_memory, valid_psnr=valid_psnr, invalid_reasons=reasons
)
diff --git a/scripts/family_e2e/server.py b/scripts/family_e2e/server.py
index c1327e32cc..e0600eedd2 100644
--- a/scripts/family_e2e/server.py
+++ b/scripts/family_e2e/server.py
@@ -17,6 +17,8 @@ import socket
import subprocess
import sys
import time
+from collections.abc import Callable
+from contextlib import AbstractContextManager
from dataclasses import dataclass
from pathlib import Path
from typing import IO, Any
@@ -538,27 +540,44 @@ def launch_server(
log_path: Path,
console_path: Path,
device_env: dict[str, str] | None = None,
+ *,
+ registration: AbstractContextManager[Callable[[int], None]],
) -> ServerProcess:
- """Starts the server on a prepared scratch root and waits until its API answers."""
+ """Starts the server on a prepared scratch root and waits until its API answers.
+
+ The spawn happens inside `registration`, which yields what records the launcher's pid; it is called right after
+ the spawn, still inside, and the wait for the server follows outside it. On POSIX the server outlives a runner
+ killed while it starts, and only what the runner records then names it for `stop` and `resume`: the runner's
+ registration holds the run lock and refuses to enter once the run is stopped (`_Session.server_registration`).
+ The one wait inside it: when recording the pid fails, the server is killed and waited for before the registration
+ ends, since a `stop` after it would find that server in no heartbeat.
+ """
env = server_env(spec, device_env)
invokeai_file = verify_interpreter(spec, env)
cmd = [str(spec.python), str(spec.code_dir / "scripts" / "invokeai-web.py"), "--root", str(scratch_root)]
log_offset = log_path.stat().st_size if log_path.exists() else 0
console = console_path.open("ab")
+ process: subprocess.Popen[bytes] | None = None
+ job: KillOnCloseJob | None = None
try:
- process, job = spawn_in_job(
- cmd, cwd=spec.code_dir, env=env, stdin=subprocess.DEVNULL, stdout=console, stderr=subprocess.STDOUT
- )
- except BaseException:
- console.close()
- raise
- try:
+ with registration as on_spawn:
+ process, job = spawn_in_job(
+ cmd, cwd=spec.code_dir, env=env, stdin=subprocess.DEVNULL, stdout=console, stderr=subprocess.STDOUT
+ )
+ try:
+ on_spawn(process.pid)
+ except BaseException:
+ terminate(process, job)
+ process = None
+ raise
port = _wait_for_port(process, log_path, log_offset, console_path)
base_url = f"http://127.0.0.1:{port}"
_wait_for_api(process, base_url, console_path)
serving = _serving_process(process.pid, port)
except BaseException:
- terminate(process, job)
+ # A recorded server is killed outside the registration: `stop` finds it, and the run lock is not kept waiting.
+ if process is not None:
+ terminate(process, job)
console.close()
raise
return ServerProcess(process, console, log_path, base_url, serving, cmd, invokeai_file, job)
diff --git a/scripts/working_memory/__init__.py b/scripts/working_memory/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/scripts/working_memory/build_shipped.py b/scripts/working_memory/build_shipped.py
new file mode 100644
index 0000000000..9d9cf2d22b
--- /dev/null
+++ b/scripts/working_memory/build_shipped.py
@@ -0,0 +1,619 @@
+"""Shipped working-memory points and fitted values from calibration store exports.
+
+ python -m scripts.working_memory.build_shipped EXPORT [EXPORT ...] [--data-dir DIR] [--write]
+
+An export is a device class's calibration store as `GET /api/v2/models/working_memory/export` returns it; a family E2E
+calibration run saves one per server lifetime under `runs/<run_id>/calibration/`. Every valid, fit-eligible window
+becomes a `probe_demand` point: per card (device class), estimator, version, platform and features, the largest
+`demand_bytes` of the windows, so repetitions and several exports of one card merge. The platform is what
+`platform_for` gives on the machine the export came from (`platform.platform_for_environment`). A point joins the
+data file that declares its estimator's coefficients, keeping the larger of itself and a shipped `probe_demand` point
+of the same card, platform and features; the carried values are then refitted with `fit.py`. A stand-in stays one
+until fresh-process points at two sizes far enough apart measure its line: `probe_demand` points can raise it, never
+lower it.
+
+Without `--write` the changes are printed only. An export of another estimator version than the registered spec, or a
+window whose features the spec's terms cannot evaluate, is refused. So is a result any point's bounds
+(`working_memory/bounds.py`, the data test's rule) reject, and a line raised on a point flagged as fragmentation unless
+`--accept-fragmentation` is given.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from collections import Counter
+from collections.abc import Mapping, Sequence
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any
+
+from pydantic import ValidationError
+
+import invokeai.backend.working_memory as working_memory_package
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
+ CalibrationEnvironment,
+ CalibrationPoint,
+ CalibrationStoreFile,
+)
+from invokeai.backend.working_memory.bounds import bound_violation, evaluate_point, point_id
+from invokeai.backend.working_memory.coefficients import (
+ CoefficientEntry,
+ MeasuredPoint,
+ WorkingMemoryData,
+ load_data,
+)
+from invokeai.backend.working_memory.fit import (
+ capping_spans,
+ entry_key,
+ fit_points,
+ fitted_values,
+ line_of,
+ shipped_pair,
+)
+from invokeai.backend.working_memory.fragmentation import Measurement, fragmented
+from invokeai.backend.working_memory.platform import Platform, is_measured, platform_for_environment
+from invokeai.backend.working_memory.spec import EstimatorSpec, import_estimator_modules
+
+METHOD = "probe_demand"
+DATA_DIR = Path(working_memory_package.__file__).parent / "data"
+EXPORT_NAME = re.compile(r"-(?:(?P<lifetime>\d+)-)?[0-9a-f]{16}\.json$")
+"""A store export as a family E2E run names it, `<run_id>-<lifetime>-<device class id>.json`."""
+REFIT_NOTE = "Refitted with probe_demand points by scripts/working_memory/build_shipped.py."
+RAISE_NOTE = (
+ "Stand-ins raised to cover probe_demand points by scripts/working_memory/build_shipped.py; still stand-ins until "
+ "fresh-process points at two sizes at least twice apart in pixels measure their line."
+)
+_RUNTIME_FACTS = ("cuda", "hip", "cudnn", "miopen", "xpu")
+
+
+class BuildError(ValueError):
+ pass
+
+
+@dataclass(frozen=True)
+class _Window:
+ """A window that becomes, or competes to become, a point."""
+
+ point: CalibrationPoint
+ env: CalibrationEnvironment
+ device: str
+ export: Path
+ attempt: str
+ """The calibration attempt the window ran in (its owner's `attempt_id`), or its run without one."""
+
+
+@dataclass(frozen=True)
+class Spread:
+ """The windows a point is the largest of, in the order they ran: export order, then queue item."""
+
+ demand: tuple[int, ...]
+ reserved: tuple[int | None, ...]
+ """Each window's reserved delta."""
+ allocated: tuple[int | None, ...]
+ fragmented: bool = False
+ """Whether the attempt its largest window ran in measured fragmentation at its features
+ (`fragmentation.fragmented`): the allocator's cache grew around the same tensors, as a long-running server
+ fragments it, rather than the operation needing more."""
+
+ @property
+ def first_to_max(self) -> float:
+ return max(self.demand) / self.demand[0]
+
+
+@dataclass
+class Build:
+ points: list[MeasuredPoint]
+ skipped: Counter[str] = field(default_factory=Counter)
+ """Windows left out, by reason."""
+ spreads: dict[tuple[str, int, str, str, str, str], Spread] = field(default_factory=dict)
+ """By `point_identity`."""
+
+
+def _canonical(features: Mapping[str, Any]) -> str:
+ return json.dumps(features, sort_keys=True, separators=(",", ":"))
+
+
+def point_identity(point: MeasuredPoint) -> tuple[str, int, str, str, str, str]:
+ """What a newer point of the same measurement replaces."""
+ return (
+ point.estimator,
+ point.version,
+ _canonical(point.platform),
+ point.device,
+ point.method,
+ _canonical(point.features),
+ )
+
+
+def point_platform(platform: Platform, entries: Sequence[CoefficientEntry]) -> dict[str, str]:
+ """The platform keys a point names: all of `platform`, the OS only where an entry that applies there names it."""
+ full = {key: str(value) for key, value in asdict(platform).items()}
+ os_specific = any(
+ "os" in entry.platform and all(full.get(key) == value for key, value in entry.platform.items())
+ for entry in entries
+ )
+ return full if os_specific else {key: value for key, value in full.items() if key != "os"}
+
+
+def _load_export(path: Path) -> CalibrationStoreFile:
+ try:
+ return CalibrationStoreFile.model_validate_json(path.read_bytes())
+ except (OSError, ValidationError) as e:
+ raise BuildError(f"{path}: not a calibration store this version reads: {e}") from e
+
+
+def _check_window(path: Path, window: CalibrationPoint, spec: EstimatorSpec) -> None:
+ where = (
+ f"{path}: {window.estimator} window of node {window.node_type} {window.node_id} (item {window.queue_item_id})"
+ )
+ try:
+ spec.terms(window.features, dict.fromkeys(spec.coefficients, 1.0))
+ except Exception as e:
+ raise BuildError(f"{where}: the estimator cannot evaluate its features {window.features}: {e!r}") from e
+
+
+def _provenance(best: _Window, count: int) -> str:
+ hard, soft = best.env.hard, best.env.soft
+ runtime = ", ".join(f"{name} {hard[name]}" for name in _RUNTIME_FACTS if hard.get(name))
+ window = best.point
+ return (
+ f"probe_demand, the largest of {count} valid fit-eligible window{'s' if count != 1 else ''}; the largest from "
+ f"calibration run {window.run_id}, item {window.queue_item_id}, node {window.node_type} {window.node_id}, "
+ f"model {window.model_key}. {best.device}, torch {soft.get('torch_build') or hard.get('torch')}"
+ f"{', ' + runtime if runtime else ''}. Export {best.export.name}."
+ )
+
+
+def build_points(
+ exports: Sequence[Path], specs: Mapping[str, EstimatorSpec], entries: Sequence[CoefficientEntry]
+) -> Build:
+ """The `probe_demand` points of the exports' valid, fit-eligible windows, and what was left out."""
+ groups: dict[tuple[str, str, int, str, str], list[_Window]] = {}
+ platforms: dict[tuple[str, str, int, str, str], dict[str, str]] = {}
+ skipped: Counter[str] = Counter()
+ seen: set[str] = set()
+ for path in exports:
+ store = _load_export(path)
+ envs = {env.id: env for env in store.envs}
+ # Two owners' attempts never share windows, whatever their ids.
+ attempts = {
+ run.run_id: f"{run.user_id}\x00{run.attempt_id}" if run.attempt_id is not None else run.run_id
+ for run in store.runs
+ }
+ # A point's card is its device class. One name can stand for several (another memory size, say); the id
+ # tells them apart, in the groups and in the points written.
+ device = f"{store.device_class.name} ({store.device_class.id})"
+ for window in store.points:
+ # The same store saved twice (an export and a copy of its file, one file named twice) counts once.
+ identity = window.model_dump_json()
+ if identity in seen:
+ skipped["duplicate"] += 1
+ continue
+ seen.add(identity)
+ spec = specs.get(window.estimator)
+ if spec is None:
+ raise BuildError(f"{path}: no registered estimator is called {window.estimator!r}")
+ if window.version != spec.version:
+ raise BuildError(
+ f"{path}: {window.estimator} windows of version {window.version}, the registered estimator is "
+ f"version {spec.version}; measure again with this version"
+ )
+ if not window.valid:
+ skipped["invalid"] += 1
+ continue
+ if not window.fit_eligible:
+ skipped["not fit-eligible"] += 1
+ continue
+ if window.demand_bytes is None or window.demand_bytes <= 0:
+ # Co-locks that moved more weights off the device than the operation took; nothing to bound.
+ skipped["no positive demand"] += 1
+ continue
+ _check_window(path, window, spec)
+ env = envs.get(window.env_id)
+ if env is None:
+ raise BuildError(f"{path}: a window names environment {window.env_id}, which the store does not hold")
+ try:
+ platform = platform_for_environment(store.device_class.backend, env.hard)
+ except ValueError:
+ # Recorded by a server that does not record every fact the platform is read from.
+ skipped["no platform facts"] += 1
+ continue
+ if not is_measured(platform):
+ raise BuildError(
+ f"{path}: measured on {platform}, which `platform.MEASURED` does not list; ship coefficient "
+ "entries for it first"
+ )
+ # A spec keyed by no platform trait reads one entry alike everywhere, and its points name no platform.
+ keys = point_platform(platform, entries) if spec.platform_keys else {}
+ group = (device, window.estimator, window.version, _canonical(keys), _canonical(window.features))
+ platforms[group] = keys
+ attempt = attempts.get(window.run_id, window.run_id)
+ groups.setdefault(group, []).append(_Window(window, env, device, path, attempt))
+
+ order = {path: index for index, path in enumerate(exports)}
+ ordered = {
+ group: sorted(windows, key=lambda w: (order[w.export], w.point.queue_item_id))
+ for group, windows in sorted(groups.items())
+ }
+ flagged = _fragmented_attempts(ordered)
+ points = []
+ spreads = {}
+ for group, windows in ordered.items():
+ best = max(windows, key=lambda w: w.point.demand_bytes or 0)
+ assert best.point.demand_bytes is not None, "windows without a positive demand are left out"
+ points.append(
+ MeasuredPoint(
+ estimator=best.point.estimator,
+ version=best.point.version,
+ platform=platforms[group],
+ features=dict(best.point.features),
+ measured_bytes=best.point.demand_bytes,
+ method=METHOD,
+ device=best.device,
+ provenance=_provenance(best, len(windows)),
+ )
+ )
+ spreads[point_identity(points[-1])] = Spread(
+ demand=tuple(w.point.demand_bytes or 0 for w in windows),
+ reserved=tuple(w.point.reserved.delta if w.point.reserved else None for w in windows),
+ allocated=tuple(w.point.allocated.delta if w.point.allocated else None for w in windows),
+ fragmented=(group, best.export, best.attempt) in flagged,
+ )
+ return Build(points=points, skipped=skipped, spreads=spreads)
+
+
+_Group = tuple[str, str, int, str, str]
+"""A point's windows: card, estimator, version, platform keys and features."""
+
+
+def _fragmented_attempts(groups: Mapping[_Group, Sequence[_Window]]) -> set[tuple[_Group, Path, str]]:
+ """The attempts whose windows of a point measured fragmentation (`fragmentation.fragmented`), as (group, export,
+ attempt): each attempt in one server lifetime is a measurement of its own, compared with the smaller sizes of
+ its card's line."""
+ keys: list[tuple[_Group, Path, str]] = []
+ measurements: list[Measurement] = []
+ for group, windows in groups.items():
+ card, estimator, version, platform, _ = group
+ found = line_of(windows[0].point.features)
+ # Features that name no line compare with nothing: the growth rule alone judges them.
+ line: object = group if found is None else (card, estimator, version, platform, found[0])
+ pixels = 0 if found is None else found[1]
+ by_attempt: dict[tuple[Path, str], list[_Window]] = {}
+ for window in windows:
+ by_attempt.setdefault((window.export, window.attempt), []).append(window)
+ for (export, attempt), members in by_attempt.items():
+ keys.append((group, export, attempt))
+ measurements.append(
+ Measurement(
+ line=line,
+ pixels=pixels,
+ demand=[w.point.demand_bytes or 0 for w in members],
+ reserved=[w.point.reserved.delta if w.point.reserved else None for w in members],
+ allocated=[w.point.allocated.delta if w.point.allocated else None for w in members],
+ )
+ )
+ return {key for key, flag in zip(keys, fragmented(measurements), strict=True) if flag}
+
+
+def merge_points(
+ data: Mapping[str, WorkingMemoryData], points: Sequence[MeasuredPoint]
+) -> dict[str, WorkingMemoryData]:
+ """`data` with `points` in the file that declares their estimator's coefficients. A point of the same measurement
+ already there keeps its place and the larger `measured_bytes` of the two; any other point is appended."""
+ owners: dict[str, str] = {}
+ for name, file in data.items():
+ for entry in file.coefficients:
+ if owners.setdefault(entry.estimator, name) != name:
+ raise BuildError(f"{entry.estimator} has coefficients in both {owners[entry.estimator]} and {name}")
+ new: dict[str, dict[tuple[str, int, str, str, str, str], MeasuredPoint]] = {name: {} for name in data}
+ for point in points:
+ owner = owners.get(point.estimator)
+ if owner is None:
+ raise BuildError(f"no data file declares coefficients for {point.estimator}; add its entries first")
+ new[owner][point_identity(point)] = point
+ merged = {}
+ for name, file in data.items():
+ replacing = new[name]
+ kept = []
+ for point in file.points:
+ newer = replacing.pop(point_identity(point), None)
+ kept.append(point if newer is None or newer.measured_bytes <= point.measured_bytes else newer)
+ merged[name] = file.model_copy(update={"points": kept + list(replacing.values())})
+ return merged
+
+
+def refit(data: Mapping[str, WorkingMemoryData]) -> dict[str, WorkingMemoryData]:
+ """`data` with every carried value that is not a stand-in set to its fit. A stand-in line whose in-fit
+ fresh-process points now span the sizes a fit needs (`fit.capping_spans`) is fitted from then on, as the data test
+ requires. Any other stays a stand-in, raised where the fit of its points lies above it: `probe_demand` points bound
+ it from below only, so they never lower it."""
+ groups = fit_points(data.values())
+
+ def raised_stand_ins(entry: CoefficientEntry) -> dict[str, float]:
+ values = entry.values or {}
+ raised = {}
+ for suffix in sorted({name[2:] for name in entry.stand_ins}):
+ line = groups.get((entry_key(entry), suffix))
+ if not line:
+ continue
+ try:
+ k, b = shipped_pair([(point.pixels, point.bytes) for point in line])
+ except ValueError:
+ # Too few sizes for a line; `bound_violations` refuses a stand-in below one of them.
+ continue
+ raised[f"k_{suffix}"] = max(values[f"k_{suffix}"], k)
+ raised[f"b_{suffix}"] = max(values[f"b_{suffix}"], b)
+ return raised
+
+ def measured_lines_fitted(entry: CoefficientEntry) -> CoefficientEntry:
+ stand_ins = [
+ name for name in entry.stand_ins if not capping_spans(groups.get((entry_key(entry), name[2:]), []))
+ ]
+ return entry.model_copy(update={"stand_ins": stand_ins})
+
+ staged = {
+ name: file.model_copy(update={"coefficients": [measured_lines_fitted(entry) for entry in file.coefficients]})
+ for name, file in data.items()
+ }
+ try:
+ fitted = fitted_values(staged.values())
+ except ValueError as e:
+ raise BuildError(f"the points cannot fit a line: {e}") from e
+
+ def refitted(entry: CoefficientEntry) -> CoefficientEntry:
+ if entry.values is None:
+ return entry
+ line = fitted.get(entry_key(entry), {})
+ raised = raised_stand_ins(entry)
+ values = {
+ name: float(raised.get(name, value)) if name in entry.stand_ins else float(line.get(name, value))
+ for name, value in entry.values.items()
+ }
+ if values == entry.values:
+ return entry
+ provenance = entry.provenance
+ for note, changed in (
+ (REFIT_NOTE, any(values[n] != entry.values[n] for n in values if n not in entry.stand_ins)),
+ (RAISE_NOTE, any(values[n] != entry.values[n] for n in raised)),
+ ):
+ if changed and note not in provenance:
+ provenance = f"{provenance} {note}"
+ return entry.model_copy(update={"values": values, "provenance": provenance})
+
+ return {
+ name: file.model_copy(update={"coefficients": [refitted(entry) for entry in file.coefficients]})
+ for name, file in staged.items()
+ }
+
+
+def bound_violations(data: Mapping[str, WorkingMemoryData], specs: Mapping[str, EstimatorSpec]) -> list[str]:
+ """Every point of `data` whose estimate under `data` breaks a bound it sets (`bounds.bound_violation`)."""
+ violations = []
+ for point in (point for file in data.values() for point in file.points):
+ violation = bound_violation(point, evaluate_point(point, specs[point.estimator], data.values()))
+ if violation is not None:
+ violations.append(f"{point_id(point)}: {violation}")
+ return violations
+
+
+@dataclass(frozen=True)
+class LineChange:
+ """A carried convolution line the refit moves, with the new points it is fitted on."""
+
+ file: str
+ entry: CoefficientEntry
+ line: str
+ old: tuple[float, float]
+ new: tuple[float, float]
+ points: list[MeasuredPoint]
+ raised: bool
+ """Whether the new line lies above the old one at any size its points measure."""
+
+ def fragmented(self, spreads: Mapping[tuple[str, int, str, str, str, str], Spread]) -> list[MeasuredPoint]:
+ """The new points on a raised line whose windows are flagged as fragmentation (`Spread.fragmented`)."""
+ if not self.raised:
+ return []
+ return [point for point in self.points if spreads[point_identity(point)].fragmented]
+
+
+def review_lines(
+ before: Mapping[str, WorkingMemoryData], after: Mapping[str, WorkingMemoryData], new_points: Sequence[MeasuredPoint]
+) -> list[LineChange]:
+ """Every line the refit moves."""
+ entries = [entry for file in after.values() for entry in file.coefficients]
+ lines: dict[tuple[Any, str], list[MeasuredPoint]] = {}
+ for point in new_points:
+ single = WorkingMemoryData(schema_version=1, coefficients=entries, points=[point])
+ for line in fit_points([single]):
+ lines.setdefault(line, []).append(point)
+ fitted_on = fit_points(after.values())
+ changes = []
+ for name, file in after.items():
+ old_entries = {entry_key(entry): entry for entry in before[name].coefficients}
+ for entry in file.coefficients:
+ old_values, values = old_entries[entry_key(entry)].values or {}, entry.values or {}
+ # Only a line points are fitted on can move. A hand-set value (`fit.hand_set_values`) is on none.
+ for suffix in sorted(line for key, line in fitted_on if key == entry_key(entry)):
+ old = (old_values[f"k_{suffix}"], old_values[f"b_{suffix}"])
+ new = (values[f"k_{suffix}"], values[f"b_{suffix}"])
+ if old == new:
+ continue
+ sizes = {p.pixels for p in fitted_on.get((entry_key(entry), suffix), [])}
+ raised = any(new[0] * x + new[1] > old[0] * x + old[1] for x in sizes)
+ on_line = lines.get((entry_key(entry), suffix), [])
+ changes.append(LineChange(name, entry, suffix, old, new, on_line, raised))
+ return changes
+
+
+def _plain(value: Any) -> Any:
+ """Whole floats as integers, as the data files write them."""
+ if isinstance(value, float) and value.is_integer():
+ return int(value)
+ if isinstance(value, dict):
+ return {key: _plain(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [_plain(item) for item in value]
+ return value
+
+
+def write_data(path: Path, data: WorkingMemoryData) -> None:
+ """Writes a data file as the shipped ones are written, keeping the file's line endings."""
+ newline = "\r\n" if path.is_file() and b"\r\n" in path.read_bytes() else "\n"
+ text = json.dumps(_plain(data.model_dump(mode="json", exclude_defaults=True)), indent=2, ensure_ascii=False)
+ path.write_bytes((text + "\n").replace("\n", newline).encode("utf-8"))
+
+
+_MIB = 2**20
+
+
+def _mib(value: float | None) -> str:
+ return "-" if value is None else f"{value / _MIB:.0f}"
+
+
+def _spread_text(spread: Spread | None) -> str:
+ if spread is None or len(spread.demand) < 2:
+ return ""
+ demand = ", ".join(map(_mib, spread.demand))
+ return f" [{len(spread.demand)} windows, MiB {demand}; max/first {spread.first_to_max:.2f}]"
+
+
+def describe_changes(
+ before: Mapping[str, WorkingMemoryData],
+ after: Mapping[str, WorkingMemoryData],
+ new_points: Sequence[MeasuredPoint],
+ spreads: Mapping[tuple[str, int, str, str, str, str], Spread],
+) -> list[str]:
+ """One line per point added or remeasured, with the spread of its windows, carried value refitted, and stand-in
+ now fitted."""
+ new = {point_identity(point) for point in new_points}
+ lines = []
+ for name, file in after.items():
+ old_points = {point_identity(point): point for point in before[name].points if point_identity(point) in new}
+ for point in (point for point in file.points if point_identity(point) in new):
+ old = old_points.get(point_identity(point))
+ where = f"{name}: {point.estimator} {point.platform} {point.device} {_canonical(point.features)}"
+ spread = _spread_text(spreads.get(point_identity(point)))
+ if old is None:
+ lines.append(f"{where} + {point.measured_bytes}{spread}")
+ elif old.measured_bytes != point.measured_bytes:
+ lines.append(f"{where} {old.measured_bytes} -> {point.measured_bytes}{spread}")
+ old_entries = {entry_key(entry): entry for entry in before[name].coefficients}
+ for entry in file.coefficients:
+ old_entry = old_entries[entry_key(entry)]
+ for value_name, value in (entry.values or {}).items():
+ previous = (old_entry.values or {}).get(value_name)
+ if previous != value:
+ lines.append(
+ f"{name}: {entry.estimator} {entry.platform} {value_name} {_plain(previous)} -> {_plain(value)}"
+ )
+ for value_name in sorted(set(old_entry.stand_ins) - set(entry.stand_ins)):
+ lines.append(f"{name}: {entry.estimator} {entry.platform} {value_name} is fitted now, no stand-in")
+ return lines
+
+
+def _export_order(path: Path) -> tuple[str, int]:
+ """Exports of one run in the order of its server lifetimes, `-10-` after `-9-`."""
+ match = EXPORT_NAME.search(path.name)
+ assert match is not None, "only exports are ordered"
+ return path.name[: match.start()], int(match["lifetime"] or 0)
+
+
+def export_paths(arguments: Sequence[Path]) -> list[Path]:
+ """The export files named, a directory standing for the exports a family E2E run saved in it (`<name>-<device
+ class id>.json`, not the status files next to them)."""
+ paths: list[Path] = []
+ for argument in arguments:
+ if argument.is_dir():
+ found = sorted(
+ (path for path in argument.glob("*.json") if EXPORT_NAME.search(path.name)), key=_export_order
+ )
+ if not found:
+ raise BuildError(f"{argument} holds no calibration store exports")
+ paths += found
+ else:
+ paths.append(argument)
+ return paths
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ prog="python -m scripts.working_memory.build_shipped", description=__doc__.split("\n")[0]
+ )
+ parser.add_argument(
+ "exports", nargs="+", type=Path, help="calibration store exports, or directories of them (a run's calibration/)"
+ )
+ parser.add_argument(
+ "--data-dir", type=Path, default=DATA_DIR, help=f"the working-memory data files (default {DATA_DIR})"
+ )
+ parser.add_argument("--write", action="store_true", help="write the merged points and refitted values")
+ parser.add_argument(
+ "--accept-fragmentation",
+ action="store_true",
+ help="let --write raise a line on points flagged as fragmentation (working_memory/fragmentation.py)",
+ )
+ args = parser.parse_args(argv)
+
+ try:
+ specs = import_estimator_modules()
+ try:
+ before = dict(load_data(args.data_dir))
+ except (FileNotFoundError, ValueError) as e:
+ raise BuildError(str(e)) from e
+ exports = export_paths(args.exports)
+ entries = [entry for file in before.values() for entry in file.coefficients]
+ build = build_points(exports, specs, entries)
+ after = refit(merge_points(before, build.points))
+ violations = bound_violations(after, specs)
+ reviews = review_lines(before, after, build.points)
+ except BuildError as e:
+ print(f"error: {e}", file=sys.stderr)
+ return 2
+
+ skipped = ", ".join(f"{count} {reason}" for reason, count in sorted(build.skipped.items())) or "none"
+ print(f"{len(build.points)} probe_demand points from {len(exports)} exports; windows left out: {skipped}")
+ changes = describe_changes(before, after, build.points, build.spreads)
+ print("\n".join(changes) if changes else "no changes")
+ for point in build.points:
+ spread = build.spreads[point_identity(point)]
+ if spread.fragmented:
+ print(
+ f"warning: fragmentation? {point.estimator} {point.platform} {point.device} {_canonical(point.features)}"
+ f": reserved MiB {', '.join(map(_mib, spread.reserved))} while allocated MiB "
+ f"{', '.join(map(_mib, spread.allocated))}; max/first {spread.first_to_max:.2f}"
+ )
+ for change in reviews:
+ (old_k, old_b), (new_k, new_b) = change.old, change.new
+ flagged = change.fragmented(build.spreads)
+ print(
+ f"line {change.file}: {change.entry.estimator} {change.entry.platform} {change.line}: "
+ f"k {_plain(old_k)} -> {_plain(new_k)}, b {_mib(old_b)} -> {_mib(new_b)} MiB; "
+ f"{'raised' if change.raised else 'lowered'}, {len(change.points)} new points on it"
+ + (f", {len(flagged)} flagged as fragmentation" if flagged else "")
+ )
+ if violations:
+ print(
+ "error: not written: the bounds of these points reject the result (working_memory/bounds.py):\n"
+ + "\n".join(violations),
+ file=sys.stderr,
+ )
+ return 1
+ if args.write and not args.accept_fragmentation and any(change.fragmented(build.spreads) for change in reviews):
+ print(
+ "error: not written: a line is raised on points flagged as fragmentation; pass --accept-fragmentation "
+ "to ship them",
+ file=sys.stderr,
+ )
+ return 1
+ if args.write and changes:
+ for name, file in after.items():
+ if file != before[name]:
+ write_data(args.data_dir / name, file)
+ print(f"wrote {args.data_dir / name}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/app/invocations/test_vae_working_memory_backend.py b/tests/app/invocations/test_vae_working_memory_backend.py
index d3c96e1403..5f391ba4be 100644
--- a/tests/app/invocations/test_vae_working_memory_backend.py
+++ b/tests/app/invocations/test_vae_working_memory_backend.py
@@ -26,6 +26,7 @@ from invokeai.backend.util.vae_working_memory import (
VAE_FLUX_SPEC,
VAE_SD3_SPEC,
VAE_SD_SPEC,
+ estimate_untiled_vae_decode,
estimate_vae_working_memory_cogview4,
estimate_vae_working_memory_flux,
estimate_vae_working_memory_flux2,
@@ -429,3 +430,61 @@ def test_expandable_segments_off_windows_are_priced_as_the_native_allocator_ther
)
assert linux.reservation_bytes == native.reservation_bytes >= 3600 * 2 * 1024 * 1024
assert "priced as conv_backend=miopen,allocator=native" in linux.source
+
+
+ "spec, estimate, vae_dtype, dtype",
+ [
+ pytest.param(
+ VAE_SD_SPEC,
+ lambda device, vae: estimate_vae_working_memory_sd15_sdxl("decode", LATENTS_1024, vae, None, False, device),
+ torch.float16,
+ "fp16",
+ id="sd",
+ ),
+ pytest.param(
+ VAE_SD3_SPEC,
+ lambda device, vae: estimate_vae_working_memory_sd3("decode", LATENTS_1024, vae, device),
+ torch.bfloat16,
+ "bf16",
+ id="sd3",
+ ),
+ pytest.param(
+ VAE_COGVIEW4_SPEC,
+ lambda device, vae: estimate_vae_working_memory_cogview4("decode", LATENTS_1024, vae, device),
+ torch.bfloat16,
+ "bf16",
+ id="cogview4",
+ ),
+ pytest.param(
+ VAE_FLUX_SPEC,
+ lambda device, vae: estimate_vae_working_memory_flux("decode", LATENTS_1024, vae, device=device),
+ torch.bfloat16,
+ "bf16",
+ id="flux",
+ ),
+ pytest.param(
+ VAE_FLUX2_SPEC,
+ lambda device, vae: estimate_vae_working_memory_flux2(
+ "decode", torch.zeros(1, 32, 128, 128), vae, device=device
+ ),
+ torch.bfloat16,
+ "bf16",
+ id="flux2",
+ ),
+ ],
+)
+def test_a_planned_untiled_decode_is_priced_as_its_decode_node_prices_it(spec, estimate, vae_dtype, dtype) -> None:
+ """The calibration plan sizes its cases without a VAE; its features must stay the decode nodes' own, the score
+ matrix included (held to a stand-in that depends on its shape)."""
+ device = torch.device("cuda", 0)
+ with patch(
+ "invokeai.backend.util.vae_working_memory.sdpa_score_matrix_bytes",
+ side_effect=lambda **kwargs: kwargs["num_heads"] * kwargs["seq_len"] ** 2 * 3,
+ ):
+ cls = AutoencoderKLFlux2 if spec is VAE_FLUX2_SPEC else AutoencoderKL
+ node = estimate(device, _vae(cls, vae_dtype))
+ planned = estimate_untiled_vae_decode(spec.id, 1024, 1024, dtype, device)
+
+ assert dict(planned.features) == dict(node.features)
+ assert planned.reservation_bytes == node.reservation_bytes
diff --git a/tests/app/routers/test_working_memory_calibration.py b/tests/app/routers/test_working_memory_calibration.py
index 35cc2de322..1f7cbb83e3 100644
--- a/tests/app/routers/test_working_memory_calibration.py
+++ b/tests/app/routers/test_working_memory_calibration.py
@@ -2,8 +2,8 @@
import threading
from pathlib import Path
+from types import SimpleNamespace
from typing import Any
-from unittest.mock import MagicMock
import pytest
import torch
@@ -11,7 +11,11 @@ from fastapi.testclient import TestClient
from invokeai.app.api_app import app
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
+from invokeai.app.invocations.fields import BoardField
+from invokeai.app.invocations.image import BlankImageInvocation
from invokeai.app.invocations.math import AddInvocation
+from invokeai.app.invocations.model import LoRACollectionLoader, LoRAField, ModelIdentifierField
+from invokeai.app.invocations.sd.sdxl import SDXLModelLoaderInvocation
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.model_records import UnknownModelException
from invokeai.app.services.session_queue.session_queue_default import SessionQueue
@@ -19,8 +23,10 @@ from invokeai.app.services.shared.database.database import Database
from invokeai.app.services.shared.graph import Graph
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
CALIBRATION_DESTINATION,
+ CalibrationStoreLockTimeoutError,
calibration_origin,
)
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
from tests.app.routers.conftest import MockApiDependencies, _auth
from tests.fixtures.working_memory_calibration import (
GPU,
@@ -43,12 +49,27 @@ def calibration(
services.session_queue = queue
queue.start(mock_invoker)
- def get_model(key: str) -> MagicMock:
- if key != "model-key":
+ model = SimpleNamespace(
+ key="model-key",
+ name="Model",
+ hash="blake3:abc",
+ base=BaseModelType.StableDiffusionXL,
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant=None,
+ )
+ # Installed too, and no model the plan covers: only `get_model` knows it.
+ other = SimpleNamespace(
+ key="other-key", name="Other", hash="blake3:def", base=BaseModelType.StableDiffusionXL, type=ModelType.Main
+ )
+
+ def get_model(key: str) -> SimpleNamespace:
+ if key not in ("model-key", "other-key"):
raise UnknownModelException(f"unknown model {key}")
- return MagicMock(key=key, hash="blake3:abc")
+ return model if key == "model-key" else other
services.model_manager.store.get_model.side_effect = get_model
+ services.model_manager.store.all_models.return_value = [model]
_DEVICES[:] = [GPU]
service = calibration_service(tmp_path, devices=lambda: list(_DEVICES))
service.start(mock_invoker)
@@ -57,7 +78,8 @@ def calibration(
mock_deps = MockApiDependencies(mock_invoker)
monkeypatch.setattr("invokeai.app.api.routers.session_queue.ApiDependencies", mock_deps)
monkeypatch.setattr("invokeai.app.api.routers.image_move_maintenance.ApiDependencies", mock_deps)
- return queue, service
+ yield queue, service
+ service.stop(mock_invoker)
def _graph() -> dict:
@@ -67,9 +89,10 @@ def _graph() -> dict:
def _calibrate(client: TestClient, token: str, body: dict | None = None, key: str = "model-key"):
+ """Posts `body`; one that names no graph_models states none, as for a graph naming no model."""
return client.post(
f"/api/v2/models/i/{key}/working_memory/calibrate",
- json=body if body is not None else {"graph": _graph()},
+ json={"graph_models": {}, **(body if body is not None else {"graph": _graph()})},
headers=_auth(token),
)
@@ -111,9 +134,11 @@ def test_non_admins_cannot_calibrate_reset_read_or_export(
client.delete(f"/api/v2/models/working_memory/runs/{run_id}", headers=_auth(user1_token)),
client.delete("/api/v2/models/i/model-key/working_memory", headers=_auth(user1_token)),
client.delete("/api/v2/models/working_memory", headers=_auth(user1_token)),
+ client.get("/api/v2/models/i/model-key/working_memory/plan", headers=_auth(user1_token)),
+ client.get("/api/v2/models/i/model-key/working_memory/summary", headers=_auth(user1_token)),
]
- assert [response.status_code for response in responses] == [403] * 6
+ assert [response.status_code for response in responses] == [403] * 8
assert queue.get_queue_item_ids("default").item_ids == item_ids
@@ -157,15 +182,39 @@ def test_calibrate_rejects_unknown_models_workflow_calls_and_server_owned_fields
call_graph = Graph()
call_graph.add_node(CallSavedWorkflowInvocation(id="call", workflow_id="workflow"))
use_cache_data = [[{"node_path": "add", "field_name": "use_cache", "items": [True]}]]
+ intermediate_data = [[{"node_path": "add", "field_name": "is_intermediate", "items": [False]}]]
assert _calibrate(client, admin_token, key="missing").status_code == 404
assert _calibrate(client, admin_token, {"graph": call_graph.model_dump(mode="json")}).status_code == 422
assert _calibrate(client, admin_token, {"graph": _graph(), "data": use_cache_data}).status_code == 422
+ assert _calibrate(client, admin_token, {"graph": _graph(), "data": intermediate_data}).status_code == 422
assert _calibrate(client, admin_token, {"graph": _graph(), "origin": "canvas"}).status_code == 422
assert queue.get_queue_item_ids("default").item_ids == []
assert service.get_status().device_classes[0].runs == []
+def _image_graph() -> dict:
+ """The decode's output as a client sends it for the gallery: not an intermediate, on a board."""
+ graph = Graph()
+ graph.add_node(AddInvocation(id="add", a=1, b=2, is_intermediate=False))
+ graph.add_node(BlankImageInvocation(id="blank", is_intermediate=False, board=BoardField(board_id="gallery-board")))
+ return graph.model_dump(mode="json")
+
+
+def test_calibrate_makes_every_node_save_intermediates_on_no_board(
+ client: TestClient, admin_token: str, calibration
+) -> None:
+ queue, _ = calibration
+
+ response = _calibrate(client, admin_token, {"graph": _image_graph()})
+
+ assert response.status_code == 201, response.text
+ item = queue.get_queue_item(response.json()["item_ids"][0])
+ nodes = item.session.graph.nodes
+ assert [node.is_intermediate for node in nodes.values()] == [True, True]
+ assert nodes["blank"].board is None
+
+
def test_retrying_a_calibration_item_keeps_its_origin_and_owner(
client: TestClient, admin_token: str, calibration
) -> None:
@@ -184,6 +233,28 @@ def test_retrying_a_calibration_item_keeps_its_origin_and_owner(
assert (retried.origin, retried.user_id) == (calibration_origin(created["run_id"]), item.user_id)
+def test_a_retry_the_calibration_store_cannot_count_is_refused_with_503_naming_no_path(
+ client: TestClient, admin_token: str, calibration, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ queue, service = calibration
+ [item_id] = _calibrate(client, admin_token).json()["item_ids"]
+ assert queue.dequeue() is not None
+ queue.fail_queue_item(item_id, "ValueError", "failed", "traceback")
+ lock = str(service._store.directory / "abc.json.lock")
+
+ def timed_out(*args: Any, **kwargs: Any) -> None:
+ raise CalibrationStoreLockTimeoutError(f"Timed out waiting for the lock on {lock}")
+
+ monkeypatch.setattr(service._store, "change", timed_out)
+ response = client.put("/api/v1/queue/default/retry_items_by_id", json=[item_id], headers=_auth(admin_token))
+
+ assert response.status_code == 503
+ assert response.json()["detail"] == (
+ "The working-memory calibration store cannot be written now, so no item was retried. Try again."
+ )
+ assert queue.dequeue() is None
+
+
def test_status_reset_and_export_for_admins(client: TestClient, admin_token: str, calibration) -> None:
_, service = calibration
run_id = _calibrate(client, admin_token).json()["run_id"]
@@ -210,6 +281,29 @@ def test_status_reset_and_export_for_admins(client: TestClient, admin_token: str
assert missing_class.status_code == 404
+def test_plan_and_summary_for_admins(client: TestClient, admin_token: str, calibration) -> None:
+ _, service = calibration
+ run_id = _calibrate(client, admin_token).json()["run_id"]
+ service.record_windows(run_id, [measured_window(run_id, model_key="model-key")])
+
+ plan = client.get("/api/v2/models/i/model-key/working_memory/plan", headers=_auth(admin_token))
+ assert plan.status_code == 200, plan.text
+ body = plan.json()
+ assert body["supported"] and body["device_class"]["id"] == GPU_CLASS.id and body["estimators"] == ["vae.sd"]
+ assert {case["line"] for case in body["cases"]} == {"decode_fp16", "decode_fp32"}
+ assert client.get("/api/v2/models/i/missing/working_memory/plan", headers=_auth(admin_token)).status_code == 404
+
+ summary = client.get("/api/v2/models/i/model-key/working_memory/summary", headers=_auth(admin_token))
+ assert summary.status_code == 200, summary.text
+ # The window's features name no line: it is counted, not fitted.
+ assert summary.json()["excluded_windows"] == 1 and summary.json()["runs"][0]["run_id"] == run_id
+ # A model removed meanwhile, as the plan says.
+ assert client.get("/api/v2/models/i/missing/working_memory/summary", headers=_auth(admin_token)).status_code == 404
+ _DEVICES[:] = [GPU, torch.device("cuda:1")]
+ no_class = client.get("/api/v2/models/i/model-key/working_memory/summary", headers=_auth(admin_token))
+ assert no_class.status_code == 409
+
+
def test_a_repeated_calibrate_with_its_retry_key_returns_the_same_run(
client: TestClient, admin_token: str, calibration
) -> None:
@@ -295,6 +389,60 @@ def test_the_status_carries_the_device_class_id(client: TestClient, admin_token:
}
+def test_calibrate_records_the_attempt_and_rejects_a_malformed_one(
+ client: TestClient, admin_token: str, calibration
+) -> None:
+ _, service = calibration
+
+ created = _calibrate(client, admin_token, {"graph": _graph(), "attempt_id": "attempt-7", "attempt_steps": 3})
+ malformed = _calibrate(client, admin_token, {"graph": _graph(), "attempt_id": "no spaces", "attempt_steps": 3})
+
+ assert created.status_code == 201 and malformed.status_code == 422
+ status = client.get("/api/v2/models/working_memory/status", headers=_auth(admin_token)).json()
+ [run] = status["device_classes"][0]["runs"]
+ assert (run["run_id"], run["attempt_id"], run["attempt_steps"]) == (created.json()["run_id"], "attempt-7", 3)
+ assert "measurement_verified" in status["device_classes"][0]
+
+
+ "attempt",
+ [
+ {"attempt_id": "alone"},
+ {"attempt_steps": 2},
+ {"attempt_id": "zero", "attempt_steps": 0},
+ {"attempt_id": "too-many", "attempt_steps": 257},
+ ],
+ ids=["attempt-without-steps", "steps-without-attempt", "no-steps", "above-the-bound"],
+)
+def test_an_attempt_and_its_step_count_come_together_or_not_at_all(
+ client: TestClient, admin_token: str, calibration, attempt: dict
+) -> None:
+ _, service = calibration
+
+ response = _calibrate(client, admin_token, {"graph": _graph(), **attempt})
+
+ assert response.status_code == 422, response.text
+ assert [run for device_class in service.get_status().device_classes for run in device_class.runs] == []
+
+
+def test_a_run_whose_step_count_differs_from_its_attempts_is_a_conflict(
+ client: TestClient, admin_token: str, calibration
+) -> None:
+ """The attempt feeds a fit once it has its planned runs: a run that plans another count would make that count
+ ambiguous, whether it is another run of the attempt or a repeat of one."""
+ _, service = calibration
+ first = {"graph": _graph(), "attempt_id": "attempt", "attempt_steps": 2, "idempotency_key": "step-1"}
+ assert _calibrate(client, admin_token, first).status_code == 201
+
+ other_run = _calibrate(client, admin_token, {**first, "attempt_steps": 3, "idempotency_key": "step-2"})
+ repeat = _calibrate(client, admin_token, {**first, "attempt_steps": 3})
+
+ assert (other_run.status_code, repeat.status_code) == (409, 409), (other_run.text, repeat.text)
+ assert "attempt_steps" in other_run.json()["detail"]
+ [run] = service.get_status().device_classes[0].runs
+ assert run.attempt_steps == 2
+
+
def test_a_store_directory_that_cannot_be_listed_answers_the_status_with_503(
client: TestClient, admin_token: str, calibration, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -323,3 +471,196 @@ def test_a_retry_key_reused_for_an_unknown_model_is_a_conflict(
response = _calibrate(client, admin_token, body, key="no-such-model")
assert response.status_code == 409, response.text
+
+
+_RECORD = {
+ "key": "model-key",
+ "hash": "blake3:abc",
+ "name": "Model",
+ "base": "sdxl",
+ "type": "main",
+ "format": "checkpoint",
+ "variant": None,
+}
+"""model-key's record in the fixture, as a client reads it."""
+
+
+def _loader_body(list_field: bool = False, identifier: dict | None = None, **compiled: Any) -> dict:
+ """A request whose graph names the model as the client compiled it, `compiled` overriding the current record: in a
+ loader's model field, or as the LoRA of a collection loader's list, and in graph_models. `identifier` overrides
+ the graph's identifier alone."""
+ record = {**_RECORD, **compiled}
+ named = ModelIdentifierField(
+ **{**{fact: record[fact] for fact in ("key", "hash", "name", "base", "type")}, **(identifier or {})}
+ )
+ graph = Graph()
+ if list_field:
+ graph.add_node(LoRACollectionLoader(id="loras", loras=[LoRAField(lora=named, weight=1.0)]))
+ else:
+ graph.add_node(SDXLModelLoaderInvocation(id="loader", model=named))
+ identity = {fact: record[fact] for fact in ("hash", "base", "type", "format", "variant")}
+ return {"graph": graph.model_dump(mode="json"), "graph_models": {record["key"]: identity}}
+
+
+ "list_field, compiled, message",
+ [
+ (False, {"hash": "blake3:compiled-before"}, "Model changed after this calibration was planned (hash)."),
+ (False, {"base": "sd-1"}, "Model changed after this calibration was planned (base)."),
+ (False, {"type": "lora"}, "Model changed after this calibration was planned (type)."),
+ (False, {"format": "diffusers"}, "Model changed after this calibration was planned (format)."),
+ (False, {"variant": "inpaint"}, "Model changed after this calibration was planned (variant)."),
+ (False, {"key": "gone-key", "name": "Gone"}, "Gone was removed after this calibration was planned."),
+ (True, {"hash": "blake3:compiled-before"}, "Model changed after this calibration was planned (hash)."),
+ (True, {"variant": "inpaint"}, "Model changed after this calibration was planned (variant)."),
+ ],
+ ids=["hash", "base", "type", "format", "variant", "removed", "list-field-hash", "list-field-variant"],
+)
+def test_a_graph_compiled_against_an_older_record_of_the_model_is_refused_with_a_code(
+ client: TestClient, admin_token: str, calibration, list_field: bool, compiled: dict, message: str
+) -> None:
+ """The client compiled the graph, then the model's record changed or went before the request arrived. A record
+ without a variant compiled to null, which it still matches."""
+ queue, _ = calibration
+ current = _calibrate(client, admin_token, _loader_body(list_field))
+ stale = _calibrate(client, admin_token, _loader_body(list_field, **compiled))
+
+ assert current.status_code == 201, current.text
+ assert stale.status_code == 409, stale.text
+ assert stale.json()["detail"] == {"code": "model_changed", "message": f"{message} Calibrate again."}
+ assert queue.get_queue_item_ids("default").item_ids == current.json()["item_ids"]
+
+
+ "fact, stale",
+ [("hash", "blake3:compiled-before"), ("base", "sd-1")],
+ ids=["hash", "base"],
+)
+def test_a_graph_whose_identifier_names_an_older_record_is_refused_though_graph_models_is_current(
+ client: TestClient, admin_token: str, calibration, fact: str, stale: str
+) -> None:
+ """graph_models states the record as it is, and the graph itself was compiled against an older one: the run would
+ load what the identifier names."""
+ queue, _ = calibration
+
+ response = _calibrate(client, admin_token, _loader_body(identifier={fact: stale}))
+
+ assert response.status_code == 409, response.text
+ assert response.json()["detail"] == {
+ "code": "model_changed",
+ "message": f"Model changed after this calibration was planned ({fact}). Calibrate again.",
+ }
+ assert queue.get_queue_item_ids("default").item_ids == []
+
+
+def _without(identity: dict, fact: str) -> dict:
+ return {name: value for name, value in identity.items() if name != fact}
+
+
+ "graph_models, loc, message",
+ [
+ ({}, ["body"], "the graph names model-key, which graph_models lacks"),
+ (
+ {"model-key": "same", "other-key": "same"},
+ ["body"],
+ "graph_models names other-key, which the graph does not",
+ ),
+ ({"model-key": "without variant"}, ["body", "graph_models", "model-key", "variant"], "Field required"),
+ ({"model-key": "null hash"}, ["body", "graph_models", "model-key", "hash"], "Input should be a valid string"),
+ (
+ {"model-key": "unknown fact"},
+ ["body", "graph_models", "model-key", "path"],
+ "Extra inputs are not permitted",
+ ),
+ ],
+ ids=["missing", "extra", "unstated-variant", "null-hash", "unknown-fact"],
+)
+def test_graph_models_must_state_exactly_the_graphs_models_with_every_fact(
+ client: TestClient, admin_token: str, calibration, graph_models: dict, loc: list[str], message: str
+) -> None:
+ """A null variant is a stated fact; an absent one is not."""
+ queue, _ = calibration
+ body = _loader_body()
+ identity = body["graph_models"]["model-key"]
+ stated = {
+ "same": identity,
+ "without variant": _without(identity, "variant"),
+ "null hash": {**identity, "hash": None},
+ "unknown fact": {**identity, "path": "/models/model.safetensors"},
+ }
+
+ response = _calibrate(
+ client, admin_token, {**body, "graph_models": {k: stated[v] for k, v in graph_models.items()}}
+ )
+
+ assert response.status_code == 422, response.text
+ [error] = response.json()["detail"]
+ assert error["loc"] == loc and message in error["msg"], error
+ assert queue.get_queue_item_ids("default").item_ids == []
+
+
+def test_a_request_without_graph_models_is_refused(client: TestClient, admin_token: str, calibration) -> None:
+ response = client.post(
+ "/api/v2/models/i/model-key/working_memory/calibrate", json={"graph": _graph()}, headers=_auth(admin_token)
+ )
+
+ assert response.status_code == 422, response.text
+ assert "graph_models" in response.text
+
+
+def test_an_attempt_is_refused_with_a_code_while_another_one_runs(
+ client: TestClient, admin_token: str, calibration
+) -> None:
+ """Another tab's attempt still waits in the queue: a new attempt is refused, the running attempt's next step is
+ not. (Two requests at once are `test_two_attempts_started_at_once_queue_only_the_first`.)"""
+ first = {"graph": _graph(), "attempt_id": "first-tab", "attempt_steps": 2}
+ second = {"graph": _graph(), "attempt_id": "second-tab", "attempt_steps": 2}
+ assert _calibrate(client, admin_token, first).status_code == 201
+
+ refused = _calibrate(client, admin_token, second)
+
+ assert refused.status_code == 409, refused.text
+ assert refused.json()["detail"] == {
+ "code": "calibration_running",
+ "message": "Another calibration is still running on this GPU. Wait until it has finished, or stop it, then "
+ "calibrate again.",
+ }
+ assert _calibrate(client, admin_token, first).status_code == 201
+
+
+def test_a_later_step_after_another_calibration_ran_is_refused_with_a_code(
+ client: TestClient, admin_token: str, calibration
+) -> None:
+ queue, _ = calibration
+ step = {"graph": _graph(), "attempt_id": "model-tab", "attempt_steps": 2}
+ [item_id] = _calibrate(client, admin_token, step).json()["item_ids"]
+ queue.dequeue()
+ queue.complete_queue_item(item_id)
+ [other] = _calibrate(client, admin_token).json()["item_ids"]
+ queue.dequeue()
+ queue.complete_queue_item(other)
+
+ refused = _calibrate(client, admin_token, step | {"idempotency_key": "step-2"})
+
+ assert refused.status_code == 409, refused.text
+ assert refused.json()["detail"] == {
+ "code": "calibration_interleaved",
+ "message": "Another calibration ran on this GPU after this calibration started, so its measurements can no "
+ "longer be combined. Calibrate again.",
+ }
+
+
+def test_an_attempt_on_another_model_is_refused_while_one_runs_on_the_gpu(
+ client: TestClient, admin_token: str, calibration
+) -> None:
+ """One attempt at a time per GPU, not per model: another model's attempt would measure between its steps."""
+ running = {"graph": _graph(), "attempt_id": "model-tab", "attempt_steps": 2}
+ assert _calibrate(client, admin_token, running).status_code == 201
+
+ refused = _calibrate(
+ client, admin_token, {"graph": _graph(), "attempt_id": "other-tab", "attempt_steps": 2}, key="other-key"
+ )
+
+ assert refused.status_code == 409, refused.text
+ assert refused.json()["detail"]["code"] == "calibration_running"
diff --git a/tests/app/services/session_processor/conftest.py b/tests/app/services/session_processor/conftest.py
index 6a9a2aec88..4353cdda6a 100644
--- a/tests/app/services/session_processor/conftest.py
+++ b/tests/app/services/session_processor/conftest.py
@@ -2,6 +2,8 @@ from types import SimpleNamespace
import pytest
+from invokeai.backend.working_memory import user_fit
+
@pytest.fixture(autouse=True)
def _no_real_paged_vram_reading(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -12,6 +14,13 @@ def _no_real_paged_vram_reading(monkeypatch: pytest.MonkeyPatch) -> None:
)
[email protected](autouse=True)
+def _no_user_fit_provider(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A started calibration service registers the process-global provider every estimate asks; one a test leaves
+ running must not price the estimates of later tests on this worker."""
+ monkeypatch.setattr(user_fit, "_provider", None)
+
+
@pytest.fixture(autouse=True)
def _no_full_collection_per_claimed_item(monkeypatch: pytest.MonkeyPatch) -> None:
"""The worker runs a full collection before each claimed item. It walks the whole heap: most of a second in a
diff --git a/tests/app/services/session_processor/test_working_memory_calibration_runner.py b/tests/app/services/session_processor/test_working_memory_calibration_runner.py
index c7e3b40746..2a45239a4e 100644
--- a/tests/app/services/session_processor/test_working_memory_calibration_runner.py
+++ b/tests/app/services/session_processor/test_working_memory_calibration_runner.py
@@ -19,19 +19,23 @@ from unittest.mock import MagicMock
import pytest
import torch
+from PIL import Image
from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation
from invokeai.app.invocations.call_saved_workflow import CallSavedWorkflowInvocation
-from invokeai.app.invocations.fields import InputField
-from invokeai.app.invocations.primitives import IntegerOutput
+from invokeai.app.invocations.fields import BoardField, InputField, WithBoard
+from invokeai.app.invocations.primitives import ImageOutput, IntegerOutput
+from invokeai.app.services.image_files.image_files_disk import DiskImageFileStorage
from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.names.names_default import SimpleNameService
from invokeai.app.services.session_processor.session_processor_common import CanceledException
from invokeai.app.services.session_processor.session_processor_default import DefaultSessionRunner
-from invokeai.app.services.session_queue.session_queue_common import Batch, SessionQueueItem
+from invokeai.app.services.session_queue.session_queue_common import Batch, BatchDatum, SessionQueueItem
from invokeai.app.services.session_queue.session_queue_default import SessionQueue
from invokeai.app.services.shared.database.database import Database
from invokeai.app.services.shared.graph import Graph, GraphExecutionState
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.app.services.urls.urls_default import LocalUrlService
from invokeai.app.services.users.users_common import UserCreateRequest, UserUpdateRequest
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
WorkingMemoryCalibrationRequest,
@@ -40,6 +44,7 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibration
from invokeai.app.services.working_memory_calibration.working_memory_calibration_default import (
WorkingMemoryCalibrationService,
)
+from invokeai.backend.util.vae_working_memory import VAE_SD_SPEC
from invokeai.backend.working_memory import probe
from tests.fixtures.sqlite_database import sqlite_cursor_of
from tests.fixtures.working_memory_calibration import GPU, GPU_CLASS, OTHER_CLASS, calibration_service, measured_window
@@ -72,6 +77,20 @@ class CalibrationProbeNodeInvocation(BaseInvocation):
return IntegerOutput(value=1)
+# The images each image node saved.
+_SAVED: list[str] = []
+
+
+@invocation("test_working_memory_calibration_image_node", version="1.0.0")
+class CalibrationImageNodeInvocation(BaseInvocation, WithBoard):
+ """Saves an image, as a decode node does."""
+
+ def invoke(self, context: InvocationContext) -> ImageOutput:
+ image = context.images.save(image=Image.new("RGB", (8, 8)))
+ _SAVED.append(image.image_name)
+ return ImageOutput.build(image)
+
+
class _Stats:
@contextmanager
def collect_stats(self, invocation, graph_execution_state_id) -> Iterator[None]:
@@ -89,10 +108,12 @@ def _reset_seen() -> Iterator[None]:
_SEEN.clear()
_ON_CANCEL.clear()
_WHILE_RUNNING.clear()
+ _SAVED.clear()
yield
_SEEN.clear()
_ON_CANCEL.clear()
_WHILE_RUNNING.clear()
+ _SAVED.clear()
@pytest.fixture
@@ -110,11 +131,12 @@ def queue(mock_invoker: Invoker, mock_sqlite_database: Database) -> SessionQueue
@pytest.fixture
-def service(tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue) -> WorkingMemoryCalibrationService:
+def service(tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue) -> Iterator[WorkingMemoryCalibrationService]:
service = calibration_service(tmp_path)
service.start(mock_invoker)
mock_invoker.services.working_memory_calibration = service
- return service
+ yield service
+ service.stop(mock_invoker)
@pytest.fixture
@@ -134,7 +156,9 @@ def _graph(*behaviours: str) -> Graph:
def _create(service: WorkingMemoryCalibrationService, user_id: str, *behaviours: str) -> tuple[str, int]:
created = asyncio.run(
- service.create_run("model-key", WorkingMemoryCalibrationRequest(graph=_graph(*behaviours)), user_id)
+ service.create_run(
+ "model-key", WorkingMemoryCalibrationRequest(graph_models={}, graph=_graph(*behaviours)), user_id
+ )
)
return created.run_id, created.item_ids[0]
@@ -146,6 +170,17 @@ def _run_next(queue: SessionQueue, runner: DefaultSessionRunner) -> SessionQueue
return queue.get_queue_item(item.item_id)
+def image_storage(tmp_path: Path, mock_invoker: Invoker) -> None:
+ """Images saved to disk under `tmp_path`, with their records in the test database."""
+ services = mock_invoker.services
+ services.image_files = DiskImageFileStorage(tmp_path / "images")
+ services.names = SimpleNameService()
+ services.urls = LocalUrlService()
+ services.image_files.start(mock_invoker)
+ services.images.start(mock_invoker)
+
+
def _stored_points(tmp_path: Path) -> list[dict]:
path = tmp_path / "working_memory" / f"{GPU_CLASS.id}.json"
return json.loads(path.read_bytes())["points"]
@@ -300,6 +335,150 @@ def test_an_ordinary_item_runs_without_a_probe_scope(
assert not (tmp_path / "working_memory").exists()
+def test_a_calibration_items_images_are_intermediates_on_no_board(
+ service: WorkingMemoryCalibrationService, queue: SessionQueue, runner, mock_invoker: Invoker, image_storage: None
+) -> None:
+ """The client sent the node as a gallery output on a board; the server made it an intermediate on none, which
+ Clear Intermediates removes like any other."""
+ services = mock_invoker.services
+ board = services.board_records.save("Gallery board", "system")
+ graph = Graph()
+ graph.add_node(
+ CalibrationImageNodeInvocation(id="image", board=BoardField(board_id=board.board_id), is_intermediate=False)
+ )
+ asyncio.run(
+ service.create_run("model-key", WorkingMemoryCalibrationRequest(graph_models={}, graph=graph), "system")
+ )
+
+ assert _run_next(queue, runner[0]).status == "completed"
+ [name] = _SAVED
+ assert services.image_records.get(name).is_intermediate is True
+ assert services.board_image_records.get_board_for_image(name) is None
+ assert services.images.get_image_names(is_intermediate=False, is_admin=True).image_names == []
+
+
+_ESTIMATED: list[str] = []
+
+
+@invocation("test_working_memory_estimate_node", version="1.0.0")
+class EstimateNodeInvocation(BaseInvocation):
+ """Prices a 1024px fp16 SD decode on the GPU, as `l2i` does, and records where the estimate's values came from."""
+
+ def invoke(self, context: InvocationContext) -> IntegerOutput:
+ features = {
+ "operation": "decode",
+ "height": 1024,
+ "width": 1024,
+ "tile": None,
+ "dtype": "fp16",
+ "vae_class": "AutoencoderKL",
+ "upcast_weight_bytes": 0,
+ "score_matrix_bytes": 0,
+ }
+ _ESTIMATED.append(VAE_SD_SPEC.estimate(features, GPU).source)
+ return IntegerOutput(value=1)
+
+
+def _line_windows(run_id: str) -> list:
+ """Windows that fit the fp16 decode line the estimate node prices with."""
+ return [
+ measured_window(run_id, estimator="vae.sd", version=VAE_SD_SPEC.version).model_copy(
+ update={
+ "features": {
+ "operation": "decode",
+ "height": side,
+ "width": side,
+ "tile": None,
+ "dtype": "fp16",
+ "upcast_weight_bytes": 0,
+ },
+ "demand_bytes": 900 * side**2 + 400 * 2**20,
+ }
+ )
+ for side in (512, 1024)
+ ]
+
+
+def test_each_item_start_reads_the_calibrations_recorded_before_it(
+ service: WorkingMemoryCalibrationService, queue: SessionQueue, runner
+) -> None:
+ _ESTIMATED.clear()
+ graph = Graph()
+ graph.add_node(EstimateNodeInvocation(id="estimate"))
+ batch = Batch(graph=graph, origin="canvas")
+ run_id, _ = _create(service, "system", "complete")
+
+ asyncio.run(queue.enqueue_batch("default", batch, prepend=False))
+ queue.cancel_queue_item(queue.dequeue().item_id) # type: ignore[union-attr] # the calibration item
+ service.record_windows(run_id, _line_windows(run_id))
+ _run_next(queue, runner[0])
+ service.reset_run(run_id)
+ asyncio.run(queue.enqueue_batch("default", batch, prepend=False))
+ _run_next(queue, runner[0])
+
+ first, second = _ESTIMATED
+ assert first.startswith(f"user:{GPU_CLASS.id}:") and second.startswith("shipped:")
+
+
+def test_windows_of_a_run_still_running_join_no_fit_until_it_finished(
+ service: WorkingMemoryCalibrationService, queue: SessionQueue, runner
+) -> None:
+ """Every item start refreshes the fits, yet the windows of a run still running join none: an item that runs
+ between a run's items (an ordinary generation here) is priced without them, and the next one after the run
+ finished with them."""
+ _ESTIMATED.clear()
+ estimate = Graph()
+ estimate.add_node(EstimateNodeInvocation(id="estimate"))
+ two_items = WorkingMemoryCalibrationRequest(
+ graph_models={},
+ graph=_graph("complete"),
+ data=[[BatchDatum(node_path="node0", field_name="behaviour", items=["complete", "complete"])]],
+ )
+ run_id = asyncio.run(service.create_run("model-key", two_items, "system")).run_id
+
+ def generate() -> None:
+ asyncio.run(queue.enqueue_batch("default", Batch(graph=estimate, origin="canvas"), prepend=True))
+ assert _run_next(queue, runner[0]).status == "completed"
+
+ assert _run_next(queue, runner[0]).status == "completed" # the run's first item
+ service.record_windows(run_id, _line_windows(run_id))
+ generate()
+ assert _run_next(queue, runner[0]).status == "completed" # its second, which finishes it
+ generate()
+
+ assert [source.split(":")[0] for source in _ESTIMATED] == ["shipped", "user"]
+
+
+def test_the_finished_steps_of_an_attempt_join_no_fit_while_a_later_step_waits(
+ service: WorkingMemoryCalibrationService, queue: SessionQueue, runner
+) -> None:
+ """A client posts every step of an attempt up front, each as its own run: the first step finishing must not price
+ the later, larger steps, so its windows wait for the whole attempt."""
+ _ESTIMATED.clear()
+ estimate = Graph()
+ estimate.add_node(EstimateNodeInvocation(id="estimate"))
+
+ def step() -> str:
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_graph("complete"), attempt_id="attempt", attempt_steps=2
+ )
+ return asyncio.run(service.create_run("model-key", request, "system")).run_id
+
+ first, _ = step(), step()
+
+ def generate() -> None:
+ asyncio.run(queue.enqueue_batch("default", Batch(graph=estimate, origin="canvas"), prepend=True))
+ assert _run_next(queue, runner[0]).status == "completed"
+
+ assert _run_next(queue, runner[0]).status == "completed" # step 1 finishes; step 2 still waits
+ service.record_windows(first, _line_windows(first))
+ generate()
+ assert _run_next(queue, runner[0]).status == "completed" # step 2, which finishes the attempt
+ generate()
+
+ assert [source.split(":")[0] for source in _ESTIMATED] == ["shipped", "user"]
+
+
def test_a_store_failure_fails_the_item_and_stops_the_session(
tmp_path: Path, service: WorkingMemoryCalibrationService, queue: SessionQueue, runner, monkeypatch
) -> None:
diff --git a/tests/app/services/session_queue/test_session_queue_query_plans.py b/tests/app/services/session_queue/test_session_queue_query_plans.py
index 7bb6f36cb3..0c306b9f66 100644
--- a/tests/app/services/session_queue/test_session_queue_query_plans.py
+++ b/tests/app/services/session_queue/test_session_queue_query_plans.py
@@ -140,6 +140,17 @@ def test_the_lineage_read_tests_the_origin_on_the_listing_index(
assert "TEMP B-TREE" not in lineage.plan
+def test_the_unfinished_origins_read_finds_its_rows_by_their_status(
+ session_queue: SessionQueue, database: Database
+) -> None:
+ """The working-memory fits ask before every queue item which calibration items are still to run: it costs the live
+ rows, not the queue's history."""
+ _enqueue(session_queue)
+ [unfinished] = _statements(database, lambda: session_queue.get_unfinished_origins("default", ORIGIN_PREFIX))
+ assert ANY_STATUS_SEEK.search(unfinished.plan), unfinished
+ assert LISTING_INDEX not in unfinished.plan, unfinished
+
+
def test_a_non_admins_project_reads_keep_their_plans(session_queue: SessionQueue, database: Database) -> None:
"""Limited to the caller's items, a project's listing and counts still read the listing index alone, and its
current and next items are still found by their status: the account's own index would read its whole history."""
diff --git a/tests/app/services/session_queue/test_session_queue_reads.py b/tests/app/services/session_queue/test_session_queue_reads.py
index 4a84ad95b5..c3e2be534f 100644
--- a/tests/app/services/session_queue/test_session_queue_reads.py
+++ b/tests/app/services/session_queue/test_session_queue_reads.py
@@ -365,6 +365,25 @@ class TestServiceReads:
assert [summary.item_id for summary in summaries] == [child, *reversed(item_ids)]
assert (summaries[0].parent_item_id, summaries[0].user_email) == (item_ids[0], "[email protected]")
+ def test_unfinished_origins_are_those_of_the_live_items_with_the_prefix(
+ self, database: Database, service: SessionQueue
+ ) -> None:
+ for status in ("pending", "in_progress", "waiting", "completed", "failed", "canceled"):
+ _item(database, status=status, origin=f"tool_run:{status}")
+ # The prefix matches ignoring case, its `_` only itself, and only in this queue.
+ _item(database, origin="TOOL_RUN:upper")
+ _item(database, origin="toolXrun:lookalike")
+ _item(database, origin="tool_run:other-queue", queue_id="other")
+ _item(database, origin="canvas")
+ _item(database)
+
+ assert service.get_unfinished_origins(QUEUE, "tool_run:") == {
+ "tool_run:pending",
+ "tool_run:in_progress",
+ "tool_run:waiting",
+ "TOOL_RUN:upper",
+ }
+
def test_batch_status_and_destination_counts(self, database: Database, service: SessionQueue) -> None:
_item(database, batch_id="b", status="pending", origin="canvas", destination="gallery")
_item(database, batch_id="b", status="completed", origin="canvas", destination="gallery")
diff --git a/tests/app/services/session_queue/test_session_queue_writes.py b/tests/app/services/session_queue/test_session_queue_writes.py
index 7accd02fce..a055e85193 100644
--- a/tests/app/services/session_queue/test_session_queue_writes.py
+++ b/tests/app/services/session_queue/test_session_queue_writes.py
@@ -62,7 +62,11 @@ def events() -> TestEventService:
def _service(database: Database, events: TestEventService, **config: Any) -> SessionQueue:
configuration = InvokeAIAppConfig(use_memory_db=True, **config)
services = SimpleNamespace(
- configuration=configuration, events=events, logger=logging.getLogger("queue"), model_manager=None
+ configuration=configuration,
+ events=events,
+ logger=logging.getLogger("queue"),
+ model_manager=None,
+ working_memory_calibration=None,
)
queue = SessionQueue(database)
queue.start(cast(Invoker, SimpleNamespace(services=services)))
diff --git a/tests/app/services/test_invoker.py b/tests/app/services/test_invoker.py
index 7ff7fd0e23..3058449927 100644
--- a/tests/app/services/test_invoker.py
+++ b/tests/app/services/test_invoker.py
@@ -94,7 +94,9 @@ def test_a_calibration_item_pending_at_startup_runs_once_every_service_started(
creator.start(mock_invoker)
graph = Graph()
graph.add_node(AddInvocation(id="add", a=1, b=2))
- created = asyncio.run(creator.create_run("model-key", WorkingMemoryCalibrationRequest(graph=graph), "system"))
+ created = asyncio.run(
+ creator.create_run("model-key", WorkingMemoryCalibrationRequest(graph_models={}, graph=graph), "system")
+ )
[item_id] = created.item_ids
# This process: new services over the same database and root, started by its invoker.
diff --git a/tests/app/services/working_memory_calibration/conftest.py b/tests/app/services/working_memory_calibration/conftest.py
new file mode 100644
index 0000000000..4392909af9
--- /dev/null
+++ b/tests/app/services/working_memory_calibration/conftest.py
@@ -0,0 +1,10 @@
+import pytest
+
+from invokeai.backend.working_memory import user_fit
+
+
[email protected](autouse=True)
+def _no_user_fit_provider(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A started calibration service registers the process-global provider every estimate asks; one a test leaves
+ running must not price the estimates of later tests on this worker."""
+ monkeypatch.setattr(user_fit, "_provider", None)
diff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_fragmentation.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_fragmentation.py
new file mode 100644
index 0000000000..ddb845227a
--- /dev/null
+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_fragmentation.py
@@ -0,0 +1,274 @@
+"""Which calibration windows count toward a user fit, on the windows a real SDXL calibration measured.
+
+The numbers are an RX 9060 XT export's (16 GB, ROCm on Windows, `vae.sd` decode, one UI attempt of 18 windows), cut
+to the fields the rules read. Its fp32 1216px windows ran on a fragmented allocator: their allocated bytes match to the
+byte, while reserved stands 1.30 to 1.47 times allocated against 1.10 at 576px and 832px. Fitted on, the fp32 line
+priced a 1024px decode at 8.3 GiB, 2.4 GiB over the shipped estimate.
+"""
+
+import datetime
+import math
+from fractions import Fraction
+from typing import Optional
+
+import pytest
+
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
+ CalibrationDeviceClass,
+ CalibrationEnvironment,
+ CalibrationPoint,
+ CalibrationRun,
+ CalibrationStoreFile,
+)
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_fits import (
+ exclusions,
+ model_lines,
+ user_fit_of,
+)
+from invokeai.backend.util.vae_working_memory import VAE_SD_SPEC
+from invokeai.backend.working_memory import user_fit
+from invokeai.backend.working_memory.coefficients import shipped_coefficients
+from invokeai.backend.working_memory.fingerprint import DeviceClass, Environment
+from invokeai.backend.working_memory.platform import Platform
+from invokeai.backend.working_memory.probe import CounterDelta
+from invokeai.backend.working_memory.spec import import_estimator_modules
+from tests.fixtures.working_memory_calibration import measured_window
+
+MIB = 2**20
+PLATFORM = Platform("miopen", "expandable", "windows")
+CARD = DeviceClass(vendor="amd", name="AMD Radeon RX 9060 XT", total_mib=16304, backend="hip", arch="gfx1200")
+ENV = Environment(hard={"os": "windows", "torch": "2.13", "hip": "7.15"}, soft={"driver": "test"})
+
+# dtype, side, upcast_weight_bytes, score_matrix_bytes, fit_eligible, demand, reserved delta, allocated delta; in the
+# order they ran. Not fit-eligible means partial_residency.
+WINDOWS = [
+ ("fp16", 1024, 0, 1073741824, True, 1992294400, 1992294400, 1610874880),
+ ("fp16", 1024, 0, 1073741824, True, 1887436800, 1887436800, 1610874880),
+ ("fp16", 1024, 0, 1073741824, True, 1887436800, 1887436800, 1610874880),
+ ("fp16", 1472, 0, 1073741824, True, 4047503360, 4047503360, 3328721920),
+ ("fp16", 1472, 0, 1073741824, True, 3902799872, 3902799872, 3328721920),
+ ("fp16", 1472, 0, 1073741824, True, 3902799872, 3902799872, 3328721920),
+ ("fp16", 2112, 0, 1073741824, False, 8011120640, 8011120640, 6852510720),
+ ("fp16", 2112, 0, 1073741824, True, 8875147264, 8875147264, 6852510720),
+ ("fp16", 2112, 0, 1073741824, False, 8870952960, 8870952960, 6852510720),
+ ("fp32", 576, 167307726, 456855552, True, 1954545664, 1900019712, 1870138368),
+ ("fp32", 576, 0, 456855552, True, 1887436800, 1887436800, 1702840320),
+ ("fp32", 576, 0, 456855552, True, 1887436800, 1887436800, 1702840320),
+ ("fp32", 832, 0, 1073741824, True, 3900702720, 3900702720, 3552839680),
+ ("fp32", 832, 0, 1073741824, True, 3900702720, 3900702720, 3552839680),
+ ("fp32", 832, 0, 1073741824, True, 3900702720, 3900702720, 3552839680),
+ ("fp32", 1216, 0, 1073741824, False, 9835642880, 9835642880, 7589201920),
+ ("fp32", 1216, 0, 1073741824, True, 11135877120, 11135877120, 7589201920),
+ ("fp32", 1216, 0, 1073741824, False, 10842275840, 10842275840, 7589201920),
+]
+
+
+def _delta(value: int) -> CounterDelta:
+ return CounterDelta(baseline=0, peak=value, offset=0, delta=value)
+
+
+def _file(attempts: Optional[list[tuple[str, list[tuple]]]] = None) -> CalibrationStoreFile:
+ """The windows as one run's, or per attempt, each a run of its own carrying that `attempt_id`, in that order."""
+ env = CalibrationEnvironment.of(ENV)
+ points = []
+ runs = []
+ for hour, (attempt, windows) in enumerate(attempts or [("run", WINDOWS)]):
+ for item, (dtype, side, upcast, scores, eligible, demand, reserved, allocated) in enumerate(windows):
+ window = measured_window(
+ attempt, 141 + item, model_key="sdxl:vae", estimator="vae.sd", version=VAE_SD_SPEC.version
+ )
+ features = {
+ "operation": "decode",
+ "height": side,
+ "width": side,
+ "tile": None,
+ "dtype": dtype,
+ "vae_class": "AutoencoderKL",
+ "upcast_weight_bytes": upcast,
+ "score_matrix_bytes": scores,
+ }
+ update = {
+ "features": features,
+ "demand_bytes": demand,
+ "reserved": _delta(reserved),
+ "allocated": _delta(allocated),
+ "fit_eligible": eligible,
+ "reasons": [] if eligible else ["partial_residency"],
+ }
+ points.append(CalibrationPoint(**window.model_copy(update=update).model_dump(), env_id=env.id))
+ runs.append(
+ CalibrationRun(
+ run_id=attempt,
+ model_key="sdxl",
+ model_hash=None,
+ user_id="system",
+ created_at=datetime.datetime(2026, 10, 18, hour, tzinfo=datetime.timezone.utc),
+ env_id=env.id,
+ attempt_id=attempt if attempts else None,
+ )
+ )
+ return CalibrationStoreFile(
+ schema_version=1, device_class=CalibrationDeviceClass.of(CARD), runs=runs, points=points, envs=[env]
+ )
+
+
+def _features(dtype: str, side: int) -> dict:
+ return {
+ "operation": "decode",
+ "height": side,
+ "width": side,
+ "tile": None,
+ "dtype": dtype,
+ "vae_class": "AutoencoderKL",
+ "upcast_weight_bytes": 0,
+ "score_matrix_bytes": 1073741824,
+ }
+
+
+def test_the_fragmented_fp32_1216px_windows_drop_out_and_the_others_count() -> None:
+ reasons = exclusions(_file())
+
+ # Rows 15-17: the one fit-eligible window is a ratio outlier (1.47 against 1.10 at the smaller sizes); its two
+ # partly resident neighbours never counted. Rows 6 and 8 are partly resident; the fp16 2112px window that ran
+ # fully resident (1.30 against 1.24 and 1.22) counts. Row 9 was upcast and measures no line at all.
+ assert reasons == {6: "partial_residency", 8: "partial_residency", 15: "partial_residency", 16: "fragmented",
+ 17: "partial_residency"} # fmt: skip
+
+
+def test_without_them_the_fp32_line_rests_on_576px_and_832px_and_1024px_prices_as_shipped() -> None:
+ fit, problems = user_fit_of(_file(), CalibrationEnvironment.of(ENV).id, PLATFORM)
+ assert fit is not None, problems
+ [fp32] = [line for (_, suffix), line in fit.lines.items() if suffix == "decode_fp32"]
+
+ # The two counted sizes, by hand: the chord through their readings beats the edge from the origin, plus 5%.
+ (x0, y0), (x1, y1) = (576**2, 1887436800), (832**2, 3900702720)
+ k = Fraction(y1 - y0, x1 - x0)
+ b = y0 - k * x0
+ assert (fp32.k, fp32.b) == (math.ceil(k * Fraction(21, 20)), math.ceil(b * Fraction(21, 20) / MIB) * MIB)
+ assert (fp32.x_min, fp32.x_max) == (576**2, 832**2)
+
+ features = _features("fp32", 1024)
+ shipped = shipped_coefficients(VAE_SD_SPEC, PLATFORM)
+ shipped_bytes = VAE_SD_SPEC.evaluate(features, shipped).reservation_bytes
+ # Above the measured sizes the larger estimate wins, and here that is the shipped one (5.9 GiB, not 8.3 GiB).
+ assert fp32.k * 1024**2 + fp32.b < shipped_bytes
+ assert user_fit.resolve(VAE_SD_SPEC, features, shipped, fit).reservation_bytes == shipped_bytes
+
+
+def test_the_summary_shows_the_sizes_that_do_not_count_and_why() -> None:
+ file = _file()
+
+ lines, excluded = model_lines(
+ file,
+ "sdxl",
+ ENV,
+ lambda env: PLATFORM,
+ import_estimator_modules(),
+ priced_on=[],
+ name_of=lambda key: "SDXL",
+ )
+
+ by_line = {line.line: line for line in lines}
+ assert [
+ (size.width, size.windows, size.counted, size.excluded_reason) for size in by_line["decode_fp32"].sizes
+ ] == [
+ (576, 2, True, None),
+ (832, 3, True, None),
+ (1216, 3, False, "fragmented"),
+ ]
+ assert [(size.width, size.windows, size.counted) for size in by_line["decode_fp16"].sizes] == [
+ (1024, 3, True),
+ (1472, 3, True),
+ (2112, 1, True),
+ ]
+ fragmented = by_line["decode_fp32"].sizes[-1]
+ assert fragmented.measured_bytes == 11135877120 and fragmented.user_bytes is not None
+ assert by_line["decode_fp32"].own_windows == 5
+ # Not counted: the upcast window, the four partly resident ones and the fragmented one.
+ assert excluded == 6
+
+
+def test_a_measurement_whose_reserve_grew_around_a_flat_allocation_drops_out_without_a_smaller_size() -> None:
+ """The fp32 1216px windows as if all three had run fully resident, with no smaller size to compare: reserved
+ grew 1.13 times from the first to the largest while allocated did not move a byte."""
+ file = _file()
+ file.points = [point.model_copy(update={"fit_eligible": True, "reasons": []}) for point in file.points[15:18]]
+
+ assert exclusions(file) == {0: "fragmented", 1: "fragmented", 2: "fragmented"}
+
+
+# The RX 9060 XT's fp32 windows of two later attempts (store rows 28-35 and 46-53): the first of them fragmented at
+# 1152px (the one fully resident window reserves 1.43 times what it allocates, beside two partly resident ones); the
+# next, run with every other model moved out first, clean (1.00 to 1.10).
+FRAGMENTED_ATTEMPT = [
+ ("fp32", 576, 0, 456855552, True, 1887436800, 1887436800, 1702840320),
+ ("fp32", 576, 0, 456855552, True, 1887436800, 1887436800, 1702840320),
+ ("fp32", 768, 0, 1073741824, True, 3334471680, 3334471680, 3027271680),
+ ("fp32", 768, 0, 1073741824, True, 3334471680, 3334471680, 3027271680),
+ ("fp32", 768, 0, 1073741824, True, 3334471680, 3334471680, 3027271680),
+ ("fp32", 1152, 0, 1073741824, False, 8157921280, 8157921280, 6811361280),
+ ("fp32", 1152, 0, 1073741824, True, 9751756800, 9751756800, 6811361280),
+ ("fp32", 1152, 0, 1073741824, False, 8724152320, 8724152320, 6811361280),
+]
+CLEAN_ATTEMPT = [
+ ("fp32", 576, 0, 456855552, True, 1866465280, 1866465280, 1702840320),
+ ("fp32", 576, 0, 456855552, True, 1866465280, 1866465280, 1702840320),
+ ("fp32", 768, 0, 1073741824, True, 3313500160, 3313500160, 3027271680),
+ ("fp32", 768, 0, 1073741824, True, 3313500160, 3313500160, 3027271680),
+ ("fp32", 768, 0, 1073741824, True, 3313500160, 3313500160, 3027271680),
+ ("fp32", 1152, 0, 1073741824, True, 6815744000, 6815744000, 6811361280),
+ ("fp32", 1152, 0, 1073741824, True, 7465861120, 7465861120, 6811361280),
+ ("fp32", 1152, 0, 1073741824, True, 7465861120, 7465861120, 6811361280),
+]
+
+
+def _reasons_by_attempt(file: CalibrationStoreFile, reasons: dict) -> dict[str, list]:
+ found: dict[str, list] = {}
+ for index, point in enumerate(file.points):
+ if point.features["width"] == 1152:
+ found.setdefault(point.run_id, []).append(reasons.get(index))
+ return found
+
+
[email protected]("order", ["fragmented-then-clean", "clean-then-fragmented"])
+def test_each_attempt_at_a_size_is_judged_on_its_own(order: str) -> None:
+ """Pooled, the clean 1152px windows would share the fragmented one's fate: as its ratio outlier, or, after them,
+ as a reserve that grew 1.43 times over the first of theirs at the same allocation. Per attempt, the clean one
+ counts."""
+ attempts = [("fragmented", FRAGMENTED_ATTEMPT), ("clean", CLEAN_ATTEMPT)]
+ file = _file(attempts if order == "fragmented-then-clean" else attempts[::-1])
+
+ assert _reasons_by_attempt(file, exclusions(file)) == {
+ "fragmented": ["partial_residency", "fragmented", "partial_residency"],
+ "clean": [None, None, None],
+ }
+ lines, _ = model_lines(
+ file, "sdxl", ENV, lambda env: PLATFORM, import_estimator_modules(), priced_on=[], name_of=lambda key: None
+ )
+ [size] = [size for size in lines[0].sizes if size.width == 1152]
+ assert (size.counted, size.windows, size.measured_bytes) == (True, 3, 7465861120)
+
+
+def test_two_owners_attempts_with_one_id_are_judged_apart() -> None:
+ """Two administrators each ran an attempt named "1": one clean, one fragmented. Pooled as one measurement, the clean
+ windows would share the fragmented ones' fate."""
+ file = _file([("fragmented", FRAGMENTED_ATTEMPT), ("clean", CLEAN_ATTEMPT)])
+ file.runs = [
+ run.model_copy(update={"attempt_id": "1", "user_id": owner})
+ for run, owner in zip(file.runs, ("admin-a", "admin-b"), strict=True)
+ ]
+
+ assert _reasons_by_attempt(file, exclusions(file)) == {
+ "fragmented": ["partial_residency", "fragmented", "partial_residency"],
+ "clean": [None, None, None],
+ }
+
+
+def test_a_running_attempts_windows_set_no_standard_for_finished_sizes() -> None:
+ """The fragmented attempt's 1152px window, with no smaller size of its own finished: while the clean attempt still
+ runs, its 576px and 768px windows are no reference, so nothing finished flags it yet."""
+ fragmented_1152 = [window for window in FRAGMENTED_ATTEMPT if window[1] == 1152]
+ file = _file([("finished", fragmented_1152), ("running", CLEAN_ATTEMPT)])
+
+ assert "fragmented" in exclusions(file).values()
+ assert "fragmented" not in exclusions(file, {"running": "running"}).values()
diff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py
new file mode 100644
index 0000000000..a7566c8e2d
--- /dev/null
+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py
@@ -0,0 +1,891 @@
+"""The calibration plan: which cases calibrate a model on this GPU, which models share its lines, and when it cannot."""
+
+import importlib
+import inspect
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import psutil
+import pytest
+import torch
+from diffusers import AutoencoderKL, AutoencoderKLFlux2
+
+from invokeai.app.services.config import get_config
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_default import _vae_dtypes
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_plan import (
+ DECODE_LINES,
+ FLUX2_PIPELINE_VAE_DTYPE,
+ FORCE_TILED_BASES,
+ SDNQ_PIPELINE_VAE_DTYPE,
+ VAE_WEIGHTS_ALLOWANCE_BYTES,
+ VaeDtypes,
+ build_plan,
+ case_sides,
+)
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+from invokeai.backend.model_manager.load.model_loaders.flux import (
+ Flux2DiffusersModel,
+ Flux2SDNQCheckpointModel,
+ FluxSDNQDiffusersModel,
+)
+from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageSDNQCheckpointModel
+from invokeai.backend.model_manager.taxonomy import (
+ BaseModelType,
+ Flux2VariantType,
+ FluxVariantType,
+ ModelFormat,
+ ModelType,
+ ModelVariantType,
+ Qwen3VariantType,
+ SubModelType,
+)
+from invokeai.backend.util import devices, vae_working_memory
+from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.vae_working_memory import dtype_name
+from invokeai.backend.working_memory import counters
+from invokeai.backend.working_memory.fingerprint import DeviceClass
+from invokeai.backend.working_memory.platform import Platform
+from invokeai.backend.working_memory.probe import calibration_reservation
+from invokeai.backend.working_memory.spec import import_estimator_modules
+from tests.fixtures.working_memory_calibration import GPU, GPU_VAE_DTYPES, calibration_service
+
+GIB = 2**30
+MIB = 2**20
+CARD = DeviceClass(vendor="nvidia", name="Test GPU 24GB", total_mib=24 * 1024, backend="cuda", arch="sm_89")
+CUDNN = Platform("cudnn", "native", "linux")
+BYTES_PER_PIXEL = {"fp16": 1000, "bf16": 1000, "fp32": 2000}
+
+
+def _model(key: str, base: BaseModelType, type: ModelType = ModelType.Main, **fields) -> SimpleNamespace:
+ return SimpleNamespace(key=key, name=key.upper(), base=base, type=type, **fields)
+
+
+def _reservation(estimator: str, height: int, width: int, dtype: str) -> int:
+ return BYTES_PER_PIXEL[dtype] * height * width
+
+
+QWEN3_8B = _model("qwen3-8b", BaseModelType.Any, ModelType.Qwen3Encoder, variant=Qwen3VariantType.Qwen3_8B)
+"""The standalone text encoder Generate fills in for a FLUX.2 Klein 9B model, or one without a variant, that is no
+pipeline: without one, or a pipeline whose encoder fits, its graph does not compile."""
+
+
+def _plan(
+ target,
+ models=(),
+ *,
+ device_class=CARD,
+ unavailable=None,
+ precision="auto",
+ vae_dtypes=GPU_VAE_DTYPES,
+ reservation=_reservation,
+ capacity_bytes=None,
+):
+ return build_plan(
+ target,
+ [target, *models],
+ device_class=device_class if unavailable is None else None,
+ unavailable=unavailable,
+ platform=CUDNN if unavailable is None else None,
+ precision=precision,
+ vae_dtypes=vae_dtypes,
+ reservation=reservation,
+ specs=import_estimator_modules(),
+ capacity_bytes=capacity_bytes,
+ )
+
+
+def test_an_sdxl_model_runs_three_sizes_per_vae_precision() -> None:
+ """24 GiB: a decode may claim 90% less 1 GiB for the VAE, 22119081574 bytes, and the calibration lock reserves
+ 1.5x the estimate. At 1000 B/px (fp16) the largest square is 3840px (3904px would need 22.9e9 bytes); a quarter and
+ a half of its area are 1920px and 2715px, rounded down to 2688px. At 2000 B/px (fp32) the largest is 2688px."""
+ sdxl = _model("sdxl", BaseModelType.StableDiffusionXL)
+
+ plan = _plan(sdxl)
+
+ assert plan.supported and plan.reason is None
+ assert plan.device_class is not None and plan.device_class.id == CARD.id
+ assert plan.estimators == ["vae.sd"]
+ assert [(case.line, case.width, case.height, case.settings) for case in plan.cases] == [
+ ("decode_fp16", 1920, 1920, {"vaePrecision": "fp16"}),
+ ("decode_fp16", 2688, 2688, {"vaePrecision": "fp16"}),
+ ("decode_fp16", 3840, 3840, {"vaePrecision": "fp16"}),
+ ("decode_fp32", 1344, 1344, {"vaePrecision": "fp32"}),
+ ("decode_fp32", 1856, 1856, {"vaePrecision": "fp32"}),
+ ("decode_fp32", 2688, 2688, {"vaePrecision": "fp32"}),
+ ]
+ assert {(case.mode, case.model_key, case.steps, case.estimator) for case in plan.cases} == {
+ ("txt2img", "sdxl", 2, "vae.sd")
+ }
+ assert len({case.id for case in plan.cases}) == 6
+ assert (plan.repetitions.warm_up, plan.repetitions.measured) == (1, 2)
+ assert plan.estimated_seconds is not None and plan.estimated_seconds > 0
+ assert any("encode" in note for note in plan.not_covered)
+
+
+ "base, precision, estimator, lines",
+ [
+ (BaseModelType.StableDiffusion1, "auto", "vae.sd", ["decode_fp16", "decode_fp32"]),
+ (BaseModelType.StableDiffusion3, "auto", "vae.sd3", ["decode_fp16"]),
+ (BaseModelType.StableDiffusion3, "bfloat16", "vae.sd3", ["decode_bf16"]),
+ (BaseModelType.Flux, "auto", "vae.flux", ["decode_bf16"]),
+ (BaseModelType.ZImage, "auto", "vae.flux", ["decode_bf16"]),
+ (BaseModelType.Flux2, "auto", "vae.flux2", ["decode_bf16"]),
+ (BaseModelType.CogView4, "auto", "vae.cogview4", ["decode_bf16"]),
+ ],
+)
+def test_each_covered_base_plans_the_lines_its_decode_runs(base, precision, estimator, lines) -> None:
+ vae_base = BaseModelType.Flux if base == BaseModelType.ZImage else base
+ plan = _plan(_model("main", base), [_model("vae", vae_base, ModelType.VAE), QWEN3_8B], precision=precision)
+
+ assert plan.supported and plan.estimators == [estimator]
+ assert sorted({case.line for case in plan.cases}) == lines
+ # Only the SD nodes cast the VAE; elsewhere the loader decides the dtype.
+ assert all(bool(case.settings) == (base == BaseModelType.StableDiffusion1) for case in plan.cases)
+
+
+FP32_VAES = VaeDtypes(standalone_flux="fp32", z_image_pipeline="bf16", sdnq_quantized_vae=lambda config: False)
+"""`precision: float32`: the standalone FLUX VAE loaders keep it; a Z-Image pipeline's own VAE still loads in bf16."""
+
+
+def _shipped_untiled_decode(estimator: str, height: int, width: int, dtype: str) -> int:
+ return vae_working_memory.estimate_untiled_vae_decode(estimator, height, width, dtype, GPU).reservation_bytes
+
+
+ "target, models",
+ [
+ (_model("flux", BaseModelType.Flux), [_model("ae", BaseModelType.Flux, ModelType.VAE)]),
+ (
+ _model("flux2-vae", BaseModelType.Flux2, ModelType.VAE),
+ [_model("klein", BaseModelType.Flux2, format="diffusers")],
+ ),
+ ],
+ ids=["flux-main", "flux2-vae"],
+)
+def test_a_flux_vae_kept_in_fp32_plans_the_fp32_line_at_the_sizes_fp32_decodes_untiled(target, models) -> None:
+ """With the shipped cuDNN/native values (no materialized attention scores) on a 24 GiB card, the largest untiled
+ bf16 decode is 1792px and the fp32 one 1344px. A configured float32 loads a standalone FLUX VAE in fp32, so the plan
+ must size for that: planned at bf16, its 1792px case would cross the pre-tiling threshold and measure nothing."""
+ with patch.object(vae_working_memory, "sdpa_score_matrix_bytes", return_value=0):
+ at_bf16 = _plan(target, models, reservation=_shipped_untiled_decode)
+ at_fp32 = _plan(target, models, vae_dtypes=FP32_VAES, reservation=_shipped_untiled_decode)
+
+ assert [(case.line, case.width) for case in at_bf16.cases] == [
+ ("decode_bf16", 896),
+ ("decode_bf16", 1216),
+ ("decode_bf16", 1792),
+ ]
+ assert [(case.line, case.width) for case in at_fp32.cases] == [
+ ("decode_fp32", 640),
+ ("decode_fp32", 896),
+ ("decode_fp32", 1344),
+ ]
+
+
+def test_a_configured_fp32_leaves_a_z_image_pipeline_decoding_in_its_own_vaes_dtype() -> None:
+ z_image = _model("z-image", BaseModelType.ZImage, format="diffusers")
+ flux_vae = _model("ae", BaseModelType.Flux, ModelType.VAE)
+
+ assert {case.line for case in _plan(z_image, [flux_vae], vae_dtypes=FP32_VAES).cases} == {"decode_bf16"}
+ # Its standalone VAE, calibrated through it, keeps the configured fp32.
+ assert {case.line for case in _plan(flux_vae, [z_image], vae_dtypes=FP32_VAES).cases} == {"decode_fp32"}
+
+
+_PIPELINE_SUBMODELS = {
+ SubModelType.Transformer: None,
+ SubModelType.VAE: None,
+ SubModelType.TextEncoder: None,
+ SubModelType.Tokenizer: None,
+}
+_FLUX1_PIPELINE_SUBMODELS = _PIPELINE_SUBMODELS | {SubModelType.TextEncoder2: None, SubModelType.Tokenizer2: None}
+
+
+def _sdnq_pipeline(key: str, base: BaseModelType, **fields) -> SimpleNamespace:
+ submodels = _FLUX1_PIPELINE_SUBMODELS if base == BaseModelType.Flux else _PIPELINE_SUBMODELS
+ return _model(key, base, format=ModelFormat.SDNQQuantized, submodels=submodels, **fields)
+
+
+def _lines_of(plan) -> set[tuple[str, tuple[tuple[str, str], ...]]]:
+ return {(case.line, tuple(case.components.items())) for case in plan.cases}
+
+
+ "pipeline, line",
+ [
+ (_model("klein", BaseModelType.Flux2, format="diffusers"), "decode_bf16"),
+ (_model("z-image", BaseModelType.ZImage, format="diffusers"), "decode_fp16"),
+ (_sdnq_pipeline("klein-sdnq", BaseModelType.Flux2), "decode_fp32"),
+ (_sdnq_pipeline("z-image-sdnq", BaseModelType.ZImage), "decode_fp32"),
+ (_sdnq_pipeline("flux-sdnq", BaseModelType.Flux), "decode_fp32"),
+ (_sdnq_pipeline("flux-sdnq-quantized-vae", BaseModelType.Flux), "decode_bf16"),
+ ],
+ ids=["flux2-diffusers", "z-image-diffusers", "flux2-sdnq", "z-image-sdnq", "flux-sdnq", "flux-sdnq-quantized-vae"],
+)
+def test_a_pipeline_decodes_in_the_dtype_its_own_vae_loads_in(pipeline, line) -> None:
+ """With an empty `vae` slot a FLUX.2 or Z-Image Diffusers pipeline and a self-contained SDNQ pipeline decode with
+ their own VAE: bf16 for FLUX.2 Diffusers, the device's bf16-safe dtype for Z-Image (here fp16), fp32 for the SDNQ
+ pipelines, whose loaders give no dtype, and bf16 for an SDNQ-quantized FLUX.1 VAE. A CPU VAE installed beside them
+ is no reason to pick one: Generate fills no `vae` slot for a pipeline."""
+ vae_base = BaseModelType.Flux2 if pipeline.base == BaseModelType.Flux2 else BaseModelType.Flux
+ standalone = [
+ _model("a-cpu-vae", vae_base, ModelType.VAE, cpu_only=True),
+ _model("b-gpu-vae", vae_base, ModelType.VAE, cpu_only=False),
+ ]
+ vaes = VaeDtypes(
+ standalone_flux="fp32",
+ z_image_pipeline="fp16",
+ sdnq_quantized_vae=lambda config: config.key == "flux-sdnq-quantized-vae",
+ )
+
+ assert _lines_of(_plan(pipeline, standalone, vae_dtypes=vaes)) == {(line, ())}
+
+
+def test_a_flux_sdnq_pipeline_without_the_t5_pair_decodes_with_a_standalone_vae() -> None:
+ """Generate requires FLUX.1's `vae` slot unless the SDNQ pipeline ships every component, T5 included."""
+ partial = _model("flux-sdnq", BaseModelType.Flux, format=ModelFormat.SDNQQuantized, submodels=_PIPELINE_SUBMODELS)
+ vae = [_model("ae", BaseModelType.Flux, ModelType.VAE)]
+
+ assert {case.line for case in _plan(partial, vae, vae_dtypes=FP32_VAES).cases} == {"decode_fp32"}
+ assert {case.line for case in _plan(partial, vae).cases} == {"decode_bf16"}
+
+
+GGUF_KLEIN_9B = _model("klein-9b-gguf", BaseModelType.Flux2, format="gguf_quantized", variant=Flux2VariantType.Klein9B)
+
+
+ "sources, line",
+ [
+ # The first installed pipeline whose Qwen3 encoder fits the 9B transformer, wherever it is listed.
+ (
+ [
+ _sdnq_pipeline("a-sdnq-4b", BaseModelType.Flux2, variant=Flux2VariantType.Klein4B),
+ _model("b-diffusers-9b", BaseModelType.Flux2, format="diffusers", variant=Flux2VariantType.Klein9B),
+ ],
+ "decode_bf16",
+ ),
+ # Without a fitting one, the first pipeline at all, which gives the VAE beside the standalone encoder.
+ ([_sdnq_pipeline("a-sdnq-4b", BaseModelType.Flux2, variant=Flux2VariantType.Klein4B)], "decode_fp32"),
+ # Without a pipeline, Generate fills the slot with a standalone VAE.
+ ([_model("flux2-vae", BaseModelType.Flux2, ModelType.VAE)], "decode_fp16"),
+ ],
+ ids=["fitting-diffusers-source", "only-an-sdnq-source", "no-source"],
+)
+def test_a_flux2_model_without_its_own_vae_decodes_with_its_component_source_vae(sources, line) -> None:
+ """Generate gives a GGUF or checkpoint FLUX.2 model an installed FLUX.2 pipeline as its component source
+ (`getAutoFlux2ComponentSourceModel`), and the FLUX.2 model loader node decodes with that pipeline's VAE. A standalone
+ Qwen3 8B encoder is installed, as one that fits no pipeline needs."""
+ vaes = VaeDtypes(standalone_flux="fp16", z_image_pipeline="bf16", sdnq_quantized_vae=lambda config: False)
+
+ assert _lines_of(_plan(GGUF_KLEIN_9B, [*sources, QWEN3_8B], vae_dtypes=vaes)) == {(line, ())}
+
+
+KLEIN_4B_SDNQ = _sdnq_pipeline("klein-4b-sdnq", BaseModelType.Flux2, variant=Flux2VariantType.Klein4B)
+FLUX2_VAE = _model("flux2-vae", BaseModelType.Flux2, ModelType.VAE)
+QWEN3_4B = _model("qwen3-4b", BaseModelType.Any, ModelType.Qwen3Encoder, variant=Qwen3VariantType.Qwen3_4B)
+GGUF_DEV = _model("dev-gguf", BaseModelType.Flux2, format="gguf_quantized", variant=Flux2VariantType.Dev)
+
+
+ "target, models, encoder",
+ [
+ (GGUF_KLEIN_9B, [KLEIN_4B_SDNQ], "Qwen3 8B"),
+ (GGUF_KLEIN_9B, [KLEIN_4B_SDNQ, FLUX2_VAE], "Qwen3 8B"),
+ (GGUF_KLEIN_9B, [FLUX2_VAE], "Qwen3 8B"),
+ # The 4B encoder fits the 4B transformer only.
+ (GGUF_KLEIN_9B, [KLEIN_4B_SDNQ, QWEN3_4B], "Qwen3 8B"),
+ (GGUF_DEV, [KLEIN_4B_SDNQ, FLUX2_VAE, QWEN3_8B], "Mistral"),
+ # A VAE goes through the only main model that takes its pick, which cannot generate.
+ (FLUX2_VAE, [GGUF_KLEIN_9B], "Qwen3 8B"),
+ ],
+ ids=["unfitting-source", "unfitting-source-and-vae", "vae-alone", "encoder-of-another-size", "dev", "vae-target"],
+)
+def test_a_flux2_model_without_a_text_encoder_generate_can_use_cannot_be_calibrated(target, models, encoder) -> None:
+ """A FLUX.2 model that is no pipeline compiles only with a text encoder: a fitting pipeline's, or a standalone one of
+ its size. A pipeline that does not fit gives only its VAE, so beside it alone, or beside a standalone VAE, no case
+ compiles: `pnpm graphs:export` rejects each with "Generate needs a Qwen3 Encoder" ("a Mistral Encoder" for [dev])."""
+ plan = _plan(target, models)
+
+ assert not plan.supported and plan.cases == [] and plan.device_class is not None
+ assert "text encoder" in (plan.reason or "") and f"{encoder} encoder" in (plan.reason or "")
+
+
+def test_a_flux2_vae_is_calibrated_through_a_main_model_whose_graph_compiles() -> None:
+ """The GGUF model sorts first but has no encoder; the 4B pipeline brings its own and takes the `vae` pick."""
+ gguf = _model("a-klein-9b-gguf", BaseModelType.Flux2, format="gguf_quantized", variant=Flux2VariantType.Klein9B)
+ pipeline = _sdnq_pipeline("b-klein-4b-sdnq", BaseModelType.Flux2, variant=Flux2VariantType.Klein4B)
+
+ plan = _plan(FLUX2_VAE, [gguf, pipeline])
+
+ assert (plan.supported, plan.calibrated_through) == (True, "b-klein-4b-sdnq")
+ assert _lines_of(plan) == {("decode_bf16", (("vae", "flux2-vae"),))}
+
+
+def test_a_flux2_model_decoding_with_its_component_source_picks_no_vae_beside_a_cpu_one() -> None:
+ """Generate fills no `vae` slot while a component source supplies the VAE, so a CPU-only VAE is no reason to pin
+ another: the pin would decode with a standalone VAE instead of the source's."""
+ models = [
+ _model("klein-9b-diffusers", BaseModelType.Flux2, format="diffusers", variant=Flux2VariantType.Klein9B),
+ _model("a-cpu-vae", BaseModelType.Flux2, ModelType.VAE, cpu_only=True),
+ _model("b-gpu-vae", BaseModelType.Flux2, ModelType.VAE, cpu_only=False),
+ ]
+
+ assert _lines_of(_plan(GGUF_KLEIN_9B, models, vae_dtypes=FP32_VAES)) == {("decode_bf16", ())}
+
+
+def test_a_standalone_flux_vae_is_not_calibrated_through_an_sdnq_pipeline_that_drops_the_pick() -> None:
+ """Generate sends no VAE for a self-contained FLUX.1 SDNQ pipeline, which decodes with its own, so a VAE target goes
+ through another main model, here one that sorts after it; without one it cannot be calibrated."""
+ flux_vae = _model("ae", BaseModelType.Flux, ModelType.VAE)
+ sdnq = _sdnq_pipeline("a-flux-sdnq", BaseModelType.Flux)
+ flux = _model("b-flux", BaseModelType.Flux)
+
+ plan = _plan(flux_vae, [sdnq, flux], vae_dtypes=FP32_VAES)
+ alone = _plan(flux_vae, [sdnq])
+
+ assert (plan.calibrated_through, _lines_of(plan)) == ("b-flux", {("decode_fp32", (("vae", "ae"),))})
+ assert not alone.supported and "takes a VAE pick" in (alone.reason or "") and alone.cases == []
+
+
+CARD_16GB = DeviceClass(vendor="amd", name="AMD Radeon RX 9060 XT", total_mib=16304, backend="hip", arch="gfx1200")
+OUTSIDE_MIB = 2628
+"""What a 16 GB card measured in use besides the torch allocator while its calibration decoded (driver less torch's
+reserve, RX 9060 XT on Windows)."""
+# About what the shipped SD estimates price a decode at there: 9058 MiB at 2112px fp16, 8521 MiB at 1216px fp32.
+SD_16GB_PER_PIXEL = {"fp16": 2100, "fp32": 6000}
+
+
+def _sd_16gb(estimator: str, height: int, width: int, dtype: str) -> int:
+ return SD_16GB_PER_PIXEL[dtype] * height * width
+
+
+def test_on_a_16gb_card_the_largest_size_leaves_the_vae_fully_resident_beside_its_reservation() -> None:
+ """The cache can give 16304 - 2628 = 13676 MiB, below the 14673 MiB the pretile share allows; less 1 GiB for the
+ VAE, the reservation (1.5x the estimate) may take 12652 MiB, 13266583552 bytes. fp16 at 2100 B/px: 2048px needs
+ 13212057600, 2112px 14050713600. fp32 at 6000 B/px: 1152px needs 11943936000, 1216px 13307904000. The share of the
+ card alone would have allowed 2112px and 1216px, the sizes that ran partly resident."""
+ plan = _plan(
+ _model("sdxl", BaseModelType.StableDiffusionXL),
+ device_class=CARD_16GB,
+ reservation=_sd_16gb,
+ capacity_bytes=(CARD_16GB.total_mib - OUTSIDE_MIB) * 2**20,
+ )
+
+ assert [(case.line, case.width) for case in plan.cases] == [
+ ("decode_fp16", 1024),
+ ("decode_fp16", 1408),
+ ("decode_fp16", 2048),
+ ("decode_fp32", 576),
+ ("decode_fp32", 768),
+ ("decode_fp32", 1152),
+ ]
+
+
+def _cache(device: str, *, reserve_gb: float = 0.0, cap_gb: float | None = None) -> ModelCache:
+ """A model cache whose execution device is `device`, built on the CPU: every memory query is patched out."""
+ cache = ModelCache(
+ execution_device_working_mem_gb=1.0,
+ enable_partial_loading=True,
+ keep_ram_copy_of_weights=True,
+ max_vram_cache_size_gb=cap_gb,
+ reserve_vram_gb=reserve_gb,
+ execution_device="cpu",
+ storage_device="cpu",
+ logger=MagicMock(),
+ )
+ cache._execution_device = torch.device(device)
+ return cache
+
+
+def _plan_with_cache(tmp_path: Path, mock_invoker: Invoker, device: torch.device, device_class: DeviceClass, cache):
+ sdxl = _model("sdxl", BaseModelType.StableDiffusionXL)
+ model_manager = MagicMock()
+ model_manager.store.get_model.return_value = sdxl
+ model_manager.store.all_models.return_value = [sdxl]
+ model_manager.load.ram_caches = {str(device): cache}
+ mock_invoker.services.model_manager = model_manager
+ service = calibration_service(
+ tmp_path,
+ devices=lambda: [device],
+ device_class=device_class,
+ untiled_decode_reservation=lambda estimator, height, width, dtype, device: _sd_16gb(
+ estimator, height, width, dtype
+ ),
+ device_memory=None,
+ )
+ service.start(mock_invoker)
+ try:
+ return service.get_plan("sdxl")
+ finally:
+ service.stop(mock_invoker)
+
+
+ "process_mib, reserve_gb, cap_gb",
+ [(16304 - OUTSIDE_MIB, 0.0, None), (16304, OUTSIDE_MIB / 1024, None), (16304, 0.0, (16304 - OUTSIDE_MIB) / 1024)],
+ ids=["outside-use", "reserve-vram", "cache-cap"],
+)
+def test_the_plan_sizes_for_what_the_cache_gives_a_calibration_lock(
+ tmp_path: Path, mock_invoker: Invoker, monkeypatch: pytest.MonkeyPatch, process_mib: int, reserve_gb, cap_gb
+) -> None:
+ """A dedicated card: the calibration's offload moves every other model out, so what they hold counts; the cache's
+ reserve and cap apply."""
+ monkeypatch.setattr(
+ TorchDevice, "cuda_mem_get_info", classmethod(lambda cls, device: ((process_mib - 2048) * MIB, 16304 * MIB))
+ )
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device=None: 2048 * MIB)
+ cache = _cache("cuda:0", reserve_gb=reserve_gb, cap_gb=cap_gb)
+
+ plan = _plan_with_cache(tmp_path, mock_invoker, GPU, CARD_16GB, cache)
+
+ assert max(case.width for case in plan.cases if case.line == "decode_fp16") == 2048
+ assert max(case.width for case in plan.cases if case.line == "decode_fp32") == 1152
+
+
+def test_a_working_memory_floor_beyond_what_the_cache_gives_leaves_nothing_to_plan(
+ tmp_path: Path, mock_invoker: Invoker, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A lock never reserves less than `device_working_mem_gb`. Set beyond what the cache can give a calibration on
+ the card (the 16 GB card of the test above, 2048px at the default), even the smallest case's lock would leave the
+ VAE partly loaded: the plan says the card cannot calibrate rather than queue cases whose windows fit no line."""
+ monkeypatch.setattr(TorchDevice, "cuda_mem_get_info", classmethod(lambda cls, device: (14256 * MIB, 16304 * MIB)))
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device=None: 2048 * MIB)
+ monkeypatch.setattr(mock_invoker.services.configuration, "device_working_mem_gb", 15.0)
+
+ plan = _plan_with_cache(tmp_path, mock_invoker, GPU, CARD_16GB, _cache("cuda:0"))
+
+ assert plan.cases == []
+ assert plan.supported is False
+
+
[email protected]("device", ["mps", "xpu:0"], ids=["mps", "integrated-xpu"])
+def test_a_device_that_shares_system_memory_sizes_for_the_ram_the_host_has_available(
+ tmp_path: Path, mock_invoker: Invoker, monkeypatch: pytest.MonkeyPatch, device: str
+) -> None:
+ """32 GiB of unified memory: the host has 10 GiB available, the backend holds 2 GiB for this process, and models
+ and tensors take 3 GiB of that now. The calibration's offload moves nothing on such a device, so the lock gets 9
+ GiB, as the cache counts it, and a case may take 8 GiB beside the VAE's 1 GiB: at 2100 B/px (fp16) the largest
+ square is 1600px, at 6000 B/px (fp32) 960px. Without the live allocations taken off: 1920px and 1088px; with 90%
+ of the total, what the plan read first: 3072px and 1792px."""
+ gpu = torch.device(device)
+ shared = DeviceClass(vendor="test", name="Unified 32GB", total_mib=32 * 1024, backend=gpu.type, arch=None)
+ monkeypatch.setattr(psutil, "virtual_memory", lambda: SimpleNamespace(total=32 * GIB, available=10 * GIB))
+ monkeypatch.setattr(torch.mps, "driver_allocated_memory", lambda: 2 * GIB)
+ monkeypatch.setattr(torch.mps, "current_allocated_memory", lambda: 3 * GIB)
+ monkeypatch.setattr(torch.xpu, "memory_reserved", lambda device=None: 2 * GIB, raising=False)
+ monkeypatch.setattr(torch.xpu, "memory_allocated", lambda device=None: 3 * GIB, raising=False)
+ monkeypatch.setattr(torch.xpu, "memory_stats", lambda device=None: {}, raising=False)
+ monkeypatch.setattr(counters, "xpu_memory_info", lambda device: None)
+ monkeypatch.setattr(devices, "xpu_device_is_integrated", lambda device: True)
+ cache = _cache(device)
+
+ plan = _plan_with_cache(tmp_path, mock_invoker, gpu, shared, cache)
+
+ assert cache.calibration_capacity() == 9 * GIB
+ assert max(case.width for case in plan.cases if case.line == "decode_fp16") == 1600
+ assert max(case.width for case in plan.cases if case.line == "decode_fp32") == 960
+ # Beside each case's working memory the lock still has room for the VAE, as the cache budgets it.
+ for case in plan.cases:
+ reservation = calibration_reservation(_sd_16gb(case.estimator, case.height, case.width, case.line[7:]))
+ assert cache._get_vram_available(reservation) >= VAE_WEIGHTS_ALLOWANCE_BYTES
+
+
+def test_the_largest_size_is_capped_at_what_generate_accepts() -> None:
+ assert case_sides(lambda side: side * side, 10**15) == [2048, 2880, 4096]
+
+
+def test_a_card_that_cannot_hold_a_small_decode_with_headroom_is_unsupported() -> None:
+ small = DeviceClass(vendor="nvidia", name="Test GPU 2GB", total_mib=2048, backend="cuda", arch="sm_75")
+
+ plan = _plan(
+ _model("flux", BaseModelType.Flux), [_model("ae", BaseModelType.Flux, ModelType.VAE)], device_class=small
+ )
+
+ assert not plan.supported and "Test GPU 2GB cannot hold" in (plan.reason or "") and plan.cases == []
+
+
+def test_shared_with_lists_the_models_whose_decode_prices_with_the_same_lines() -> None:
+ """On cuDNN the SD, SD3 and FLUX.1 estimators all price with the SD3 entry's values: an SDXL calibration (fp16 and
+ fp32) moves SD1 models and an SD3 model running fp16, but not FLUX.1, which decodes in bf16."""
+ target = _model("sdxl", BaseModelType.StableDiffusionXL)
+ models = [
+ _model("sd1", BaseModelType.StableDiffusion1),
+ _model("sd3", BaseModelType.StableDiffusion3),
+ _model("sdxl-vae", BaseModelType.StableDiffusionXL, ModelType.VAE),
+ _model("sdxl-vae-cpu", BaseModelType.StableDiffusionXL, ModelType.VAE, cpu_only=True),
+ _model("flux", BaseModelType.Flux),
+ _model("lora", BaseModelType.StableDiffusionXL, ModelType.LoRA),
+ _model("wan", BaseModelType.Wan),
+ ]
+
+ plan = _plan(target, models)
+
+ assert [(shared.key, shared.lines) for shared in plan.shared_with] == [
+ ("sd1", ["decode_fp16", "decode_fp32"]),
+ ("sd3", ["decode_fp16"]),
+ ("sdxl-vae", ["decode_fp16", "decode_fp32"]),
+ ]
+
+
+def test_a_standalone_vae_is_calibrated_through_a_compatible_main_model() -> None:
+ flux_vae = _model("ae", BaseModelType.Flux, ModelType.VAE)
+ z_image = _model("z-image", BaseModelType.ZImage)
+ sdxl_vae = _model("sdxl-vae", BaseModelType.StableDiffusionXL, ModelType.VAE)
+ sdxl = _model("sdxl", BaseModelType.StableDiffusionXL)
+
+ flux_plan = _plan(flux_vae, [z_image, sdxl])
+ sd_plan = _plan(sdxl_vae, [z_image, sdxl])
+
+ # Z-Image decodes with a FLUX.1 VAE, through its `vae` slot.
+ assert (flux_plan.supported, flux_plan.calibrated_through, flux_plan.estimators) == (True, "z-image", ["vae.flux"])
+ assert {(case.model_key, tuple(case.components.items())) for case in flux_plan.cases} == {
+ ("z-image", (("vae", "ae"),))
+ }
+ # The SD bases pick a VAE through a setting a case cannot set: the main model's own VAE runs the same lines.
+ assert (sd_plan.supported, sd_plan.calibrated_through) == (True, "sdxl")
+ assert {(case.model_key, tuple(case.components.items())) for case in sd_plan.cases} == {("sdxl", ())}
+
+
+def test_a_main_model_picks_a_gpu_vae_where_generate_could_fill_in_one_on_the_cpu() -> None:
+ flux = _model("flux", BaseModelType.Flux)
+ cpu = _model("a-cpu-vae", BaseModelType.Flux, ModelType.VAE, cpu_only=True)
+ gpu = _model("b-gpu-vae", BaseModelType.Flux, ModelType.VAE, cpu_only=False)
+
+ assert {tuple(case.components.items()) for case in _plan(flux, [cpu, gpu]).cases} == {(("vae", "b-gpu-vae"),)}
+ assert {tuple(case.components.items()) for case in _plan(flux, [gpu]).cases} == {()}
+
+
+def _with_default_vae(model: SimpleNamespace, vae_key: str) -> SimpleNamespace:
+ return SimpleNamespace(**{**vars(model), "default_settings": SimpleNamespace(vae=vae_key)})
+
+
+SDXL_CPU_VAE = _model("sdxl-cpu-vae", BaseModelType.StableDiffusionXL, ModelType.VAE, cpu_only=True)
+
+
+def test_an_sd_model_whose_default_vae_runs_on_the_cpu_cannot_be_calibrated() -> None:
+ """Selecting the model applies its default VAE (`getModelDefaultVae`), and the SD graph decodes with it; an SD case
+ has no `vae` slot to pick another. A default the model does not accept is not applied, so its own VAE decodes."""
+ sdxl = _with_default_vae(_model("sdxl", BaseModelType.StableDiffusionXL), "sdxl-cpu-vae")
+ gpu_vae = _model("sdxl-gpu-vae", BaseModelType.StableDiffusionXL, ModelType.VAE)
+ sd1_cpu_vae = _model("sd1-cpu-vae", BaseModelType.StableDiffusion1, ModelType.VAE, cpu_only=True)
+
+ plan = _plan(sdxl, [SDXL_CPU_VAE, gpu_vae])
+
+ assert not plan.supported and plan.cases == []
+ assert "default VAE, SDXL-CPU-VAE, which runs on the CPU" in (plan.reason or "")
+ assert _plan(_with_default_vae(sdxl, "sdxl-gpu-vae"), [SDXL_CPU_VAE, gpu_vae]).supported
+ assert _plan(_with_default_vae(sdxl, "sd1-cpu-vae"), [sd1_cpu_vae]).supported
+
+
+def test_an_sd_vae_is_calibrated_through_a_main_model_whose_default_vae_runs_on_the_gpu() -> None:
+ sdxl_vae = _model("sdxl-vae", BaseModelType.StableDiffusionXL, ModelType.VAE)
+ on_the_cpu = _with_default_vae(_model("a-sdxl", BaseModelType.StableDiffusionXL), "sdxl-cpu-vae")
+ own_vae = _model("b-sdxl", BaseModelType.StableDiffusionXL)
+
+ plan = _plan(sdxl_vae, [on_the_cpu, own_vae, SDXL_CPU_VAE])
+ alone = _plan(sdxl_vae, [on_the_cpu, SDXL_CPU_VAE])
+
+ assert (plan.supported, plan.calibrated_through) == (True, "b-sdxl")
+ assert not alone.supported and "A-SDXL decodes with its default VAE" in (alone.reason or "")
+
+
+def test_a_model_with_a_vae_slot_picks_a_gpu_vae_over_its_default_one_on_the_cpu() -> None:
+ sd3 = _with_default_vae(_model("sd3", BaseModelType.StableDiffusion3), "a-cpu-vae")
+ cpu = _model("a-cpu-vae", BaseModelType.StableDiffusion3, ModelType.VAE, cpu_only=True)
+ gpu = _model("b-gpu-vae", BaseModelType.StableDiffusion3, ModelType.VAE)
+
+ assert {tuple(case.components.items()) for case in _plan(sd3, [cpu, gpu]).cases} == {(("vae", "b-gpu-vae"),)}
+ alone = _plan(sd3, [cpu])
+ assert not alone.supported and "no compatible VAE that runs on the GPU" in (alone.reason or "")
+
+
+ "pipeline, vae_base",
+ [
+ (_model("klein", BaseModelType.Flux2, format="diffusers"), BaseModelType.Flux2),
+ (_model("z-image", BaseModelType.ZImage, format="diffusers"), BaseModelType.Flux),
+ ],
+ ids=["flux2-diffusers", "z-image-diffusers"],
+)
+def test_a_pipeline_with_a_default_vae_decodes_with_it_in_the_standalone_vaes_dtype(pipeline, vae_base) -> None:
+ """The FLUX.2 and Z-Image model loader nodes take the `vae` setting over the pipeline's own VAE. Under `precision:
+ float32` a standalone FLUX VAE stays fp32 where both pipelines' own VAEs load in bf16; one on the CPU gives way to
+ a pick on the GPU."""
+ cpu = _model("a-cpu-vae", vae_base, ModelType.VAE, cpu_only=True)
+ gpu = _model("b-gpu-vae", vae_base, ModelType.VAE)
+
+ assert _lines_of(_plan(pipeline, [cpu, gpu], vae_dtypes=FP32_VAES)) == {("decode_bf16", ())}
+ assert _lines_of(_plan(_with_default_vae(pipeline, "b-gpu-vae"), [cpu, gpu], vae_dtypes=FP32_VAES)) == {
+ ("decode_fp32", ())
+ }
+ assert _lines_of(_plan(_with_default_vae(pipeline, "a-cpu-vae"), [cpu, gpu], vae_dtypes=FP32_VAES)) == {
+ ("decode_fp32", (("vae", "b-gpu-vae"),))
+ }
+
+
+def test_a_flux_sdnq_pipeline_decodes_with_its_own_vae_whatever_its_default_vae() -> None:
+ """Generate sends no VAE for a self-contained FLUX.1 SDNQ pipeline, its default one included: a default on the CPU
+ neither refuses the plan nor moves it to the standalone VAE's dtype."""
+ cpu = _model("a-cpu-vae", BaseModelType.Flux, ModelType.VAE, cpu_only=True)
+ sdnq = _with_default_vae(_sdnq_pipeline("flux-sdnq", BaseModelType.Flux), "a-cpu-vae")
+
+ plan = _plan(sdnq, [cpu], vae_dtypes=FP32_VAES)
+
+ assert plan.supported and _lines_of(plan) == {(f"decode_{SDNQ_PIPELINE_VAE_DTYPE}", ())}
+ assert _lines_of(_plan(sdnq, [cpu])) == {(f"decode_{SDNQ_PIPELINE_VAE_DTYPE}", ())}
+
+
+ "target, models, reason",
+ [
+ (_model("ae", BaseModelType.Flux, ModelType.VAE, cpu_only=True), [_model("f", BaseModelType.Flux)], "CPU"),
+ (
+ _model("ae", BaseModelType.Flux, ModelType.VAE),
+ [_model("s", BaseModelType.StableDiffusionXL)],
+ "no compatible",
+ ),
+ (_model("lora", BaseModelType.Flux, ModelType.LoRA), [], "this is a flux lora model"),
+ (_model("qwen", BaseModelType.QwenImage), [], "this is a qwen-image main model"),
+ (_model("refiner", BaseModelType.StableDiffusionXLRefiner), [], "plain text prompt"),
+ (_model("ideogram", BaseModelType.Ideogram4), [], "plain text prompt"),
+ (_model("fill", BaseModelType.Flux, variant=FluxVariantType.DevFill), [], "dev_fill variant"),
+ (_model("inpaint", BaseModelType.StableDiffusion1, variant=ModelVariantType.Inpaint), [], "inpaint variant"),
+ ],
+ ids=["cpu-only-vae", "vae-without-main", "lora", "uncovered-base", "refiner", "ideogram", "fill", "inpaint"],
+)
+def test_models_a_text_to_image_decode_cannot_calibrate_say_why(target, models, reason) -> None:
+ plan = _plan(target, models)
+
+ assert not plan.supported and reason in (plan.reason or "")
+ assert plan.cases == [] and plan.shared_with == [] and plan.estimated_seconds is None
+
+
+_DECODE_NODES = {
+ BaseModelType.StableDiffusion1: "latents_to_image",
+ BaseModelType.StableDiffusion2: "latents_to_image",
+ BaseModelType.StableDiffusionXL: "latents_to_image",
+ BaseModelType.StableDiffusionXLRefiner: "latents_to_image",
+ BaseModelType.StableDiffusion3: "sd3_latents_to_image",
+ BaseModelType.Flux: "flux_vae_decode",
+ BaseModelType.ZImage: "z_image_latents_to_image",
+ BaseModelType.Flux2: "flux2_vae_decode",
+ BaseModelType.Ideogram4: "ideogram4_latents_to_image",
+ BaseModelType.CogView4: "cogview4_latents_to_image",
+}
+"""The node each base's text-to-image graph decodes with (`invokeai/app/invocations/vae/`)."""
+
+
[email protected]("base", sorted(DECODE_LINES, key=str))
+def test_each_base_plans_the_estimator_its_decode_node_prices_with(base: BaseModelType) -> None:
+ """`DECODE_LINES` restates what the decode nodes do; a node that switches its estimator must fail here."""
+ assert set(DECODE_LINES) == set(_DECODE_NODES)
+ node = importlib.import_module(f"invokeai.app.invocations.vae.{_DECODE_NODES[base]}")
+ [estimate] = [
+ value
+ for name, value in vars(node).items()
+ if name.startswith("estimate_vae_working_memory_") and value is getattr(vae_working_memory, name, None)
+ ]
+ defaults = {"tile_size": None, "fp32": False, "device": GPU}
+ kwargs = {name: defaults[name] for name in inspect.signature(estimate).parameters if name in defaults}
+ vae = torch.nn.Linear(1, 1).to(torch.bfloat16)
+
+ with patch.object(vae_working_memory, "sdpa_score_matrix_bytes", return_value=0):
+ priced = estimate("decode", torch.zeros(1, 16, 64, 64), vae, **kwargs)
+
+ assert priced.estimator == DECODE_LINES[base].estimator
+
+
+def test_the_sd_decode_precisions_are_the_dtypes_the_sd_nodes_cast_to() -> None:
+ names = {torch.float16: "fp16", torch.bfloat16: "bf16", torch.float32: "fp32"}
+ cast = {names[vae_working_memory.sd_vae_run_dtype("decode", fp32, GPU)] for fp32 in (False, True)}
+ assert set(DECODE_LINES[BaseModelType.StableDiffusionXL].dtypes) == cast
+
+
+ "devices, reason",
+ [([GPU, torch.device("cuda:1")], "single generation device"), ([torch.device("cpu")], "GPU memory")],
+ ids=["two-gpus", "no-gpu"],
+)
+def test_a_machine_that_cannot_calibrate_says_why_in_the_plan(
+ tmp_path: Path, mock_invoker: Invoker, devices, reason
+) -> None:
+ flux = _model("flux", BaseModelType.Flux)
+ model_manager = MagicMock()
+ model_manager.store.get_model.return_value = flux
+ model_manager.store.all_models.return_value = [flux]
+ mock_invoker.services.model_manager = model_manager
+ service = calibration_service(tmp_path, devices=lambda: devices)
+ service.start(mock_invoker)
+ try:
+ plan = service.get_plan("flux")
+ finally:
+ service.stop(mock_invoker)
+
+ assert not plan.supported and reason in (plan.reason or "")
+ assert plan.device_class is None and plan.estimators == ["vae.flux"] and plan.cases == []
+
+
+# `force_tiled_decode` and a decode with no VAE on the GPU: runs that would measure no decode line.
+
+
+def _service_plan(tmp_path: Path, mock_invoker: Invoker, target, models=(), **config):
+ model_manager = MagicMock()
+ model_manager.store.get_model.return_value = target
+ model_manager.store.all_models.return_value = [target, *models]
+ mock_invoker.services.model_manager = model_manager
+ for name, value in config.items():
+ setattr(mock_invoker.services.configuration, name, value)
+ service = calibration_service(
+ tmp_path, untiled_decode_reservation=lambda estimator, h, w, dtype, device: 1000 * h * w
+ )
+ service.start(mock_invoker)
+ try:
+ return service.get_plan(target.key)
+ finally:
+ service.stop(mock_invoker)
+
+
+ "target, models",
+ [
+ (_model("sdxl", BaseModelType.StableDiffusionXL), []),
+ (_model("flux", BaseModelType.Flux), [_model("ae", BaseModelType.Flux, ModelType.VAE)]),
+ (_model("z-image", BaseModelType.ZImage, format="diffusers"), []),
+ (_model("klein", BaseModelType.Flux2, format="diffusers"), []),
+ (_model("ae", BaseModelType.Flux, ModelType.VAE), [_model("flux", BaseModelType.Flux)]),
+ ],
+ ids=["sdxl", "flux", "z-image", "flux2", "flux-vae"],
+)
+def test_force_tiled_decode_leaves_nothing_to_calibrate_and_says_how_to_change_that(
+ tmp_path: Path, mock_invoker: Invoker, target, models
+) -> None:
+ """With `force_tiled_decode` every generation decodes tiled, so a case measures no untiled line, and no estimate
+ would read one."""
+ plan = _service_plan(tmp_path, mock_invoker, target, models, force_tiled_decode=True)
+
+ assert not plan.supported and plan.cases == [] and plan.device_class is not None
+ assert "force_tiled_decode" in (plan.reason or "")
+
+
+ "target", [_model("sd3", BaseModelType.StableDiffusion3), _model("cogview4", BaseModelType.CogView4)]
+)
+def test_force_tiled_decode_leaves_the_decodes_that_ignore_it_calibratable(
+ tmp_path: Path, mock_invoker: Invoker, target
+) -> None:
+ assert _service_plan(tmp_path, mock_invoker, target, force_tiled_decode=True).supported
+
+
[email protected]("base", sorted(DECODE_LINES, key=str))
+def test_the_bases_force_tiled_decode_stops_are_those_whose_decode_node_reads_it(base: BaseModelType) -> None:
+ node = importlib.import_module(f"invokeai.app.invocations.vae.{_DECODE_NODES[base]}")
+ assert ("force_tiled_decode" in inspect.getsource(node)) == (base in FORCE_TILED_BASES)
+
+
+ "main, vae_base",
+ [
+ (_model("flux", BaseModelType.Flux), BaseModelType.Flux),
+ (_model("z-image-gguf", BaseModelType.ZImage, format="gguf_quantized"), BaseModelType.Flux),
+ (_model("klein-gguf", BaseModelType.Flux2, format="gguf_quantized"), BaseModelType.Flux2),
+ ],
+ ids=["flux", "z-image", "flux2"],
+)
+def test_a_model_that_needs_a_standalone_vae_and_has_none_on_the_gpu_cannot_be_calibrated(main, vae_base) -> None:
+ """The decode would run on the CPU, where no calibration window opens; without any VAE the graph cannot compile.
+ (The FLUX.2 model takes its text encoder from the standalone one.)"""
+ cpu_vae = _model("cpu-vae", vae_base, ModelType.VAE, cpu_only=True)
+
+ for models in ([cpu_vae], []):
+ plan = _plan(main, [*models, QWEN3_8B])
+ assert not plan.supported and plan.cases == [] and "GPU" in (plan.reason or "")
+ assert _plan(main, [cpu_vae, _model("gpu-vae", vae_base, ModelType.VAE), QWEN3_8B]).supported
+
+
+def test_a_pipeline_with_its_own_vae_needs_no_gpu_vae_beside_it() -> None:
+ cpu_vae = _model("cpu-vae", BaseModelType.Flux2, ModelType.VAE, cpu_only=True)
+ klein_9b = _model("klein-9b", BaseModelType.Flux2, format="diffusers", variant=Flux2VariantType.Klein9B)
+
+ assert _plan(_model("klein", BaseModelType.Flux2, format="diffusers"), [cpu_vae]).supported
+ # Nor does a FLUX.2 model decoding with its component source's VAE.
+ assert _plan(GGUF_KLEIN_9B, [cpu_vae, klein_9b]).supported
+
+
+# The pipeline VAE dtypes the plan restates, held to what their loaders yield (`own_vae_dtype`).
+
+
+def _save_tiny_vae(folder: Path, vae_class: type, dtype: torch.dtype) -> None:
+ vae = vae_class(
+ block_out_channels=(32,),
+ down_block_types=("DownEncoderBlock2D",),
+ up_block_types=("UpDecoderBlock2D",),
+ norm_num_groups=8,
+ latent_channels=4,
+ layers_per_block=1,
+ )
+ vae.to(dtype).save_pretrained(folder)
+
+
+def _dtype_of(model: torch.nn.Module) -> str:
+ return dtype_name(next(model.parameters()).dtype)
+
+
+ "loader_class, vae_class",
+ [(Flux2SDNQCheckpointModel, AutoencoderKLFlux2), (ZImageSDNQCheckpointModel, AutoencoderKL)],
+ ids=["flux2", "z-image"],
+)
+def test_an_sdnq_pipelines_own_vae_loads_in_the_dtype_the_plan_sizes_for(tmp_path: Path, loader_class, vae_class):
+ _save_tiny_vae(tmp_path / "vae", vae_class, torch.bfloat16)
+ loader = loader_class.__new__(loader_class)
+
+ vae = loader._load_vae(SimpleNamespace(path=str(tmp_path), submodels=None))
+
+ assert _dtype_of(vae) == SDNQ_PIPELINE_VAE_DTYPE
+
+
+def test_a_flux_sdnq_pipelines_plain_vae_loads_in_the_dtype_the_plan_sizes_for(tmp_path: Path):
+ _save_tiny_vae(tmp_path / "vae", AutoencoderKL, torch.bfloat16)
+ loader = FluxSDNQDiffusersModel.__new__(FluxSDNQDiffusersModel)
+
+ assert _dtype_of(loader._load_vae(tmp_path / "vae")) == SDNQ_PIPELINE_VAE_DTYPE
+
+
+def test_a_flux2_diffusers_pipelines_own_vae_loads_in_the_dtype_the_plan_sizes_for(tmp_path: Path):
+ _save_tiny_vae(tmp_path / "vae", AutoencoderKLFlux2, torch.float32)
+ (tmp_path / "model_index.json").write_text(json.dumps({"vae": ["diffusers", "AutoencoderKLFlux2"]}))
+ loader = Flux2DiffusersModel.__new__(Flux2DiffusersModel)
+ loader._apply_fp8_layerwise_casting = lambda model, config, submodel_type: model
+
+ vae = loader._load_model(SimpleNamespace(path=str(tmp_path), repo_variant=None), SubModelType.VAE)
+
+ assert _dtype_of(vae) == FLUX2_PIPELINE_VAE_DTYPE
+
+
[email protected]("precision, expected", [("float32", "fp32"), ("bfloat16", "bf16"), ("auto", "bf16")])
+def test_the_service_reads_a_standalone_flux_vaes_dtype_from_the_precision_setting(
+ monkeypatch: pytest.MonkeyPatch, precision: str, expected: str
+):
+ """On a CUDA card `auto` is fp16, which the FLUX loaders turn into bf16 where the card has it."""
+ monkeypatch.setattr(get_config(), "precision", precision)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device=None: "NVIDIA GeForce RTX 4090")
+ empty = torch.empty
+ # The bf16 probe on a card that has it; no CUDA device is needed for the answer.
+ monkeypatch.setattr(torch, "empty", lambda *args, dtype, device: empty(0, dtype=dtype))
+
+ assert _vae_dtypes(GPU, Path("models")).standalone_flux == expected
+
+
+def test_the_service_tells_an_sdnq_quantized_vae_folder_where_the_loader_looks(tmp_path: Path):
+ quantized, plain = tmp_path / "flux-sdnq" / "vae", tmp_path / "flux-sdnq-plain" / "vae"
+ quantized.mkdir(parents=True)
+ plain.mkdir(parents=True)
+ (quantized / "quantization_config.json").write_text(json.dumps({"quant_method": "sdnq"}))
+ vaes = _vae_dtypes(torch.device("cpu"), tmp_path)
+
+ assert vaes.sdnq_quantized_vae(SimpleNamespace(path="flux-sdnq", submodels=None))
+ assert not vaes.sdnq_quantized_vae(SimpleNamespace(path="flux-sdnq-plain", submodels=None))
diff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_service.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_service.py
index e5da3d2324..504d198b08 100644
--- a/tests/app/services/working_memory_calibration/test_working_memory_calibration_service.py
+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_service.py
@@ -16,6 +16,8 @@ from unittest.mock import MagicMock
import pytest
from invokeai.app.invocations.math import AddInvocation
+from invokeai.app.invocations.model import ModelIdentifierField
+from invokeai.app.invocations.sd.sdxl import SDXLModelLoaderInvocation
from invokeai.app.services.invoker import Invoker
from invokeai.app.services.model_records import UnknownModelException
from invokeai.app.services.session_queue.session_queue_common import (
@@ -31,6 +33,7 @@ from invokeai.app.services.working_memory_calibration import working_memory_cali
from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
CALIBRATION_ORIGIN_PREFIX,
CalibrationDeviceClass,
+ CalibrationModelChangedError,
CalibrationQueueFullError,
CalibrationRunNotFoundError,
CalibrationStoreError,
@@ -39,11 +42,13 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibration
WorkingMemoryCalibrationRunCreated,
WorkingMemoryCalibrationStatus,
calibration_run_id,
+ graph_model_identifiers,
)
from invokeai.app.services.working_memory_calibration.working_memory_calibration_default import (
WorkingMemoryCalibrationService,
)
from invokeai.app.services.working_memory_calibration.working_memory_calibration_store import CalibrationStore
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
from tests.fixtures.sqlite_database import sqlite_cursor
from tests.fixtures.working_memory_calibration import (
GPU_CLASS,
@@ -78,7 +83,7 @@ def _request(
graph = Graph() if graph_id is None else Graph(id=graph_id)
graph.add_node(AddInvocation(id="add", a=1, b=b))
data = [[BatchDatum(node_path="add", field_name="a", items=list(values))]] if len(values) > 1 else None
- return WorkingMemoryCalibrationRequest(graph=graph, data=data, idempotency_key=key)
+ return WorkingMemoryCalibrationRequest(graph_models={}, graph=graph, data=data, idempotency_key=key)
def _create(
@@ -721,6 +726,123 @@ def test_requests_that_differ_only_in_their_graph_id_are_one_request(
assert _calibration_item_ids(queue) == first.item_ids
+def _attempt_request(
+ attempt_id: str | None, key: str | None = "retry", attempt_steps: int | None = 1
+) -> WorkingMemoryCalibrationRequest:
+ steps = attempt_steps if attempt_id is not None else None
+ return WorkingMemoryCalibrationRequest.model_validate(
+ {**_request().model_dump(), "attempt_id": attempt_id, "attempt_steps": steps, "idempotency_key": key}
+ )
+
+
+def test_a_runs_attempt_is_stored_and_returned_and_a_run_without_one_writes_none(
+ tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue
+) -> None:
+ service = _service(tmp_path, mock_invoker)
+ with_attempt = asyncio.run(service.create_run("model-a", _attempt_request("attempt-1"), "system"))
+ without = asyncio.run(service.create_run("model-a", _attempt_request(None, None), "system"))
+
+ runs = {run["run_id"]: run for run in json.loads(_store_path(tmp_path).read_bytes())["runs"]}
+ assert (runs[with_attempt.run_id]["attempt_id"], runs[with_attempt.run_id]["attempt_steps"]) == ("attempt-1", 1)
+ # Absent rather than null: a version that forbids unknown fields still reads a run without one.
+ assert "attempt_id" not in runs[without.run_id] and "attempt_steps" not in runs[without.run_id]
+ status = {run.run_id: (run.attempt_id, run.attempt_steps) for run in service.get_status().device_classes[0].runs}
+ assert status == {with_attempt.run_id: ("attempt-1", 1), without.run_id: (None, None)}
+ summary = {run.run_id: (run.attempt_id, run.attempt_steps) for run in service.get_model_summary("model-a").runs}
+ assert summary == status
+
+
+def test_a_retry_key_names_one_run_per_attempt(tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue) -> None:
+ """The run id derives from the attempt too, so a key reused under another attempt never returns the first
+ attempt's run: the queue refuses the different batch, and the attempt's own run is discarded."""
+ service = _service(tmp_path, mock_invoker)
+
+ request = _attempt_request("a")
+ first = asyncio.run(service.create_run("model-a", request, "system"))
+ replay = asyncio.run(service.create_run("model-a", request.model_copy(deep=True), "system"))
+ with pytest.raises(EnqueueIdempotencyConflictError):
+ asyncio.run(service.create_run("model-a", _attempt_request("b"), "system"))
+
+ assert replay.run_id == first.run_id and replay.item_ids == first.item_ids
+ assert [run.run_id for run in service.get_status().device_classes[0].runs] == [first.run_id]
+ # Once the first attempt finished, the other one may start.
+ for item_id in first.item_ids:
+ queue.complete_queue_item(item_id)
+ assert asyncio.run(service.create_run("model-a", _attempt_request("b", "other-key"), "system")).run_id not in {
+ first.run_id
+ }
+
+
+def test_runs_stored_before_attempts_and_soft_facts_existed_still_load(
+ tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue
+) -> None:
+ service = _service(tmp_path, mock_invoker)
+ created = _create(service)
+ path = _store_path(tmp_path)
+ stored = json.loads(path.read_bytes())
+ assert all("attempt_id" not in run for run in stored["runs"])
+ assert [run["soft"] for run in stored["runs"]] == [stored["envs"][0]["soft"]]
+ for run in stored["runs"]:
+ del run["soft"]
+ path.write_bytes(json.dumps(stored).encode())
+
+ [run] = _service(tmp_path, mock_invoker).get_status().device_classes[0].runs
+
+ assert (run.run_id, run.attempt_id) == (created.run_id, None)
+ # Rewritten by a later change, the run stays without the field it never had.
+ service.record_windows(created.run_id, [measured_window(created.run_id)])
+ assert "soft" not in json.loads(path.read_bytes())["runs"][0]
+
+
[email protected]("attempt_id", ["", "x" * 65, "has space", "slash/no"])
+def test_an_attempt_id_outside_its_alphabet_or_length_is_rejected(attempt_id: str) -> None:
+ graph = Graph()
+ graph.add_node(AddInvocation(id="add", a=1, b=2))
+ with pytest.raises(ValueError):
+ WorkingMemoryCalibrationRequest(graph_models={}, graph=graph, attempt_id=attempt_id, attempt_steps=1)
+
+
+ ("platform", "hip", "method", "verified"),
+ [
+ ("win32", None, "windows-d3dkmt", True),
+ ("linux", None, "nvml", True),
+ ("linux", "6.4.0", "fdinfo", False),
+ ],
+)
+def test_status_and_summary_say_whether_this_gpus_measurement_is_verified(
+ tmp_path: Path,
+ mock_invoker: Invoker,
+ queue: SessionQueue,
+ monkeypatch: pytest.MonkeyPatch,
+ platform,
+ hip,
+ method,
+ verified,
+) -> None:
+ import sys
+
+ import torch
+
+ service = _service(tmp_path, mock_invoker)
+ _create(service)
+ # A file of a class no generation device here belongs to.
+ _service(tmp_path, mock_invoker, device_class=OTHER_CLASS)._store.change(
+ OTHER_CLASS.id, lambda file: (True, None), create=CalibrationDeviceClass.of(OTHER_CLASS)
+ )
+ monkeypatch.setattr(torch.version, "hip", hip)
+ monkeypatch.setattr(sys, "platform", platform)
+
+ classes = {entry.device_class_id: entry for entry in service.get_status().device_classes}
+ summary = service.get_model_summary("model-a")
+
+ current = classes[GPU_CLASS.id]
+ assert (current.measurement_method, current.measurement_verified) == (method, verified)
+ assert (classes[OTHER_CLASS.id].measurement_method, classes[OTHER_CLASS.id].measurement_verified) == (None, None)
+ assert (summary.measurement_method, summary.measurement_verified) == (method, verified)
+ assert service.get_model_summary("model-a", OTHER_CLASS.id).measurement_verified is None
+
+
def test_a_model_reset_removes_its_points_that_a_write_in_flight_brings(
tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -767,6 +889,22 @@ def test_a_model_reset_by_another_process_keeps_out_the_points_a_node_measured_b
assert [point["model_key"] for point in points] == ["vae-key", "model-a"]
+def test_a_model_reset_also_keeps_out_the_points_of_its_submodels_a_node_measured_before_it(
+ tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue
+) -> None:
+ """The reset removes the windows of `<key>:vae` with the model's (`measured_models`), so the fence drops them."""
+ service = _service(tmp_path, mock_invoker)
+ run_b = _create(service, "model-b")
+ node_start = service.model_reset_epochs(run_b.run_id)
+
+ service.reset_model("model-a")
+ windows = [measured_window(run_b.run_id, model_key="model-a:vae"), measured_window(run_b.run_id)]
+ service.record_windows(run_b.run_id, windows, node_start)
+
+ points = json.loads(_store_path(tmp_path).read_bytes())["points"]
+ assert [point["model_key"] for point in points] == ["vae-key"]
+
+
def test_a_retry_stands_in_for_its_item_before_the_runner_starts_it(
tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue
) -> None:
@@ -1160,6 +1298,20 @@ def test_repeats_in_one_process_leave_one_worker_waiting_for_the_file_lock(
assert all(repeat == first for repeat in repeats) and _calibration_item_ids(queue) == first.item_ids
+def test_an_attempts_creation_lock_never_waits_for_its_runs_creation_lock(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A creation of an attempt's run holds the attempts' lock and then its run's: whatever the run's id, the second
+ must not wait for the first. 2048 ids land on every one of the run ids' 256 lock files."""
+ monkeypatch.setattr(working_memory_calibration_store, "LOCK_TIMEOUT_S", 0.2)
+ store = CalibrationStore(tmp_path)
+
+ with store.attempts_lock():
+ for n in range(2048):
+ with store.creation_lock(f"run-{n}"):
+ pass
+
+
def test_a_model_reset_covers_its_submodels_windows(tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue) -> None:
"""A submodel's window carries its cache key (`<model>:vae`): it is the model's, both for what a reset removes and
for what a write in flight may no longer bring."""
@@ -1178,3 +1330,88 @@ def test_a_model_reset_covers_its_submodels_windows(tmp_path: Path, mock_invoker
assert removed.points_removed == 1
points = json.loads(_store_path(tmp_path).read_bytes())["points"]
assert [point["model_key"] for point in points] == ["vae-key"]
+
+
+ANIMA_LLLITE_GRAPHS = (
+ Path(__file__).parents[4]
+ / "invokeai"
+ / "frontend"
+ / "webv2"
+ / "src"
+ / "features"
+ / "generation"
+ / "core"
+ / "__snapshots__"
+ / "animaLLLiteCanvasGraphs.json"
+)
+
+
+def test_the_models_a_compiled_graph_names_are_found_where_the_client_finds_them() -> None:
+ """A graph webv2's canvas compiler wrote: the main model, its encoder and VAE in the loader's fields and again in
+ the metadata node's, and three ControlNet-LLLite adapters, beside image fields that name no model. webv2's
+ `compiledModelIdentities` test reads the same graph and expects the same keys."""
+ graph = Graph.model_validate(json.loads(ANIMA_LLLITE_GRAPHS.read_text(encoding="utf-8"))["inpaint_three_adapters"])
+
+ assert sorted({identifier.key for identifier in graph_model_identifiers(graph)}) == [
+ "anima-model",
+ "depth",
+ "pose",
+ "qwen-vae",
+ "qwen3",
+ "sketch",
+ ]
+
+
+def test_a_repeat_stating_other_identities_than_its_run_recorded_is_refused(
+ tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue, mock_sqlite_database: Database
+) -> None:
+ """The run id does not derive from graph_models. A repeat of a keyed request whose run lost its items, recompiled
+ after model-b's variant changed, names the same run and passes the check against the record; its item would fail
+ at admission on what the run recorded. It is refused at once, and a repeat stating what the run recorded is not."""
+ record = SimpleNamespace(
+ key="model-b",
+ name="Model B",
+ hash="blake3:b",
+ base=BaseModelType.StableDiffusionXL,
+ type=ModelType.Main,
+ format="diffusers",
+ variant="dev",
+ )
+ mock_invoker.services.model_manager.store.get_model.side_effect = lambda key: (
+ record if key == "model-b" else SimpleNamespace(key=key, hash=f"blake3:{key}")
+ )
+ service = _service(tmp_path, mock_invoker)
+
+ def compiled() -> WorkingMemoryCalibrationRequest:
+ named = ModelIdentifierField(
+ key="model-b", hash=record.hash, name=record.name, base=record.base, type=record.type
+ )
+ graph = Graph()
+ graph.add_node(SDXLModelLoaderInvocation(id="loader", model=named))
+ identity = {
+ "hash": record.hash,
+ "base": "sdxl",
+ "type": "main",
+ "format": record.format,
+ "variant": record.variant,
+ }
+ return WorkingMemoryCalibrationRequest(graph=graph, graph_models={"model-b": identity}, idempotency_key="lost")
+
+ first = asyncio.run(service.create_run("model-a", compiled(), "system"))
+ # Its items left the queue unseen, and the run lost them and its mark, as a store written before the mark has it.
+ queue.delete_queue_items_by_id(first.item_ids)
+ _collect_receipt(queue, mock_sqlite_database, "lost")
+ path = _store_path(tmp_path)
+ stored = json.loads(path.read_bytes())
+ stored["runs"][0].update(queue_item_ids=[], enqueue_attempted=False)
+ path.write_bytes(json.dumps(stored).encode())
+
+ record.variant = "klein_9b"
+ with pytest.raises(CalibrationModelChangedError) as refused:
+ asyncio.run(service.create_run("model-a", compiled(), "system"))
+
+ assert str(refused.value) == "Model B changed after this calibration was planned (variant). Calibrate again."
+ assert _calibration_item_ids(queue) == []
+ record.variant = "dev"
+ repeat = asyncio.run(service.create_run("model-a", compiled(), "system"))
+ assert repeat.run_id == first.run_id and _calibration_item_ids(queue) == repeat.item_ids != []
diff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_user_fits.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_user_fits.py
new file mode 100644
index 0000000000..efec58ce81
--- /dev/null
+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_user_fits.py
@@ -0,0 +1,2111 @@
+"""User fits from the calibration store: what estimates read after a session start, and the per-model summary."""
+
+import asyncio
+import builtins
+import datetime
+import json
+import os
+from collections.abc import Iterator, Mapping
+from contextlib import asynccontextmanager
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any, Optional
+from unittest.mock import MagicMock
+
+import pytest
+from pydantic import ValidationError
+
+from invokeai.app.invocations.math import AddInvocation
+from invokeai.app.invocations.metadata import CoreMetadataInvocation
+from invokeai.app.invocations.model import LoRACollectionLoader, LoRAField, ModelIdentifierField
+from invokeai.app.invocations.sd.sdxl import SDXLModelLoaderInvocation
+from invokeai.app.services.invoker import Invoker
+from invokeai.app.services.model_records import UnknownModelException
+from invokeai.app.services.session_queue.session_queue_common import Batch, BatchDatum
+from invokeai.app.services.session_queue.session_queue_default import SessionQueue
+from invokeai.app.services.shared.database.database import Database
+from invokeai.app.services.shared.database.errors import DatabaseUnavailableError
+from invokeai.app.services.shared.database.queries.session_queue import SessionQueueQueries
+from invokeai.app.services.shared.graph import Graph
+from invokeai.app.services.working_memory_calibration import (
+ working_memory_calibration_default as calibration_default,
+)
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
+ CalibrationAttemptBusyError,
+ CalibrationAttemptConflictError,
+ CalibrationAttemptInterleavedError,
+ CalibrationModelChangedError,
+ CalibrationStoreError,
+ CalibrationStoreLockTimeoutError,
+ WorkingMemoryCalibrationRequest,
+)
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_default import (
+ _ATTEMPTS_LOCK,
+ ATTEMPT_IDLE_GRACE,
+ DeviceMemory,
+ SettingValue,
+ WorkingMemoryCalibrationService,
+)
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_store import CalibrationStore
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+from invokeai.backend.util.vae_working_memory import VAE_SD_SPEC
+from invokeai.backend.working_memory.coefficients import shipped_coefficients
+from invokeai.backend.working_memory.fingerprint import DeviceClass, Environment
+from invokeai.backend.working_memory.platform import platform_for
+from invokeai.backend.working_memory.probe import CounterDelta, MeasuredWindow
+from tests.fixtures.working_memory_calibration import (
+ GPU,
+ HeldEnqueue,
+ calibration_service,
+ fake_environment,
+ measured_window,
+)
+
+MIB = 2**20
+PLATFORM = platform_for(GPU)
+
+
+def _features(side: int, **extra: object) -> dict:
+ return {
+ "operation": "decode",
+ "height": side,
+ "width": side,
+ "tile": None,
+ "dtype": "fp16",
+ "vae_class": "AutoencoderKL",
+ "upcast_weight_bytes": 0,
+ "score_matrix_bytes": 0,
+ **extra,
+ }
+
+
+def _window(run_id: str, side: int, demand: int, **update: object) -> MeasuredWindow:
+ window = measured_window(run_id, model_key="model-a:vae", estimator="vae.sd", version=VAE_SD_SPEC.version)
+ return window.model_copy(update={"features": _features(side), "demand_bytes": demand, **update})
+
+
+def _on_the_line(run_id: str, sides: tuple[int, ...] = (512, 768, 1024)) -> list[MeasuredWindow]:
+ """Windows on 900 B/px + 400 MiB, which the user line prices at 945 B/px + 420 MiB."""
+ return [_window(run_id, side, 900 * side**2 + 400 * MIB) for side in sides]
+
+
+def _user_bytes(side: int) -> int:
+ return 945 * side**2 + 420 * MIB
+
+
+def _estimate(side: int = 1024) -> int:
+ return VAE_SD_SPEC.estimate(_features(side), GPU).reservation_bytes
+
+
+def _shipped(side: int = 1024) -> int:
+ return VAE_SD_SPEC.evaluate(_features(side), shipped_coefficients(VAE_SD_SPEC, PLATFORM)).reservation_bytes
+
+
+MODELS = {
+ key: SimpleNamespace(
+ key=key, name=key.upper(), hash=None, base=BaseModelType.StableDiffusionXL, type=ModelType.Main
+ )
+ for key in ("model-a", "model-b", "model-c")
+}
+"""Installed SDXL main models: their decode prices on vae.sd's fp16 and fp32 lines."""
+
+
+def _get_model(key: str) -> SimpleNamespace:
+ if key not in MODELS:
+ raise UnknownModelException(key)
+ return MODELS[key]
+
+
+def queue(mock_invoker: Invoker, mock_sqlite_database: Database) -> SessionQueue:
+ queue = SessionQueue(mock_sqlite_database)
+ mock_invoker.services.session_queue = queue
+ model_manager = MagicMock()
+ model_manager.store.get_model.side_effect = _get_model
+ model_manager.store.all_models.return_value = list(MODELS.values())
+ mock_invoker.services.model_manager = model_manager
+ queue.start(mock_invoker)
+ return queue
+
+
+def started(mock_invoker: Invoker, queue: SessionQueue) -> Iterator:
+ """Start services on a root; each is stopped after the test, which unregisters its user-fit provider."""
+ services: list[WorkingMemoryCalibrationService] = []
+
+ def start(root: Path, **kwargs) -> WorkingMemoryCalibrationService:
+ service = calibration_service(root, **kwargs)
+ service.start(mock_invoker)
+ # The queue's retries reach the latest one, as they reach the server's.
+ mock_invoker.services.working_memory_calibration = service
+ services.append(service)
+ return service
+
+ yield start
+ for service in services:
+ service.stop(mock_invoker)
+
+
+def _create(
+ service: WorkingMemoryCalibrationService,
+ model_key: str = "model-a",
+ *,
+ running: bool = False,
+ attempt_id: str | None = None,
+ attempt_steps: int | None = None,
+) -> str:
+ """A run of `model_key`; finished (its item completed) unless `running`, so the fits take its windows."""
+ graph = Graph()
+ graph.add_node(AddInvocation(id="add", a=1, b=2))
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=graph, attempt_id=attempt_id, attempt_steps=attempt_steps
+ )
+ created = asyncio.run(service.create_run(model_key, request, "system"))
+ if not running:
+ _finish(service, created.item_ids)
+ return created.run_id
+
+
+def _finish(service: WorkingMemoryCalibrationService, item_ids: list[int]) -> None:
+ for item_id in item_ids:
+ service._services.session_queue.complete_queue_item(item_id)
+
+
+def _environment(hard: Mapping[str, str] | None = None, soft: Mapping[str, str] | None = None):
+ def environment_for(device, settings: Mapping[str, SettingValue]) -> Environment:
+ env = fake_environment(device, settings)
+ return Environment(hard={**env.hard, **(hard or {})}, soft={**env.soft, **(soft or {})})
+
+ return environment_for
+
+
+def test_estimates_read_a_calibration_from_the_next_session_start_on_and_drop_it_on_reset(
+ tmp_path: Path, started
+) -> None:
+ service = started(tmp_path)
+ run_id = _create(service)
+ service.record_windows(run_id, _on_the_line(run_id))
+
+ assert _estimate() == _shipped()
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024) and _estimate(256) == _user_bytes(256)
+
+ # A reset takes effect at once, not at the next session start.
+ service.reset_model("model-a")
+ assert _estimate() == _shipped()
+
+
+def test_a_plan_is_priced_with_the_store_as_it_is_now(tmp_path: Path, started) -> None:
+ def reservation(estimator: str, height: int, width: int, dtype: str, device) -> int:
+ return VAE_SD_SPEC.estimate(_features(height, dtype=dtype), device).reservation_bytes
+
+ def largest_fp16(service: WorkingMemoryCalibrationService) -> int:
+ return max(case.width for case in service.get_plan("model-c").cases if case.line == "decode_fp16")
+
+ service = started(tmp_path, untiled_decode_reservation=reservation)
+ shipped = largest_fp16(service)
+ run_id = _create(service)
+ # Steeper than the shipped line, so the largest size that decodes untiled shrinks.
+ service.record_windows(run_id, [_window(run_id, side, 8000 * side**2) for side in (512, 1024)])
+
+ assert largest_fp16(service) < shipped
+
+
+CARD_16GB = DeviceClass(vendor="amd", name="AMD Radeon RX 9060 XT", total_mib=16304, backend="hip", arch="gfx1200")
+# Driver and torch-reserved baselines of real windows on that card (rows 0, 9, 15 and 16 of one 18-window UI attempt):
+# what the process held outside torch grew from 722 MiB at the first decode to 2628 MiB at the last sizes.
+RX9060XT_BASELINES = [
+ (7777943552, 7021264896),
+ (7608401920, 7063207936),
+ (4718526464, 1962934272),
+ (4718526464, 1969225728),
+]
+
+
+def _baseline(value: int) -> CounterDelta:
+ return CounterDelta(baseline=value, peak=value, offset=0, delta=0)
+
+
+def test_a_fresh_servers_plan_sizes_for_the_outside_use_its_stored_windows_recorded(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A fresh server reads 300 MiB outside torch where the stored windows recorded 2755592192 bytes, so the cache can
+ give 16304 MiB less those: 14340390912 bytes, below 0.9 of the card (15386384793). A calibration lock moves every
+ other model out first, so only the VAE stays beside the decode: less 1 GiB for it, a reservation (1.5x the
+ estimate) may take 13266649088. fp16 at 2100 B/px: 2048px needs 13212057600, 2112px 14050713600. fp32 at 6000
+ B/px: 1152px needs 11943936000, 1216px 13307904000. The reading alone would have allowed 2112px and 1216px."""
+ per_pixel = {"fp16": 2100, "fp32": 6000}
+ idle = DeviceMemory(capacity_bytes=(16304 - 300) * MIB, outside_torch_bytes=300 * MIB)
+ service = started(
+ tmp_path,
+ device_class=CARD_16GB,
+ untiled_decode_reservation=lambda estimator, height, width, dtype, device: per_pixel[dtype] * height * width,
+ device_memory=lambda device: idle,
+ )
+ run_id = _create(service)
+ windows = [
+ measured_window(run_id).model_copy(update={"driver": _baseline(driver), "reserved": _baseline(reserved)})
+ for driver, reserved in RX9060XT_BASELINES
+ ]
+ # An invalid window says nothing about what a decode finds.
+ invalid = {"driver": _baseline(16 * 2**30), "valid": False, "fit_eligible": False, "reasons": ["oom"]}
+ windows.append(windows[2].model_copy(update=invalid))
+ service.record_windows(run_id, windows)
+ reads: list[str] = []
+ real_read = CalibrationStore.read
+ monkeypatch.setattr(
+ CalibrationStore, "read", lambda store, class_id: reads.append(class_id) or real_read(store, class_id)
+ )
+
+ plan = service.get_plan("model-c")
+
+ assert [(case.line, case.width) for case in plan.cases] == [
+ ("decode_fp16", 1024),
+ ("decode_fp16", 1408),
+ ("decode_fp16", 2048),
+ ("decode_fp32", 576),
+ ("decode_fp32", 768),
+ ("decode_fp32", 1152),
+ ]
+ # The plan sizes from the store its refresh read, and reads it no second time.
+ assert reads == [CARD_16GB.id]
+
+
+def test_a_first_calibration_sizes_for_the_reading_alone(tmp_path: Path, started) -> None:
+ """No stored window yet: 300 MiB outside, so 16004 MiB, above 0.9 of the card; the pretile share decides, as in
+ the sizes the RX 9060 XT ran partly resident."""
+ per_pixel = {"fp16": 2100, "fp32": 6000}
+ idle = DeviceMemory(capacity_bytes=(16304 - 300) * MIB, outside_torch_bytes=300 * MIB)
+ service = started(
+ tmp_path,
+ device_class=CARD_16GB,
+ untiled_decode_reservation=lambda estimator, height, width, dtype, device: per_pixel[dtype] * height * width,
+ device_memory=lambda device: idle,
+ )
+
+ plan = service.get_plan("model-c")
+
+ assert [case.width for case in plan.cases] == [1024, 1472, 2112, 576, 832, 1216]
+
+
+def test_an_unchanged_store_is_not_read_again_and_estimates_touch_no_file(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ service = started(tmp_path)
+ run_id = _create(service)
+ service.record_windows(run_id, _on_the_line(run_id))
+ reads: list[str] = []
+ real_read = CalibrationStore.read
+ monkeypatch.setattr(
+ CalibrationStore, "read", lambda store, class_id: reads.append(class_id) or real_read(store, class_id)
+ )
+
+ service.refresh_user_fits()
+ service.refresh_user_fits()
+ assert len(reads) == 1
+
+ def no_io(*args, **kwargs):
+ raise AssertionError("file access on the estimate path")
+
+ monkeypatch.setattr(os, "stat", no_io)
+ monkeypatch.setattr(builtins, "open", no_io)
+ monkeypatch.setattr(Path, "stat", no_io)
+ monkeypatch.setattr(CalibrationStore, "read", no_io)
+ assert [_estimate(side) for side in (512, 1024)] == [_user_bytes(512), _user_bytes(1024)]
+
+
+def test_a_hard_environment_change_falls_back_to_shipped_and_a_soft_one_keeps_the_fit(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ service = started(tmp_path)
+ run_id = _create(service)
+ service.record_windows(run_id, _on_the_line(run_id))
+ service.stop(mock_invoker)
+
+ soft = started(tmp_path, environment_for=_environment(soft={"driver": "2.0"}))
+ soft.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+ [line] = soft.get_model_summary("model-a").lines
+ assert (line.state, line.changed_facts) == ("stale", ["driver"])
+ soft.stop(mock_invoker)
+
+ hard = started(tmp_path, environment_for=_environment(hard={"torch": "2.8"}))
+ hard.refresh_user_fits()
+ assert _estimate() == _shipped()
+ [line] = hard.get_model_summary("model-a").lines
+ assert (line.state, line.changed_facts) == ("unusable", ["torch"])
+
+
+def test_the_summary_shows_per_line_what_was_measured_and_what_estimates_make_of_it(tmp_path: Path, started) -> None:
+ service = started(tmp_path)
+ run_id = _create(service)
+ windows = _on_the_line(run_id) + [
+ _window(run_id, 1024, 900 * 1024**2 + 300 * MIB),
+ _window(run_id, 1024, 9 * 10**9, valid=False, fit_eligible=False, reasons=["oom"]),
+ _window(run_id, 2048, 9 * 10**9, features=_features(2048, tile=512)),
+ ]
+ service.record_windows(run_id, windows)
+ other = _create(service, "model-b")
+ service.record_windows(other, [_window(other, 256, 900 * 256**2 + 400 * MIB, model_key="model-b:vae")])
+
+ summary = service.get_model_summary("model-a")
+
+ assert summary.excluded_windows == 2
+ assert [(run.run_id, run.status, run.point_count) for run in summary.runs] == [(run_id, "completed", 6)]
+ [line] = summary.lines
+ assert (line.estimator, line.line, line.carrier, line.state) == ("vae.sd", "decode_fp16", "vae.sd3", "in_use")
+ # The line is fitted on every model's windows of it, and shows them: model-b's 256px window widens the range.
+ assert (line.measured_range.min_pixels, line.measured_range.max_pixels) == (256**2, 1024**2) # type: ignore[union-attr]
+ assert [(size.width, size.windows, size.measured_bytes) for size in line.sizes] == [
+ (256, 1, 900 * 256**2 + 400 * MIB),
+ (512, 1, 900 * 512**2 + 400 * MIB),
+ (768, 1, 900 * 768**2 + 400 * MIB),
+ (1024, 2, 900 * 1024**2 + 400 * MIB),
+ ]
+ assert [size.shipped_bytes for size in line.sizes] == [_shipped(side) for side in (256, 512, 768, 1024)]
+ assert [size.user_bytes for size in line.sizes] == [_user_bytes(side) for side in (256, 512, 768, 1024)]
+ assert line.own_windows == 4
+ assert _measured_by(line) == [("model-a", "MODEL-A", 4), ("model-b", "MODEL-B", 1)]
+
+
+def _measured_by(line) -> list[tuple[str, str | None, int]]:
+ return [(entry.model_key, entry.name, entry.windows) for entry in line.measured_by]
+
+
+def test_a_model_never_calibrated_sees_the_line_its_decode_shares_with_another_models(tmp_path: Path, started) -> None:
+ service = started(tmp_path)
+ run_id = _create(service, "model-a")
+ service.record_windows(run_id, _on_the_line(run_id))
+
+ summary = service.get_model_summary("model-b")
+
+ assert summary.runs == [] and summary.excluded_windows == 0
+ # Only the fp16 line has windows; model-b's fp32 decode line has none and is not shown.
+ [line] = summary.lines
+ assert (line.line, line.state, line.own_windows) == ("decode_fp16", "in_use", 0)
+ assert _measured_by(line) == [("model-a", "MODEL-A", 3)]
+ assert [size.user_bytes for size in line.sizes] == [_user_bytes(side) for side in (512, 768, 1024)]
+
+
+def test_after_a_reset_a_shared_line_stays_carried_by_the_other_models_windows(tmp_path: Path, started) -> None:
+ service = started(tmp_path)
+ run_a = _create(service, "model-a")
+ service.record_windows(run_a, _on_the_line(run_a))
+ run_b = _create(service, "model-b")
+ service.record_windows(
+ run_b, [_window(run_b, side, 900 * side**2 + 400 * MIB, model_key="model-b:vae") for side in (512, 1024)]
+ )
+
+ service.reset_model("model-a")
+
+ [line] = service.get_model_summary("model-a").lines
+ assert (line.state, line.own_windows) == ("in_use", 0)
+ assert _measured_by(line) == [("model-b", "MODEL-B", 2)]
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_resetting_a_model_removes_every_window_the_summary_attributes_to_it(tmp_path: Path, started) -> None:
+ """Model A's VAE measured inside model B's run counts for A, as a submodel key (`model-a:vae`)."""
+ service = started(tmp_path)
+ run_b = _create(service, "model-b")
+ service.record_windows(run_b, _on_the_line(run_b))
+ [line] = service.get_model_summary("model-a").lines
+ assert line.own_windows == 3
+
+ removed = service.reset_model("model-a")
+
+ assert (removed.runs_removed, removed.points_removed) == (0, 3)
+ assert service.get_model_summary("model-a").lines == []
+
+
+def test_recalibrating_under_new_soft_facts_clears_stale(tmp_path: Path, started, mock_invoker: Invoker) -> None:
+ service = started(tmp_path)
+ run_id = _create(service)
+ service.record_windows(run_id, _on_the_line(run_id))
+ service.stop(mock_invoker)
+
+ updated = started(tmp_path, environment_for=_environment(soft={"driver": "2.0"}))
+ [line] = updated.get_model_summary("model-a").lines
+ assert (line.state, line.changed_facts) == ("stale", ["driver"])
+
+ rerun = _create(updated)
+ updated.record_windows(rerun, _on_the_line(rerun, sides=(512, 1024)))
+
+ [line] = updated.get_model_summary("model-a").lines
+ assert (line.state, line.changed_facts) == ("in_use", [])
+ # The older windows of the same hard environment still feed the line.
+ assert line.own_windows == 5
+
+
+def test_a_run_still_running_feeds_no_fit_until_the_queue_finishes_it(tmp_path: Path, started) -> None:
+ """Whoever refreshes meanwhile (a plan, another item, a reset): a running attempt's windows move no estimate.
+ The summary shows what the run measured so far, and the user estimates estimates really read."""
+ service = started(tmp_path)
+ graph = Graph()
+ graph.add_node(AddInvocation(id="add", a=1, b=2))
+ created = asyncio.run(
+ service.create_run("model-a", WorkingMemoryCalibrationRequest(graph_models={}, graph=graph), "system")
+ )
+ service.record_windows(created.run_id, _on_the_line(created.run_id))
+
+ service.refresh_user_fits()
+ assert _estimate() == _shipped()
+ [line] = service.get_model_summary("model-a").lines
+ assert (line.state, line.own_windows, [size.windows for size in line.sizes]) == ("insufficient", 3, [1, 1, 1])
+ assert line.measured_range is None and {size.user_bytes for size in line.sizes} == {None}
+ assert "still measuring" in (line.problem or "")
+
+ # Finished in the queue only: the file is unchanged, and the next refresh still notices.
+ _finish(service, created.item_ids)
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+ [line] = service.get_model_summary("model-a").lines
+ assert line.state == "in_use"
+
+
+def test_a_failed_run_feeds_no_fit_while_its_retry_waits_in_the_queue(tmp_path: Path, started) -> None:
+ """A retry is a new item of the run's origin, which the run's record does not name until the runner admits it:
+ queued behind other work, it must hold the failed run's windows back from the moment it is queued, and release
+ them once it is canceled."""
+ service = started(tmp_path)
+ created = asyncio.run(
+ service.create_run("model-a", WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph()), "system")
+ )
+ service.record_windows(created.run_id, _on_the_line(created.run_id))
+ queue = service._services.session_queue
+ [item_id] = created.item_ids
+ queue.fail_queue_item(item_id, "OutOfMemoryError", "out of memory", "")
+ # Failed with valid windows: the partial run feeds the fit, as every finished run does.
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+
+ [retried] = queue.retry_items_by_id("default", [item_id]).retried_items
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ [line] = service.get_model_summary("model-a").lines
+ assert line.state == "insufficient" and "still measuring" in (line.problem or "")
+
+ queue.cancel_queue_item(retried.item_id)
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_an_attempt_feeds_no_fit_until_every_run_of_it_finished_and_another_finished_attempt_does(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ service = started(tmp_path)
+ finished_attempt = _create(service, attempt_id="earlier", attempt_steps=1)
+ service.record_windows(finished_attempt, _on_the_line(finished_attempt))
+ # The running attempt measures a steeper line: were its finished first step used, estimates would move.
+ first = _create(service, attempt_id="current", attempt_steps=2)
+ service.record_windows(first, [_window(first, side, 3000 * side**2) for side in (512, 1024)])
+ second = asyncio.run(
+ service.create_run(
+ "model-a",
+ WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph(), attempt_id="current", attempt_steps=2),
+ "system",
+ )
+ )
+
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+
+ _finish(service, second.item_ids)
+ service.refresh_user_fits()
+ assert _estimate() > _user_bytes(1024)
+
+
+def _add_graph() -> Graph:
+ graph = Graph()
+ graph.add_node(AddInvocation(id="add", a=1, b=2))
+ return graph
+
+
+def test_an_attempt_stopped_before_it_queued_every_run_never_feeds_a_fit_and_the_summary_says_so(
+ tmp_path: Path, started
+) -> None:
+ """Two of three planned runs, finished, whose windows alone span enough sizes to fit a line: Stop ended the attempt
+ before its last step was queued, so it feeds nothing, then or later."""
+ service = started(tmp_path)
+ queued = [_create(service, attempt_id="stopped", attempt_steps=3) for _ in range(2)]
+ for run_id in queued:
+ service.record_windows(run_id, _on_the_line(run_id))
+
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ summary = service.get_model_summary("model-a")
+ assert {(run.run_id, run.attempt_steps, run.held_back) for run in summary.runs} == {
+ (run_id, 3, "aborted_attempt") for run_id in queued
+ }
+ [line] = summary.lines
+ assert line.state == "insufficient"
+ assert "A stopped or interrupted calibration measured this line" in (line.problem or "")
+ assert {(size.counted, size.excluded_reason) for size in line.sizes} == {(False, "aborted_attempt")}
+ assert summary.excluded_windows == 6
+
+
+def test_an_attempt_feeds_once_it_queued_every_planned_run_and_all_finished(tmp_path: Path, started) -> None:
+ service = started(tmp_path)
+ first = _create(service, attempt_id="whole", attempt_steps=2)
+ service.record_windows(first, _on_the_line(first))
+ # The first step finished before the second was posted: a prefix, which feeds nothing yet.
+ service.refresh_user_fits()
+ assert _estimate() == _shipped()
+
+ graph = _add_graph()
+ request = WorkingMemoryCalibrationRequest(graph_models={}, graph=graph, attempt_id="whole", attempt_steps=2)
+ second = asyncio.run(service.create_run("model-a", request, "system"))
+ service.refresh_user_fits()
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"running"}
+
+ _finish(service, second.item_ids)
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {None}
+
+
+def _idle(monkeypatch: pytest.MonkeyPatch, by: datetime.timedelta = ATTEMPT_IDLE_GRACE) -> None:
+ """Let the service's clock run on by `by` and a second, as if the client went away between two steps."""
+ clock = calibration_default._now
+ monkeypatch.setattr(calibration_default, "_now", lambda: clock() + by + datetime.timedelta(seconds=1))
+
+
+def _queue_attempt(service: WorkingMemoryCalibrationService, attempt_id: str, steps: int) -> list:
+ """Every run of the attempt queued, as the client posts them; the first measures the line."""
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id=attempt_id, attempt_steps=steps
+ )
+ created = [asyncio.run(service.create_run("model-a", request, "system")) for _ in range(steps)]
+ service.record_windows(created[0].run_id, _on_the_line(created[0].run_id))
+ _finish(service, created[0].item_ids)
+ return created
+
+
+def test_an_attempt_stopped_after_it_queued_every_run_never_feeds_a_fit(tmp_path: Path, started) -> None:
+ """Stop cancels the items the queue still holds: the attempt has all its runs, and still was aborted."""
+ service = started(tmp_path)
+ _, stopped = _queue_attempt(service, "stopped-late", 2)
+
+ service._services.session_queue.cancel_queue_item(stopped.item_ids[0])
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"aborted_attempt"}
+
+
+def test_a_step_stopped_after_it_measured_a_size_aborts_its_attempt(tmp_path: Path, started) -> None:
+ """Stop while a step runs: its measurement is recorded, then its item is canceled, so the run ends `partial`."""
+ service = started(tmp_path)
+ _, stopped = _queue_attempt(service, "stopped-mid-step", 2)
+ queue = service._services.session_queue
+ item = queue.get_queue_item(stopped.item_ids[0])
+ assert service.admit(item, stopped.run_id) is None
+ service.record_windows(stopped.run_id, [_window(stopped.run_id, 1536, 900 * 1536**2 + 400 * MIB)])
+ queue.cancel_queue_item(item.item_id)
+ service.observe(item, stopped.run_id)
+ service.refresh_user_fits()
+
+ summary = service.get_model_summary("model-a")
+ assert {run.status for run in summary.runs} == {"completed", "partial"}
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in summary.runs} == {"aborted_attempt"}
+
+
+def test_a_cleared_queue_aborts_the_attempt_whose_step_it_removed(tmp_path: Path, started) -> None:
+ """Clear Queue deletes the waiting step's row before the runner saw it: the queue no longer knows it."""
+ service = started(tmp_path)
+ _queue_attempt(service, "cleared", 2)
+
+ service._services.session_queue.clear("default")
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"aborted_attempt"}
+
+
+def test_an_attempt_whose_largest_step_failed_still_feeds_a_fit(tmp_path: Path, started) -> None:
+ """An out-of-memory error at the largest size ends a run, not the attempt: the finished sizes count."""
+ service = started(tmp_path)
+ _, largest = _queue_attempt(service, "oom-at-the-top", 2)
+
+ service._services.session_queue.fail_queue_item(largest.item_ids[0], "OutOfMemoryError", "out of memory", "")
+ service.refresh_user_fits()
+
+ assert _estimate() == _user_bytes(1024)
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {None}
+
+
+def test_a_canceled_run_whose_retry_completed_no_longer_aborts_its_attempt(tmp_path: Path, started) -> None:
+ """A run's outcome is that of its items' latest retries (`derive_run_status`), as the runner admitted them."""
+ service = started(tmp_path)
+ _, stopped = _queue_attempt(service, "resumed", 2)
+ queue = service._services.session_queue
+ queue.cancel_queue_item(stopped.item_ids[0])
+ service.refresh_user_fits()
+ assert _estimate() == _shipped()
+
+ [retried] = queue.retry_items_by_id("default", stopped.item_ids).retried_items
+ retry = queue.get_queue_item(retried.item_id)
+ assert service.admit(retry, stopped.run_id) is None
+ queue.complete_queue_item(retry.item_id)
+ service.observe(retry, stopped.run_id)
+ service.refresh_user_fits()
+
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_a_retry_of_a_failed_step_canceled_before_it_ran_aborts_its_attempt(tmp_path: Path, started) -> None:
+ """Out of memory at the largest size, a retry, then Stop while the retry waits: the runner never saw the retry,
+ which the store recorded as the queue committed it, and the run's status is canceled. The fit agrees."""
+ service = started(tmp_path)
+ _, largest = _queue_attempt(service, "retried-then-stopped", 2)
+ queue = service._services.session_queue
+ queue.fail_queue_item(largest.item_ids[0], "OutOfMemoryError", "out of memory", "")
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+
+ [retried] = queue.retry_items_by_id("default", largest.item_ids).retried_items
+ queue.cancel_queue_item(retried.item_id)
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ summary = service.get_model_summary("model-a")
+ assert {run.run_id: run.status for run in summary.runs}[largest.run_id] == "canceled"
+ assert {run.held_back for run in summary.runs} == {"aborted_attempt"}
+
+
+def test_a_retry_of_a_judged_failed_step_cleared_before_the_next_refresh_aborts_its_attempt(
+ tmp_path: Path, started
+) -> None:
+ """The failed step was judged (its outcome read from the queue, the attempt feeding the fit), then retried, and a
+ queue clear deleted the retry's row before anything refreshed: no read of the queue finds the retry any more. The
+ store recorded it as the queue committed it, so the attempt is aborted and its measurements leave the fit."""
+ service = started(tmp_path)
+ _, largest = _queue_attempt(service, "retried-then-cleared", 2)
+ queue = service._services.session_queue
+ queue.fail_queue_item(largest.item_ids[0], "OutOfMemoryError", "out of memory", "")
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+
+ [retried] = queue.retry_items_by_id("default", largest.item_ids).retried_items
+ queue.clear("default")
+ service.refresh_user_fits()
+
+ assert queue.get_queue_item_ids("default").item_ids == []
+ assert _estimate() == _shipped()
+ summary = service.get_model_summary("model-a")
+ assert {run.held_back for run in summary.runs} == {"aborted_attempt"}
+ sizes = {(size.counted, size.excluded_reason) for line in summary.lines for size in line.sizes}
+ assert sizes == {(False, "aborted_attempt")}
+
+
+def test_a_queue_item_id_that_now_names_another_item_is_not_taken_for_the_runs(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ """A recreated or restored database numbers its items anew while the store stays: the stopped step's id now names
+ a finished generation, which says nothing about the step."""
+ service = started(tmp_path)
+ _, stopped = _queue_attempt(service, "renumbered", 2)
+ queue = service._services.session_queue
+ queue.cancel_queue_item(stopped.item_ids[0])
+ queue.delete_queue_item(stopped.item_ids[0])
+ generation = asyncio.run(queue.enqueue_batch("default", Batch(graph=_add_graph(), origin="canvas"), prepend=False))
+ [other] = generation.item_ids
+ queue.complete_queue_item(other)
+ service.stop(mock_invoker)
+ path = next((tmp_path / "working_memory").glob("*.json"))
+ stored = json.loads(path.read_bytes())
+ [renumbered] = [run for run in stored["runs"] if run["run_id"] == stopped.run_id]
+ renumbered["queue_item_ids"] = [other]
+ path.write_text(json.dumps(stored))
+
+ started(tmp_path).refresh_user_fits()
+
+ assert _estimate() == _shipped()
+
+
+def test_a_step_with_a_failed_and_a_canceled_item_aborts_its_attempt(tmp_path: Path, started) -> None:
+ """A step whose batch data makes two items: one ran out of memory, Stop canceled the other. The run shows as
+ failed, yet its attempt was stopped."""
+ service = started(tmp_path)
+ first = _create(service, attempt_id="two-items", attempt_steps=2)
+ service.record_windows(first, _on_the_line(first))
+ data = [[BatchDatum(node_path="add", field_name="a", items=[1, 2])]]
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), data=data, attempt_id="two-items", attempt_steps=2
+ )
+ second = asyncio.run(service.create_run("model-a", request, "system"))
+ queue = service._services.session_queue
+ failed, stopped = second.item_ids
+ queue.fail_queue_item(failed, "OutOfMemoryError", "out of memory", "")
+ queue.cancel_queue_item(stopped)
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ summary = service.get_model_summary("model-a")
+ assert {run.run_id: run.status for run in summary.runs}[second.run_id] == "failed"
+ assert {run.held_back for run in summary.runs} == {"aborted_attempt"}
+
+
+def _stored(tmp_path: Path) -> dict:
+ return json.loads(next((tmp_path / "working_memory").glob("*.json")).read_bytes())
+
+
+def test_removing_a_run_of_a_complete_attempt_discards_only_its_own_measurements(tmp_path: Path, started) -> None:
+ """The attempt queued all three runs: removing one leaves the other two judged as part of a complete attempt."""
+ service = started(tmp_path)
+ _, *rest = _queue_attempt(service, "complete", 3)
+ for created in rest:
+ _finish(service, created.item_ids)
+ service.record_windows(rest[1].run_id, [_window(rest[1].run_id, 2048, 8000 * 2048**2)])
+ assert "removed_attempt_steps" not in _stored(tmp_path)
+
+ removed = service.reset_run(rest[1].run_id)
+
+ assert (removed.runs_removed, removed.points_removed) == (1, 1)
+ assert _estimate() == _user_bytes(1024)
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {None}
+ assert _stored(tmp_path)["removed_attempt_steps"] == [
+ {"user_id": "system", "attempt_id": "complete", "removed": 1, "aborted": False, "attempt_steps": 3}
+ ]
+
+
+def test_each_reset_forgets_what_the_service_kept_of_the_runs_it_removed(tmp_path: Path, started) -> None:
+ """The service keeps, for the runs it judged, which file holds each and the outcomes of their items it read from
+ the queue, retries included. Those last as long as the runs: calibrating and resetting again and again leaves
+ nothing behind."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ items: dict[str, set[int]] = {}
+ for index, model_key in enumerate(("model-a", "model-a", "model-b", "model-c")):
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id=f"attempt-{index}", attempt_steps=1
+ )
+ created = asyncio.run(service.create_run(model_key, request, "system"))
+ items[created.run_id] = set(created.item_ids)
+ if index != 1:
+ _finish(service, created.item_ids)
+ continue
+ # Out of memory, then a retry that completed: the store records the retry beside the item it retried.
+ [item] = created.item_ids
+ queue.fail_queue_item(item, "OutOfMemoryError", "out of memory", "")
+ [retried] = queue.retry_items_by_id("default", [item]).retried_items
+ queue.complete_queue_item(retried.item_id)
+ items[created.run_id].add(retried.item_id)
+ service.refresh_user_fits()
+
+ def kept() -> tuple[set[tuple[str, int]], set[str]]:
+ return set(service._item_outcomes), set(service._run_files)
+
+ def of(*ids: str) -> tuple[set[tuple[str, int]], set[str]]:
+ return {(run_id, item_id) for run_id in ids for item_id in items[run_id]}, set(ids)
+
+ first, retried_run, third, fourth = items
+ assert len(items[retried_run]) == 2 and kept() == of(*items)
+ service.reset_run(retried_run)
+ assert kept() == of(first, third, fourth)
+ service.reset_model("model-b")
+ assert kept() == of(first, fourth)
+ service.reset_all()
+ assert kept() == (set(), set())
+
+
+def test_every_judgement_of_item_outcomes_holds_the_lock_removals_hold(tmp_path: Path, started, monkeypatch) -> None:
+ """A removal drops its runs' outcomes under the fits' lock, in the same hold as its store change. Every other
+ judgement of the store's items (the summary, a new attempt's check of an attempt between its steps, a reset's hold
+ reasons) reads the queue under it too: none can write back an outcome of a run a removal just dropped, or find
+ one dropped between checking and reading it."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ settled = _create(service, attempt_id="settled", attempt_steps=1)
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id="between-steps", attempt_steps=2
+ )
+ _finish(service, asyncio.run(service.create_run("model-b", request, "other-admin")).item_ids)
+ read_by_id = queue.get_queue_item_summaries_by_ids
+ held: dict[str, list[bool]] = {}
+ phase = ""
+
+ def read_noting_the_lock(*args, **kwargs):
+ held.setdefault(phase, []).append(service._fits_lock.locked())
+ return read_by_id(*args, **kwargs)
+
+ monkeypatch.setattr(queue, "get_queue_item_summaries_by_ids", read_noting_the_lock)
+ phase = "summary"
+ service._item_outcomes.clear()
+ service.get_model_summary("model-a")
+ phase = "attempt check"
+ service._item_outcomes.clear()
+ with pytest.raises(CalibrationAttemptBusyError):
+ _create(service, attempt_id="next", attempt_steps=1)
+ phase = "reset"
+ service._item_outcomes.clear()
+ service.reset_run(settled)
+
+ assert held == {"summary": [True], "attempt check": [True], "reset": [True]}
+
+
+def _renumber(tmp_path: Path, run_id: str, item_ids: list[int]) -> None:
+ """Record `item_ids` as the run's items, as a store kept beside a recreated database that numbered them anew."""
+ path = next((tmp_path / "working_memory").glob("*.json"))
+ stored = json.loads(path.read_bytes())
+ [run] = [run for run in stored["runs"] if run["run_id"] == run_id]
+ run["queue_item_ids"] = item_ids
+ path.write_text(json.dumps(stored))
+
+
+def _off_the_line(run_id: str) -> list[MeasuredWindow]:
+ return [_window(run_id, side, 1800 * side**2 + 400 * MIB) for side in (512, 768, 1024)]
+
+
+def test_a_new_attempt_whose_item_id_an_old_run_recorded_counts_when_judged_after_the_old_run(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ """A restored database gave the new attempt's item the id an old, finished attempt recorded. The old run is judged
+ while the new one runs: its id now names another run's item, so its own item is gone. That says nothing about the
+ new run, which feeds the fit once it finished."""
+ service = started(tmp_path)
+ old = _create(service, attempt_id="old", attempt_steps=1)
+ service.record_windows(old, _off_the_line(old))
+ request = WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph(), attempt_id="new", attempt_steps=1)
+ new = asyncio.run(service.create_run("model-a", request, "system"))
+ service.stop(mock_invoker)
+ _renumber(tmp_path, old, new.item_ids)
+ service = started(tmp_path)
+
+ service.refresh_user_fits()
+ assert {run.run_id: run.held_back for run in service.get_model_summary("model-a").runs}[new.run_id] == "running"
+ service.record_windows(new.run_id, _on_the_line(new.run_id))
+ _finish(service, new.item_ids)
+ service.refresh_user_fits()
+
+ held = {run.run_id: run.held_back for run in service.get_model_summary("model-a").runs}
+ assert held == {old: "aborted_attempt", new.run_id: None}
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_an_old_run_whose_item_id_a_new_attempt_took_is_not_judged_by_the_new_item(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ """As above, with both runs settled and judged in one refresh: the old run's own item is gone (canceled), however
+ the new run's item with its id ended, so the old attempt never feeds the fit."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ old_created = asyncio.run(
+ service.create_run(
+ "model-a",
+ WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph(), attempt_id="old", attempt_steps=1),
+ "system",
+ )
+ )
+ old = old_created.run_id
+ service.record_windows(old, _off_the_line(old))
+ _finish(service, old_created.item_ids)
+ for item_id in old_created.item_ids:
+ queue.delete_queue_item(item_id)
+ new = _create(service, attempt_id="new", attempt_steps=1)
+ service.record_windows(new, _on_the_line(new))
+ service.stop(mock_invoker)
+ _renumber(tmp_path, old, _stored_run(tmp_path, new)["queue_item_ids"])
+ service = started(tmp_path)
+
+ service.refresh_user_fits()
+
+ held = {run.run_id: run.held_back for run in service.get_model_summary("model-a").runs}
+ assert held == {old: "aborted_attempt", new: None}
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_removing_a_canceled_run_keeps_its_attempt_aborted(tmp_path: Path, started) -> None:
+ service = started(tmp_path)
+ _, stopped = _queue_attempt(service, "stopped-then-removed", 2)
+ service._services.session_queue.cancel_queue_item(stopped.item_ids[0])
+
+ service.reset_run(stopped.run_id)
+
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"aborted_attempt"}
+
+
+def test_a_reset_while_an_attempt_runs_discards_the_attempt(tmp_path: Path, started) -> None:
+ """The model's runs are removed while the attempt's second step waits: the first step's measurements go with
+ the reset, and the attempt, which can no longer measure every size it planned, never feeds a fit."""
+ service = started(tmp_path)
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id="reset-while-running", attempt_steps=3
+ )
+ first = asyncio.run(service.create_run("model-a", request, "system"))
+ _finish(service, first.item_ids)
+ second = asyncio.run(service.create_run("model-a", request, "system"))
+
+ service.reset_model("model-a")
+ third = asyncio.run(service.create_run("model-a", request, "system"))
+ service.record_windows(third.run_id, _on_the_line(third.run_id))
+ _finish(service, [*second.item_ids, *third.item_ids])
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ assert [run.held_back for run in service.get_model_summary("model-a").runs] == ["aborted_attempt"]
+
+
+def test_a_finished_attempts_removal_record_is_dropped_once_none_of_its_runs_is_left(tmp_path: Path, started) -> None:
+ """Nothing is left that the record could judge, and no later step of the finished attempt will come."""
+ service = started(tmp_path)
+ for created in _queue_attempt(service, "finished", 2)[1:]:
+ _finish(service, created.item_ids)
+ service.reset_run(service.get_model_summary("model-a").runs[0].run_id)
+ assert [record["attempt_id"] for record in _stored(tmp_path)["removed_attempt_steps"]] == ["finished"]
+
+ service.reset_model("model-a")
+
+ assert "removed_attempt_steps" not in _stored(tmp_path)
+
+
[email protected]("reset", ["run", "all"])
+def test_a_later_run_of_an_attempt_a_reset_removed_while_it_ran_must_plan_the_same_steps(
+ tmp_path: Path, started, reset: str
+) -> None:
+ """The reset left no run of the attempt, yet its later steps may still come: they must plan its count."""
+ service = started(tmp_path)
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id="still-posting", attempt_steps=2
+ )
+ waiting = asyncio.run(service.create_run("model-a", request, "system"))
+
+ if reset == "run":
+ service.reset_run(waiting.run_id)
+ else:
+ service.reset_all()
+
+ assert _stored(tmp_path)["removed_attempt_steps"] == [
+ {"user_id": "system", "attempt_id": "still-posting", "removed": 1, "aborted": True, "attempt_steps": 2}
+ ]
+ other_count = request.model_copy(update={"attempt_steps": 3})
+ with pytest.raises(CalibrationAttemptConflictError):
+ asyncio.run(service.create_run("model-a", other_count, "system"))
+ asyncio.run(service.create_run("model-a", request, "system"))
+
+
+def test_a_run_whose_items_were_never_recorded_aborts_its_attempt(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ """An enqueue that raised, a lookup of its items that raised too: the run is stored with no items, and the queue
+ holds none with its origin. It measured nothing, and the attempt cannot have measured every size."""
+ service = started(tmp_path)
+ _, lost = _queue_attempt(service, "items-lost", 2)
+ service._services.session_queue.delete_queue_item(lost.item_ids[0])
+ service.stop(mock_invoker)
+ path = next((tmp_path / "working_memory").glob("*.json"))
+ stored = json.loads(path.read_bytes())
+ [run] = [run for run in stored["runs"] if run["run_id"] == lost.run_id]
+ run["queue_item_ids"] = []
+ path.write_text(json.dumps(stored))
+
+ started(tmp_path).refresh_user_fits()
+
+ assert _estimate() == _shipped()
+
+
+def test_a_retry_queued_between_the_two_queue_reads_holds_its_attempt_back(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The stopped step is retried after the read for running items and before the items are read by id: the refresh
+ judges the store it read, in which the step ended canceled, so the attempt feeds nothing; the next one finds the
+ retry running, and the attempt feeds once it completed."""
+ service = started(tmp_path)
+ _, stopped = _queue_attempt(service, "retried-between-reads", 2)
+ queue = service._services.session_queue
+ queue.cancel_queue_item(stopped.item_ids[0])
+ read_by_id = queue.get_queue_item_summaries_by_ids
+ retries: list[int] = []
+
+ def retry_then_read(*args, **kwargs):
+ if not retries:
+ retries.extend(item.item_id for item in queue.retry_items_by_id("default", stopped.item_ids).retried_items)
+ return read_by_id(*args, **kwargs)
+
+ monkeypatch.setattr(queue, "get_queue_item_summaries_by_ids", retry_then_read)
+ service.refresh_user_fits()
+
+ assert retries and _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"running"}
+
+ retry = queue.get_queue_item(retries[0])
+ assert service.admit(retry, stopped.run_id) is None
+ queue.complete_queue_item(retry.item_id)
+ service.observe(retry, stopped.run_id)
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+
+
+def _settle_as_the_runner(service: WorkingMemoryCalibrationService, run_id: str, item_ids: list[int], status: str):
+ """Run each item as the session runner would: admitted, finished in the queue, and observed."""
+ queue = service._services.session_queue
+ for item_id in item_ids:
+ item = queue.get_queue_item(item_id)
+ assert service.admit(item, run_id) is None
+ if status == "completed":
+ queue.complete_queue_item(item_id)
+ else:
+ queue.fail_queue_item(item_id, "OutOfMemoryError", "out of memory", "")
+ service.observe(item, run_id)
+
+
+def _failed_largest_step(service: WorkingMemoryCalibrationService, attempt_id: str):
+ """A two-step attempt whose first step measured the line and whose largest step ran out of memory, as the runner
+ saw them: complete, it feeds the fit."""
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id=attempt_id, attempt_steps=2
+ )
+ first, largest = (asyncio.run(service.create_run("model-a", request, "system")) for _ in range(2))
+ _settle_as_the_runner(service, first.run_id, first.item_ids, "completed")
+ service.record_windows(first.run_id, _on_the_line(first.run_id))
+ _settle_as_the_runner(service, largest.run_id, largest.item_ids, "failed")
+ return largest
+
+
+def test_a_retry_canceled_and_pruned_before_any_refresh_still_aborts_its_attempt_also_after_a_restart(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ """Out of memory at the largest size, which the runner saw; a retry; Stop; then a prune removes every finished row
+ before anything refreshed, and the server restarts. Nothing but the store knows the retry, which it recorded as the
+ queue committed it: canceled."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "retried-then-pruned")
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+
+ [retried] = queue.retry_items_by_id("default", largest.item_ids).retried_items
+ queue.cancel_queue_item(retried.item_id)
+ queue.prune("default")
+ service.stop(mock_invoker)
+ restarted = started(tmp_path)
+ restarted.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in restarted.get_model_summary("model-a").runs} == {"aborted_attempt"}
+
+
+def _stored_run(tmp_path: Path, run_id: str) -> dict:
+ [run] = [run for run in _stored(tmp_path)["runs"] if run["run_id"] == run_id]
+ return run
+
+
+def _refuse_the_record(monkeypatch: pytest.MonkeyPatch, service: WorkingMemoryCalibrationService, refusals: list):
+ """Let the store refuse the count-down of a retry's record with each error of `refusals`, one per try."""
+ change = service._store.change
+
+ def refuse_the_record(device_class_id, apply, **kwargs):
+ if refusals and getattr(apply, "func", None) is calibration_default._record_committed_retries:
+ raise refusals.pop(0)
+ return change(device_class_id, apply, **kwargs)
+
+ monkeypatch.setattr(service._store, "change", refuse_the_record)
+
+
+ "refusals",
+ [
+ [CalibrationStoreError("Cannot write the file")],
+ [CalibrationStoreLockTimeoutError("Timed out waiting for the lock")] * 2,
+ ],
+ ids=["unwritable", "lock-timed-out-twice"],
+)
+def test_a_retry_the_store_could_not_record_keeps_its_attempt_out(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, refusals: list
+) -> None:
+ """The queue committed the retry, and recording it failed (a server stopped there leaves the same store). The
+ retry is canceled and pruned unseen: no record names it, so the count left over keeps the attempt out."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "record-failed")
+ _refuse_the_record(monkeypatch, service, list(refusals))
+
+ [retried] = queue.retry_items_by_id("default", largest.item_ids).retried_items
+ queue.cancel_queue_item(retried.item_id)
+ queue.prune("default")
+ service.refresh_user_fits()
+
+ assert "Could not record the retries of calibration runs" in caplog.text
+ run = _stored_run(tmp_path, largest.run_id)
+ assert (run["retries_in_flight"], sorted(run["observed"])) == (1, [str(largest.item_ids[0])])
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"aborted_attempt"}
+
+
+def test_a_record_whose_lock_timed_out_once_is_tried_again(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Another process held the file's lock past the timeout once: a count left over for that would keep a healthy
+ attempt out for good."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "lock-timed-out-once")
+ _refuse_the_record(monkeypatch, service, [CalibrationStoreLockTimeoutError("Timed out waiting for the lock")])
+
+ [retried] = queue.retry_items_by_id("default", largest.item_ids).retried_items
+ _settle_as_the_runner(service, largest.run_id, [retried.item_id], "completed")
+ service.refresh_user_fits()
+
+ run = _stored_run(tmp_path, largest.run_id)
+ assert "retries_in_flight" not in run and str(retried.item_id) in run["observed"]
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_a_retry_the_full_queue_had_no_room_for_leaves_no_count(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "queue-full")
+ monkeypatch.setattr(service._services.configuration, "max_queue_size", 1)
+ asyncio.run(queue.enqueue_batch("default", Batch(graph=_add_graph(), origin="canvas"), prepend=False))
+
+ assert queue.retry_items_by_id("default", largest.item_ids).retried_items == []
+
+ service.refresh_user_fits()
+ assert "retries_in_flight" not in _stored_run(tmp_path, largest.run_id)
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_a_retry_that_failed_before_its_insertions_ended_rolled_back_and_leaves_no_count(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "rolled-back")
+ before = queue.get_queue_item_ids("default").item_ids
+
+ def refuse(*args, **kwargs):
+ raise OSError("disk I/O error")
+
+ insert_item = SessionQueueQueries.insert_item
+ monkeypatch.setattr(SessionQueueQueries, "insert_item", refuse)
+ with pytest.raises(OSError):
+ queue.retry_items_by_id("default", largest.item_ids)
+ monkeypatch.setattr(SessionQueueQueries, "insert_item", insert_item)
+ service.refresh_user_fits()
+
+ assert queue.get_queue_item_ids("default").item_ids == before
+ run = _stored_run(tmp_path, largest.run_id)
+ assert "retries_in_flight" not in run and sorted(run["observed"]) == [str(largest.item_ids[0])]
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_a_retry_whose_commit_failed_after_its_insertions_keeps_its_count(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ """The connection to MySQL or MariaDB is lost at the commit, which the server carried out: the retry exists, and
+ nobody can say so. It is canceled and pruned unseen; the count left over keeps the attempt out."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "commit-lost")
+ before = set(queue.get_queue_item_ids("default").item_ids)
+ run = queue._queries.run
+
+ def commit_then_lose_the_connection(work, *, read_only: bool = False):
+ result = run(work, read_only=read_only)
+ if work.__name__ == "admit":
+ raise DatabaseUnavailableError("Lost connection to server during query")
+ return result
+
+ monkeypatch.setattr(queue._queries, "run", commit_then_lose_the_connection)
+ with pytest.raises(DatabaseUnavailableError):
+ queue.retry_items_by_id("default", largest.item_ids)
+ monkeypatch.setattr(queue._queries, "run", run)
+ [retry] = set(queue.get_queue_item_ids("default").item_ids) - before
+ queue.cancel_queue_item(retry)
+ queue.prune("default")
+ service.refresh_user_fits()
+
+ assert "failed at its commit, which may have committed" in caplog.text
+ stored = _stored_run(tmp_path, largest.run_id)
+ assert (stored["retries_in_flight"], sorted(stored["observed"])) == (1, [str(largest.item_ids[0])])
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"aborted_attempt"}
+
+
+def test_a_store_that_cannot_count_a_retry_refuses_it(tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Without the count, a retry the store then failed to record could go unnoticed: the queue retries nothing."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "count-refused")
+ before = queue.get_queue_item_ids("default").item_ids
+
+ def refuse(*args, **kwargs):
+ raise CalibrationStoreError("Timed out waiting for the lock")
+
+ monkeypatch.setattr(service._store, "change", refuse)
+ with pytest.raises(CalibrationStoreError):
+ queue.retry_items_by_id("default", largest.item_ids)
+
+ assert queue.get_queue_item_ids("default").item_ids == before
+
+
+def test_a_retry_of_an_unrelated_item_that_reuses_a_recorded_id_is_not_the_runs(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ """A recreated database gave the id the run recorded to a canvas item, which fails and is retried: its row's
+ origin says it is not the run's, and its retry is not recorded."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ created = asyncio.run(
+ service.create_run("model-a", WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph()), "system")
+ )
+ [canvas] = asyncio.run(
+ queue.enqueue_batch("default", Batch(graph=_add_graph(), origin="canvas"), prepend=False)
+ ).item_ids
+ service.stop(mock_invoker)
+ path = next((tmp_path / "working_memory").glob("*.json"))
+ stored = json.loads(path.read_bytes())
+ stored["runs"][0]["queue_item_ids"] = [canvas]
+ path.write_text(json.dumps(stored))
+ service = started(tmp_path)
+ queue.fail_queue_item(canvas, "OutOfMemoryError", "out of memory", "")
+
+ assert queue.retry_items_by_id("default", [canvas]).retried_items
+
+ assert _stored(tmp_path)["runs"][0]["observed"] == {}
+ assert created.item_ids
+
+
+def test_a_retry_of_a_retry_is_recorded_on_its_run_standing_for_the_item_it_all_started_from(
+ tmp_path: Path, started
+) -> None:
+ """Out of memory at the largest size; its retry R1 is canceled, and retried as R2, which is canceled too; a prune
+ removes every row before anything refreshed. The queue links R2 to the item it all started from, and so does the
+ store."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "retried-twice")
+ [first_retry] = queue.retry_items_by_id("default", largest.item_ids).retried_items
+ queue.cancel_queue_item(first_retry.item_id)
+ [second_retry] = queue.retry_items_by_id("default", [first_retry.item_id]).retried_items
+ queue.cancel_queue_item(second_retry.item_id)
+ queue.prune("default")
+
+ service.refresh_user_fits()
+
+ [run] = [run for run in _stored(tmp_path)["runs"] if run["run_id"] == largest.run_id]
+ assert {int(key): value["retried_from_item_id"] for key, value in run["observed"].items()} == {
+ largest.item_ids[0]: None,
+ first_retry.item_id: largest.item_ids[0],
+ second_retry.item_id: largest.item_ids[0],
+ }
+ assert "retries_in_flight" not in run
+ assert _estimate() == _shipped()
+
+
+def test_each_retry_of_a_calibration_item_is_recorded_on_its_run_as_the_queue_commits_it(
+ tmp_path: Path, started
+) -> None:
+ """Items of two runs and a generation, retried in one call: each retry becomes an item of its own run, pending,
+ standing for the item it retried, and no count is left. The generation's retry leaves the store as it is."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ created = [
+ asyncio.run(
+ service.create_run(model, WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph()), "system")
+ )
+ for model in ("model-a", "model-b")
+ ]
+ [generation] = asyncio.run(
+ queue.enqueue_batch("default", Batch(graph=_add_graph(), origin="canvas"), prepend=False)
+ ).item_ids
+ item_ids = [run.item_ids[0] for run in created] + [generation]
+ for item_id in item_ids:
+ queue.fail_queue_item(item_id, "OutOfMemoryError", "out of memory", "")
+
+ retried = {
+ retry.source_item_id: retry.item_id for retry in queue.retry_items_by_id("default", item_ids).retried_items
+ }
+
+ assert len(retried) == 3
+ for run in created:
+ [item_id] = run.item_ids
+ stored = _stored_run(tmp_path, run.run_id)
+ assert "retries_in_flight" not in stored
+ assert {key: {**value, "observed_at": None} for key, value in stored["observed"].items()} == {
+ str(retried[item_id]): {
+ "status": "pending",
+ "error_message": None,
+ "retried_from_item_id": item_id,
+ "observed_at": None,
+ }
+ }
+
+
+def test_a_retry_the_runner_settled_before_it_was_recorded_keeps_what_the_runner_saw(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Out of memory at the largest size; the runner takes the retry and completes it between the queue's commit and
+ the store's record of it. The record must not turn it back into a pending item, which, once pruned, would read
+ canceled and abort the attempt."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ largest = _failed_largest_step(service, "settled-first")
+ committed = service.retries_committed
+
+ def run_it_first(in_flight, retried) -> None:
+ retried = list(retried)
+ _settle_as_the_runner(service, largest.run_id, [retry.item_id for retry in retried], "completed")
+ committed(in_flight, retried)
+
+ monkeypatch.setattr(service, "retries_committed", run_it_first)
+ queue.retry_items_by_id("default", largest.item_ids)
+ queue.prune("default")
+ service.refresh_user_fits()
+
+ assert _estimate() == _user_bytes(1024)
+
+
[email protected]("reset", ["run", "model", "all"])
+def test_a_retry_queued_as_a_reset_takes_the_files_lock_still_stops_the_attempt(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, reset: str
+) -> None:
+ """The failed step's retry is queued by the time the reset reads the queue, under the file's lock: the reset finds
+ the attempt running and stops it for good. Resetting the model is what the UI does."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ _, failed = _queue_attempt(service, "retried-while-reset", 2)
+ queue.fail_queue_item(failed.item_ids[0], "OutOfMemoryError", "out of memory", "")
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+ change = service._store.change
+ retried: list[int] = []
+
+ def retry_then_change(*args, **kwargs):
+ if not retried:
+ # Marked first: the retry's own changes of the file pass.
+ retried.append(-1)
+ retried.extend(item.item_id for item in queue.retry_items_by_id("default", failed.item_ids).retried_items)
+ return change(*args, **kwargs)
+
+ monkeypatch.setattr(service._store, "change", retry_then_change)
+ if reset == "run":
+ service.reset_run(failed.run_id)
+ elif reset == "model":
+ service.reset_model("model-a")
+ else:
+ service.reset_all()
+
+ assert retried and _estimate() == _shipped()
+ assert _stored(tmp_path).get("removed_attempt_steps") == [
+ {
+ "user_id": "system",
+ "attempt_id": "retried-while-reset",
+ "removed": 1 if reset == "run" else 2,
+ "aborted": True,
+ "attempt_steps": 2,
+ }
+ ]
+
+
+def test_two_owners_attempts_with_one_id_are_two_incomplete_attempts(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Each owner posts one of two planned steps under the same attempt id: neither attempt queued both, so neither
+ feeds a fit; and each owner's count is its own."""
+ service = started(tmp_path)
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id="shared-id", attempt_steps=2
+ )
+ for owner in ("system", "other-admin"):
+ created = asyncio.run(service.create_run("model-a", request, owner))
+ service.record_windows(created.run_id, _on_the_line(created.run_id))
+ _finish(service, created.item_ids)
+ # The other owner's attempt may start once this one went idle between its steps.
+ _idle(monkeypatch)
+
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"aborted_attempt"}
+ asyncio.run(service.create_run("model-a", request.model_copy(update={"attempt_steps": 3}), "third-admin"))
+
+
+ "change, refusal",
+ [
+ ("hash", "MODEL-A changed after this calibration was planned (hash). Calibrate again."),
+ ("base", "MODEL-A changed after this calibration was planned (base). Calibrate again."),
+ ("removed", "Model model-a was removed after this calibration was planned. Calibrate again."),
+ ("format", "MODEL-A changed after this calibration was planned (format). Calibrate again."),
+ ("variant", "MODEL-A changed after this calibration was planned (variant). Calibrate again."),
+ ],
+)
+def test_an_item_whose_model_changed_after_planning_fails_at_admission_with_its_code(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, change: str, refusal: str
+) -> None:
+ """The record changed while the calibration waited in the queue: the item would measure another model than the
+ run was planned with, so it fails before any node runs, and the run's status says why in a code."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ created = asyncio.run(
+ service.create_run("model-a", WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph()), "system")
+ )
+ if change == "removed":
+ monkeypatch.delitem(MODELS, "model-a")
+ elif change == "hash":
+ monkeypatch.setattr(MODELS["model-a"], "hash", "blake3:reinstalled")
+ elif change == "base":
+ monkeypatch.setattr(MODELS["model-a"], "base", BaseModelType.StableDiffusion1)
+ else:
+ # A model without a format or variant passes as it is (every other test); one set since does not.
+ monkeypatch.setattr(
+ MODELS["model-a"], change, "gguf_quantized" if change == "format" else "klein_9b", raising=False
+ )
+ item = queue.get_queue_item(created.item_ids[0])
+
+ assert service.admit(item, created.run_id) == refusal
+
+ # As the runner fails it, and records what the queue then holds.
+ queue.fail_queue_item(item.item_id, "WorkingMemoryCalibrationError", refusal, refusal)
+ service.observe(item, created.run_id)
+ [run] = service.get_status().device_classes[0].runs
+ assert (run.status, run.error, run.error_code) == ("failed", refusal, "model_changed")
+
+
+def test_a_model_changed_between_steps_aborts_its_attempt(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Step 1 measured the model; then it was reinstalled (a new hash) while steps 2 and 3 waited, and they fail at
+ admission. Unlike an out-of-memory failure, that interrupts the attempt: step 1's windows feed no fit."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id="reinstalled", attempt_steps=3
+ )
+ first, *later = [asyncio.run(service.create_run("model-a", request, "system")) for _ in range(3)]
+ _settle_as_the_runner(service, first.run_id, first.item_ids, "completed")
+ service.record_windows(first.run_id, _on_the_line(first.run_id))
+ monkeypatch.setattr(MODELS["model-a"], "hash", "blake3:reinstalled")
+
+ for step in later:
+ item = queue.get_queue_item(step.item_ids[0])
+ refusal = service.admit(item, step.run_id)
+ assert refusal == "MODEL-A changed after this calibration was planned (hash). Calibrate again."
+ queue.fail_queue_item(item.item_id, "WorkingMemoryCalibrationError", refusal, refusal)
+ service.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ assert {run.held_back for run in service.get_model_summary("model-a").runs} == {"aborted_attempt"}
+
+
+def test_a_later_step_that_would_measure_another_version_of_the_model_is_refused(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The client posts each step once the last one finished. The model was reinstalled in between: the next step
+ would measure another model than the first did, so it is refused, and the attempt, short of a step, never feeds."""
+ service = started(tmp_path)
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id="posted-late", attempt_steps=2
+ )
+ first = asyncio.run(service.create_run("model-a", request, "system"))
+ _settle_as_the_runner(service, first.run_id, first.item_ids, "completed")
+ service.record_windows(first.run_id, _on_the_line(first.run_id))
+ monkeypatch.setattr(MODELS["model-a"], "hash", "blake3:reinstalled")
+
+ with pytest.raises(CalibrationModelChangedError) as refused:
+ asyncio.run(service.create_run("model-a", request, "system"))
+
+ assert str(refused.value) == "MODEL-A changed after this calibration was planned (hash). Calibrate again."
+ assert _estimate() == _shipped()
+ # Another attempt of the model as it is now measures it afresh.
+ other = request.model_copy(update={"attempt_id": "afresh", "attempt_steps": 1})
+ asyncio.run(service.create_run("model-a", other, "system"))
+
+
+def _compiled_naming_model_b(field: str = "loader", **fields: Any) -> WorkingMemoryCalibrationRequest:
+ """A request whose graph names model-b as a client compiles it now, over its record: in the graph's identifier, as
+ a loader's model or as a LoRA in a collection, and in graph_models."""
+ record = MODELS["model-b"]
+ named = ModelIdentifierField(key="model-b", hash=record.hash, name="MODEL-B", base=record.base, type=record.type)
+ graph = _add_graph()
+ if field == "loader":
+ graph.add_node(SDXLModelLoaderInvocation(id="loader", model=named))
+ else:
+ graph.add_node(LoRACollectionLoader(id="loras", loras=[LoRAField(lora=named, weight=1.0)]))
+ compiled = {
+ "hash": record.hash,
+ "base": record.base.value,
+ "type": record.type.value,
+ "format": getattr(record, "format", None),
+ "variant": getattr(record, "variant", None),
+ }
+ return WorkingMemoryCalibrationRequest(graph=graph, graph_models={"model-b": compiled}, **fields)
+
+
+def _planned_model_b(monkeypatch: pytest.MonkeyPatch) -> None:
+ """model-b as installed when the client compiles: a variant, a diffusers folder."""
+ monkeypatch.setattr(MODELS["model-b"], "hash", "blake3:planned")
+ monkeypatch.setattr(MODELS["model-b"], "variant", "dev", raising=False)
+ monkeypatch.setattr(MODELS["model-b"], "format", "diffusers", raising=False)
+
+
+_CHANGED_FACTS = {
+ "hash": "blake3:reinstalled",
+ "base": BaseModelType.StableDiffusion1,
+ "type": ModelType.LoRA,
+ "format": "gguf_quantized",
+ "variant": "klein_9b",
+}
+"""What an administrator's edit or reinstall changes model-b's record to, per fact."""
+
+
[email protected]("fact", list(_CHANGED_FACTS))
+def test_a_model_that_changed_between_compiling_the_graph_and_posting_it_is_refused(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, fact: str
+) -> None:
+ """The client compiled the graph over model-b's record, which changed before the request arrived: the run would
+ measure another configuration than the one compiled, so it is refused and nothing is queued or recorded."""
+ service = started(tmp_path)
+ _planned_model_b(monkeypatch)
+ request = _compiled_naming_model_b()
+ monkeypatch.setattr(MODELS["model-b"], fact, _CHANGED_FACTS[fact])
+
+ with pytest.raises(CalibrationModelChangedError) as refused:
+ asyncio.run(service.create_run("model-a", request, "system"))
+
+ assert str(refused.value) == f"MODEL-B changed after this calibration was planned ({fact}). Calibrate again."
+ assert service._services.session_queue.get_queue_item_ids("default").item_ids == []
+ assert [run for device_class in service.get_status().device_classes for run in device_class.runs] == []
+
+
+def test_a_graph_compiled_over_the_records_as_they_are_is_accepted_and_records_what_was_compiled(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A model without a variant compiles to null, which a record that still has none matches."""
+ service = started(tmp_path)
+ monkeypatch.setattr(MODELS["model-b"], "hash", "blake3:planned")
+ monkeypatch.setattr(MODELS["model-b"], "format", "checkpoint", raising=False)
+
+ created = asyncio.run(service.create_run("model-a", _compiled_naming_model_b(), "system"))
+
+ [run] = _stored(tmp_path)["runs"]
+ assert run["run_id"] == created.run_id
+ assert run["graph_models"] == {
+ "model-b": {"hash": "blake3:planned", "base": "sdxl", "type": "main", "format": "checkpoint", "variant": None}
+ }
+
+
+def test_a_model_only_an_untyped_field_names_is_stated_and_compared(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A metadata node's extra field holds a model as a plain mapping, which a client cannot tell from a typed model
+ field in the graph's JSON: it counts as a model the graph names."""
+ service = started(tmp_path)
+ _planned_model_b(monkeypatch)
+ graph = _add_graph()
+ named = {"key": "model-b", "hash": "blake3:planned", "name": "MODEL-B", "base": "sdxl", "type": "main"}
+ graph.add_node(CoreMetadataInvocation(id="metadata", t5_encoder=named))
+ compiled = {"hash": "blake3:planned", "base": "sdxl", "type": "main", "format": "diffusers", "variant": "dev"}
+
+ with pytest.raises(ValidationError, match="the graph names model-b, which graph_models lacks"):
+ WorkingMemoryCalibrationRequest(graph=graph, graph_models={})
+ request = WorkingMemoryCalibrationRequest(graph=graph, graph_models={"model-b": compiled})
+ monkeypatch.setattr(MODELS["model-b"], "variant", "klein_9b")
+
+ with pytest.raises(CalibrationModelChangedError, match=r"\(variant\)"):
+ asyncio.run(service.create_run("model-a", request, "system"))
+
+
[email protected]("change", ["variant", "format"])
+def test_an_item_whose_component_model_changed_variant_or_format_fails_at_admission(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, change: str
+) -> None:
+ """The graph's identifiers carry no variant or format: the run recorded them for model-b as it was compiled."""
+ service = started(tmp_path)
+ _planned_model_b(monkeypatch)
+ created = asyncio.run(service.create_run("model-a", _compiled_naming_model_b(), "system"))
+ monkeypatch.setattr(MODELS["model-b"], change, _CHANGED_FACTS[change])
+ item = service._services.session_queue.get_queue_item(created.item_ids[0])
+
+ assert service.admit(item, created.run_id) == (
+ f"MODEL-B changed after this calibration was planned ({change}). Calibrate again."
+ )
+
+
+def test_a_component_recorded_without_a_hash_is_admitted_on_the_rest_of_its_identity(
+ tmp_path: Path, started, mock_invoker: Invoker, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Runs stored before graph_models recorded hashes: their items are admitted while the rest of the identity holds,
+ and refused once it changed."""
+ service = started(tmp_path)
+ _planned_model_b(monkeypatch)
+ created = asyncio.run(service.create_run("model-a", _compiled_naming_model_b(), "system"))
+ service.stop(mock_invoker)
+ path = next((tmp_path / "working_memory").glob("*.json"))
+ stored = json.loads(path.read_bytes())
+ del stored["runs"][0]["graph_models"]["model-b"]["hash"]
+ path.write_text(json.dumps(stored))
+ restarted = started(tmp_path)
+ item = restarted._services.session_queue.get_queue_item(created.item_ids[0])
+
+ assert restarted.admit(item, created.run_id) is None
+ monkeypatch.setattr(MODELS["model-b"], "variant", "klein_9b")
+ assert restarted.admit(item, created.run_id) == (
+ "MODEL-B changed after this calibration was planned (variant). Calibrate again."
+ )
+
+
+def test_a_later_step_whose_model_changed_variant_is_refused(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Step 1 measured model-a as FLUX.2 [dev]; the record now says Klein 9B: step 2 would measure another model."""
+ service = started(tmp_path)
+ monkeypatch.setattr(MODELS["model-a"], "variant", "dev", raising=False)
+ request = WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id="variant-changed", attempt_steps=2
+ )
+ first = asyncio.run(service.create_run("model-a", request, "system"))
+ _settle_as_the_runner(service, first.run_id, first.item_ids, "completed")
+ monkeypatch.setattr(MODELS["model-a"], "variant", "klein_9b")
+
+ with pytest.raises(CalibrationModelChangedError, match=r"\(variant\)"):
+ asyncio.run(service.create_run("model-a", request, "system"))
+
+
[email protected]("field", ["loader", "lora-collection"])
+def test_an_item_whose_component_model_changed_after_planning_fails_at_admission(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, field: str
+) -> None:
+ """The run calibrates model-a, and its graph loads model-b too, which was reinstalled while the item waited."""
+ service = started(tmp_path)
+ monkeypatch.setattr(MODELS["model-b"], "hash", "blake3:planned")
+ created = asyncio.run(service.create_run("model-a", _compiled_naming_model_b(field), "system"))
+ monkeypatch.setattr(MODELS["model-b"], "hash", "blake3:reinstalled")
+ queue = service._services.session_queue
+ item = queue.get_queue_item(created.item_ids[0])
+
+ refusal = service.admit(item, created.run_id)
+
+ assert refusal == "MODEL-B changed after this calibration was planned (hash). Calibrate again."
+ queue.fail_queue_item(item.item_id, "WorkingMemoryCalibrationError", refusal, refusal)
+ [run] = service.get_status().device_classes[0].runs
+ assert (run.status, run.error_code) == ("failed", "model_changed")
+
+
+def _step(service: WorkingMemoryCalibrationService, attempt_id: Optional[str], owner: str = "system"):
+ """One step of a two-step attempt (or a run without one), queued and run to completion by the runner."""
+ request = WorkingMemoryCalibrationRequest(
+ graph=_add_graph(), graph_models={}, attempt_id=attempt_id, attempt_steps=2 if attempt_id is not None else None
+ )
+ created = asyncio.run(service.create_run("model-a", request, owner))
+ _settle_as_the_runner(service, created.run_id, created.item_ids, "completed")
+ return created
+
+
+def test_a_calibration_between_two_steps_of_an_attempt_refuses_its_next_step(tmp_path: Path, started) -> None:
+ """The reviewer's sequence: A's first step finishes, another calibration (an API client's run without an attempt,
+ which no attempt blocks) runs to completion, and A's next step is refused: it would measure the GPU after that
+ calibration. A stays short and never feeds."""
+ service = started(tmp_path)
+ first = _step(service, "tab-a")
+ service.record_windows(first.run_id, _on_the_line(first.run_id))
+ _step(service, None)
+
+ with pytest.raises(CalibrationAttemptInterleavedError) as refused:
+ asyncio.run(
+ service.create_run(
+ "model-a",
+ WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id="tab-a", attempt_steps=2
+ ),
+ "system",
+ )
+ )
+
+ assert (refused.value.code, str(refused.value)) == (
+ "calibration_interleaved",
+ "Another calibration ran on this GPU after this calibration started, so its measurements can no longer be "
+ "combined. Calibrate again.",
+ )
+ service.refresh_user_fits()
+ assert _estimate() == _shipped()
+ runs = {run.run_id: run.held_back for run in service.get_model_summary("model-a").runs}
+ assert runs[first.run_id] == "aborted_attempt"
+
+
+def test_another_attempt_waits_while_one_is_between_its_steps(tmp_path: Path, started, monkeypatch) -> None:
+ """A's first step finished a moment ago, and its client is about to post the next: B, another administrator's,
+ is refused, A's next step is not, and once A finished B may start."""
+ service = started(tmp_path)
+ _step(service, "tab-a")
+
+ with pytest.raises(CalibrationAttemptBusyError):
+ _step(service, "tab-b", "other-admin")
+ _step(service, "tab-a")
+ _step(service, "tab-b", "other-admin")
+
+
+def test_an_attempt_idle_past_the_grace_blocks_nothing_and_cannot_go_on_after_another_ran(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A's client went away after its first step. Past `ATTEMPT_IDLE_GRACE` B may run; A's next step, posted after
+ all, is refused, and A never feeds."""
+ service = started(tmp_path)
+ first = _step(service, "tab-a")
+ service.record_windows(first.run_id, _on_the_line(first.run_id))
+ _idle(monkeypatch, ATTEMPT_IDLE_GRACE - datetime.timedelta(seconds=2))
+ with pytest.raises(CalibrationAttemptBusyError):
+ _step(service, "tab-b", "other-admin")
+ _idle(monkeypatch, datetime.timedelta(seconds=2))
+
+ _step(service, "tab-b", "other-admin")
+ with pytest.raises(CalibrationAttemptInterleavedError):
+ _step(service, "tab-a")
+ service.refresh_user_fits()
+ runs = {run.run_id: run.held_back for run in service.get_model_summary("model-a").runs}
+ assert runs[first.run_id] == "aborted_attempt"
+
+
+def test_the_idle_wait_counts_from_the_last_observation_not_the_run_s_creation(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A long step: created long ago, it finished a moment ago. A is open."""
+ service = started(tmp_path)
+ request = WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph(), attempt_id="tab-a", attempt_steps=2)
+ created = asyncio.run(service.create_run("model-a", request, "system"))
+ _idle(monkeypatch)
+ _settle_as_the_runner(service, created.run_id, created.item_ids, "completed")
+
+ with pytest.raises(CalibrationAttemptBusyError):
+ _step(service, "tab-b", "other-admin")
+
+
+def test_an_attempt_whose_steps_another_calibration_ran_between_never_feeds(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ """A store that holds such an attempt all the same (its later step posted past the refusal, say by a build without
+ it): complete, every step finished, and still aborted."""
+ service = started(tmp_path)
+ first, _ = _step(service, "tab-a"), _step(service, "tab-a")
+ service.record_windows(first.run_id, _on_the_line(first.run_id))
+ other = _step(service, None)
+ service.stop(mock_invoker)
+ path = next((tmp_path / "working_memory").glob("*.json"))
+ stored = json.loads(path.read_bytes())
+ start = datetime.datetime(2026, 10, 27, 12, tzinfo=datetime.timezone.utc)
+ # The plain run between the attempt's two steps.
+ for run, offset in zip(
+ sorted(stored["runs"], key=lambda run: (run["run_id"] == other.run_id, run["created_at"])),
+ (0, 10, 5),
+ strict=True,
+ ):
+ run["created_at"] = (start + datetime.timedelta(seconds=offset)).isoformat()
+ path.write_text(json.dumps(stored))
+
+ reread = started(tmp_path)
+ reread.refresh_user_fits()
+
+ assert _estimate() == _shipped()
+ held = {run.run_id: run.held_back for run in reread.get_model_summary("model-a").runs}
+ assert held[first.run_id] == "aborted_attempt"
+
+
+def test_another_attempt_started_as_the_next_step_of_one_is_posted_is_refused(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A's first step finished; A's client posts the next step as another tab starts B. A's step is held inside its
+ enqueue, recorded and not yet queued, while B reaches the attempts' lock: B is refused, A's step is queued."""
+ service = started(tmp_path)
+ _step(service, "tab-a")
+ held = HeldEnqueue(monkeypatch)
+ lock = service._file_lock
+ arrived = asyncio.Event()
+
+ @asynccontextmanager
+ async def watched(name: str, os_lock):
+ if name == _ATTEMPTS_LOCK and held.entered.is_set():
+ arrived.set()
+ async with lock(name, os_lock):
+ yield
+
+ monkeypatch.setattr(service, "_file_lock", watched)
+
+ def request(attempt_id: str) -> WorkingMemoryCalibrationRequest:
+ return WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id=attempt_id, attempt_steps=2
+ )
+
+ async def both() -> list:
+ step = asyncio.create_task(service.create_run("model-a", request("tab-a"), "system"))
+ assert await asyncio.to_thread(held.entered.wait, 10)
+ other = asyncio.create_task(service.create_run("model-a", request("tab-b"), "system"))
+ await asyncio.wait_for(arrived.wait(), 10)
+ held.release.set()
+ return await asyncio.gather(step, other, return_exceptions=True)
+
+ created, refused = asyncio.run(both())
+
+ assert isinstance(refused, CalibrationAttemptBusyError), refused
+ assert [run.attempt_id for run in service.get_status().device_classes[0].runs] == ["tab-a", "tab-a"]
+ assert created.item_ids
+
+
+def _steps(attempt_id: str, steps: int) -> WorkingMemoryCalibrationRequest:
+ return WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id=attempt_id, attempt_steps=steps
+ )
+
+
+def test_an_owners_new_attempt_replaces_its_own_attempt_that_stopped_between_steps(tmp_path: Path, started) -> None:
+ """The submission stopped after step 2 of 3 (a full queue, a lost connection): the summary shows it aborted, and
+ its owner's Retry starts a new attempt at once. The old one stays short, and a late step of it is refused."""
+ service = started(tmp_path)
+ stopped = [asyncio.run(service.create_run("model-a", _steps("first-try", 3), "system")) for _ in range(2)]
+ for created in stopped:
+ _settle_as_the_runner(service, created.run_id, created.item_ids, "completed")
+ service.record_windows(created.run_id, _on_the_line(created.run_id))
+
+ retry = asyncio.run(service.create_run("model-a", _steps("second-try", 1), "system"))
+ _settle_as_the_runner(service, retry.run_id, retry.item_ids, "completed")
+
+ with pytest.raises(CalibrationAttemptInterleavedError):
+ asyncio.run(service.create_run("model-a", _steps("first-try", 3), "system"))
+ service.refresh_user_fits()
+ held = {run.run_id: run.held_back for run in service.get_model_summary("model-a").runs}
+ assert [held[created.run_id] for created in stopped] == ["aborted_attempt", "aborted_attempt"]
+ assert held[retry.run_id] is None
+
+
+def test_another_owners_attempt_between_its_steps_is_said_to_be_between_its_steps(tmp_path: Path, started) -> None:
+ service = started(tmp_path)
+ _step(service, "tab-a")
+
+ with pytest.raises(CalibrationAttemptBusyError) as refused:
+ _step(service, "tab-b", "other-admin")
+
+ assert str(refused.value) == (
+ "Another calibration on this GPU is between its steps. Try again in a moment, or once it has finished."
+ )
+
+
+def test_an_attempt_stopped_between_its_steps_blocks_no_other_owner(tmp_path: Path, started) -> None:
+ """Stop canceled the item of step 2 of 3: the attempt is aborted, and another administrator may start at once."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ first = asyncio.run(service.create_run("model-a", _steps("stopped", 3), "system"))
+ _settle_as_the_runner(service, first.run_id, first.item_ids, "completed")
+ second = asyncio.run(service.create_run("model-a", _steps("stopped", 3), "system"))
+ queue.cancel_queue_item(second.item_ids[0])
+
+ _step(service, "tab-b", "other-admin")
+
+
+def test_an_attempt_a_reset_stopped_blocks_no_other_owner(tmp_path: Path, started) -> None:
+ """A reset removed step 2 of 3 between the steps: the attempt can no longer measure every size, so it is aborted."""
+ service = started(tmp_path)
+ for _ in range(2):
+ created = asyncio.run(service.create_run("model-a", _steps("reset", 3), "system"))
+ _settle_as_the_runner(service, created.run_id, created.item_ids, "completed")
+ service.reset_run(created.run_id)
+
+ _step(service, "tab-b", "other-admin")
+
+
+def test_an_attempt_another_run_cut_off_blocks_no_other_owner(tmp_path: Path, started) -> None:
+ """A script's run without an attempt ran after A's first step: A cannot go on, so it holds nothing open."""
+ service = started(tmp_path)
+ _step(service, "tab-a")
+ _step(service, None)
+
+ _step(service, "tab-b", "other-admin")
+
+
[email protected]("change", ["variant", "format", "hash"])
+def test_a_later_step_whose_component_model_changed_is_refused(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch, change: str
+) -> None:
+ """The graph loads model-b too, which changed between the steps. The later step compiles over the record as it is
+ now, so its creation finds the graph current, and the attempt refuses it: it would measure another version of
+ model-b than the first step did."""
+ service = started(tmp_path)
+ _planned_model_b(monkeypatch)
+ request = _compiled_naming_model_b(attempt_id="component", attempt_steps=2)
+ first = asyncio.run(service.create_run("model-a", request, "system"))
+ _settle_as_the_runner(service, first.run_id, first.item_ids, "completed")
+ monkeypatch.setattr(MODELS["model-b"], change, _CHANGED_FACTS[change])
+ later = _compiled_naming_model_b(attempt_id="component", attempt_steps=2)
+
+ with pytest.raises(CalibrationModelChangedError) as refused:
+ asyncio.run(service.create_run("model-a", later, "system"))
+
+ assert str(refused.value) == f"MODEL-B changed after this calibration was planned ({change}). Calibrate again."
+
+
+def test_a_bulk_retry_of_generations_touches_no_store_file(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A thousand failed generations retried at once: a retry carries its source's origin, no calibration's."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ asyncio.run(
+ service.create_run("model-a", WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph()), "system")
+ )
+ data = [[BatchDatum(node_path="add", field_name="a", items=list(range(1000)))]]
+ generations = asyncio.run(
+ queue.enqueue_batch("default", Batch(graph=_add_graph(), data=data, origin="canvas"), prepend=False)
+ ).item_ids
+ for generation in generations:
+ queue.fail_queue_item(generation, "OutOfMemoryError", "out of memory", "")
+ touched: list[str] = []
+ for name in ("read", "change"):
+ method = getattr(service._store, name)
+
+ def noted(device_class_id, *args, _method=method, **kwargs):
+ touched.append(device_class_id)
+ return _method(device_class_id, *args, **kwargs)
+
+ monkeypatch.setattr(service._store, name, noted)
+
+ retried = queue.retry_items_by_id("default", generations).retried_items
+
+ assert len(retried) == 1000 and touched == []
+
+
+def test_one_step_attempts_started_at_once_queue_only_the_first(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A one-step attempt held inside its enqueue is complete, and its item not queued yet: neither running nor open,
+ it would let another administrator's attempt through. Only the attempts' lock keeps that one out until the item is
+ queued, and then it is running."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ held = HeldEnqueue(monkeypatch)
+
+ async def both() -> list:
+ first = asyncio.create_task(service.create_run("model-a", _steps("tab-a", 1), "system"))
+ assert await asyncio.to_thread(held.entered.wait, 10)
+ second = asyncio.create_task(service.create_run("model-a", _steps("tab-b", 1), "other-admin"))
+ # Time for the second creation to pass the first, were nothing to hold it.
+ await asyncio.wait({second}, timeout=0.5)
+ held.release.set()
+ return await asyncio.gather(first, second, return_exceptions=True)
+
+ created, refused = asyncio.run(both())
+
+ assert isinstance(refused, CalibrationAttemptBusyError), refused
+ assert queue.get_queue_item_ids("default").item_ids == created.item_ids
+
+
+def test_two_attempts_started_at_once_queue_only_the_first(
+ tmp_path: Path, started, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Two clients start attempts together. The first is held inside its enqueue, its run recorded, its items not yet
+ queued; the second reaches the attempts' lock meanwhile and waits there. Once the first has queued its items the
+ second finds them running and is refused, and nothing of it is queued."""
+ service = started(tmp_path)
+ queue = service._services.session_queue
+ held = HeldEnqueue(monkeypatch)
+ lock = service._file_lock
+ arrived: list[asyncio.Event] = []
+
+ @asynccontextmanager
+ async def watched(name: str, os_lock):
+ if name == _ATTEMPTS_LOCK and held.entered.is_set():
+ arrived[0].set()
+ async with lock(name, os_lock):
+ yield
+
+ monkeypatch.setattr(service, "_file_lock", watched)
+
+ def request(attempt_id: str) -> WorkingMemoryCalibrationRequest:
+ return WorkingMemoryCalibrationRequest(
+ graph_models={}, graph=_add_graph(), attempt_id=attempt_id, attempt_steps=2
+ )
+
+ async def both() -> list:
+ arrived.append(asyncio.Event())
+ first = asyncio.create_task(service.create_run("model-a", request("first-tab"), "system"))
+ assert await asyncio.to_thread(held.entered.wait, 10)
+ second = asyncio.create_task(service.create_run("model-a", request("second-tab"), "system"))
+ # A ceiling, not a wait: the second creation reaches the lock at once.
+ await asyncio.wait_for(arrived[0].wait(), 10)
+ held.release.set()
+ return await asyncio.gather(first, second, return_exceptions=True)
+
+ created, refused = asyncio.run(both())
+
+ assert isinstance(refused, CalibrationAttemptBusyError), refused
+ assert queue.get_queue_item_ids("default").item_ids == created.item_ids
+ assert [run.attempt_id for run in service.get_status().device_classes[0].runs] == ["first-tab"]
+
+
+def test_a_development_builds_removal_records_read_as_each_owners(
+ tmp_path: Path, started, mock_invoker: Invoker, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Development builds kept what resets removed by attempt id alone. Such a record reads as the record of each owner
+ whose runs carry the id: each owner's attempt queued one step, lost the other to a reset, and is complete. A record
+ no stored run carries any more is dropped."""
+ service = started(tmp_path)
+ request = WorkingMemoryCalibrationRequest(graph_models={}, graph=_add_graph(), attempt_id="before", attempt_steps=2)
+ for owner in ("system", "other-admin"):
+ created = asyncio.run(service.create_run("model-a", request, owner))
+ service.record_windows(created.run_id, _on_the_line(created.run_id))
+ _finish(service, created.item_ids)
+ _idle(monkeypatch)
+ service.stop(mock_invoker)
+ path = next((tmp_path / "working_memory").glob("*.json"))
+ stored = json.loads(path.read_bytes())
+ stored["removed_attempt_steps"] = {
+ "before": {"removed": 1, "aborted": False, "attempt_steps": 2},
+ "forgotten": {"removed": 1, "aborted": True, "attempt_steps": 3},
+ }
+ path.write_text(json.dumps(stored))
+
+ reread = started(tmp_path)
+ reread.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+
+ # Any write stores them per owner; a reset of another model removes nothing of theirs.
+ reread.reset_model("model-b")
+ assert _stored(tmp_path)["removed_attempt_steps"] == [
+ {"user_id": owner, "attempt_id": "before", "removed": 1, "aborted": False, "attempt_steps": 2}
+ for owner in ("other-admin", "system")
+ ]
+
+
+def test_an_attempt_stored_before_attempt_steps_is_judged_on_the_runs_it_recorded(
+ tmp_path: Path, started, mock_invoker: Invoker
+) -> None:
+ """Only development builds stored such runs; their attempt feeds once its recorded runs finished, as it did then."""
+ service = started(tmp_path)
+ run_id = _create(service, attempt_id="before", attempt_steps=2)
+ service.record_windows(run_id, _on_the_line(run_id))
+ service.stop(mock_invoker)
+ path = next((tmp_path / "working_memory").glob("*.json"))
+ stored = json.loads(path.read_bytes())
+ del stored["runs"][0]["attempt_steps"]
+ path.write_text(json.dumps(stored))
+
+ started(tmp_path).refresh_user_fits()
+
+ assert _estimate() == _user_bytes(1024)
+
+
+def test_a_line_measured_at_one_size_is_insufficient(tmp_path: Path, started) -> None:
+ service = started(tmp_path)
+ run_id = _create(service)
+ service.record_windows(run_id, _on_the_line(run_id, sides=(1024,)))
+
+ [line] = service.get_model_summary("model-a").lines
+
+ assert line.state == "insufficient" and "measure more sizes" in (line.problem or "")
+ assert line.measured_range is None and [size.user_bytes for size in line.sizes] == [None]
+
+
+def test_a_stopped_service_no_longer_feeds_estimates(tmp_path: Path, started, mock_invoker: Invoker) -> None:
+ service = started(tmp_path)
+ run_id = _create(service)
+ service.record_windows(run_id, _on_the_line(run_id))
+ service.refresh_user_fits()
+
+ service.stop(mock_invoker)
+
+ assert _estimate() == _shipped()
diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py b/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py
index 368e0620c1..46b492ce96 100644
--- a/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py
+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py
@@ -124,3 +124,30 @@ def test_a_device_whose_vram_is_system_ram_moves_nothing(cache: ModelCache, devi
):
assert cache.offload_models_from_vram_except(set()) == 0
move.assert_not_called()
+
+
+def test_a_calibration_offload_moves_every_other_unlocked_entry_out_whole(cache: ModelCache, moved):
+ """`offload_unlocked_models_from_vram` keeps exact cache keys: the VAE being locked stays, its UNet sibling goes,
+ and each entry is asked to free all its bytes, so none is split."""
+ keys, empty_cache = moved
+ _put(cache, "sdxl:unet", 8)
+ _put(cache, "sdxl:text_encoder_2", 2)
+ _put(cache, "sdxl:vae", 1)
+ _put(cache, "controlnet", 1)
+ cache._cached_models["controlnet"].lock()
+ requested: dict[str, int] = {}
+ real_move = cache._move_model_to_ram
+
+ def record(cache_entry, vram_bytes_to_free, keep_required_weights_in_vram=None):
+ requested[cache_entry.key] = vram_bytes_to_free
+ return real_move(cache_entry, vram_bytes_to_free, keep_required_weights_in_vram)
+
+ with patch.object(cache, "_move_model_to_ram", side_effect=record):
+ freed = cache.offload_unlocked_models_from_vram(keep_cache_keys=("sdxl:vae",))
+
+ assert sorted(keys) == ["sdxl:text_encoder_2", "sdxl:unet"]
+ assert requested == {
+ key: cache._cached_models[key].cached_model.total_bytes() for key in ("sdxl:unet", "sdxl:text_encoder_2")
+ }
+ assert freed == 10 * MB and len(cache._cached_models) == 4
+ empty_cache.assert_called_once()
diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py
index da28b8c373..937954df70 100644
--- a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py
+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py
@@ -402,3 +402,45 @@ def test_lock_hands_cached_blocks_back_when_the_reserve_is_not_driver_free():
finally:
cache.unlock(record)
torch.cuda.empty_cache()
+
+
+def _calibrating_cache(device: str, cap_gb: float | None) -> ModelCache:
+ cache = ModelCache(
+ execution_device_working_mem_gb=1.0,
+ enable_partial_loading=True,
+ keep_ram_copy_of_weights=True,
+ max_vram_cache_size_gb=cap_gb,
+ reserve_vram_gb=0.5,
+ execution_device="cpu",
+ storage_device="cpu",
+ logger=MagicMock(),
+ shared_cpu_weights=None,
+ )
+ cache._execution_device = torch.device(device) # policy only; every memory query below is patched out
+ return cache
+
+
[email protected]("cap_gb", [None, 8.0], ids=["uncapped", "capped"])
+def test_a_calibration_on_a_shared_memory_device_plans_with_what_its_lock_budgets(
+ monkeypatch: pytest.MonkeyPatch, cap_gb: float | None
+):
+ """On MPS the calibration's pre-lock offload moves nothing, so what is live stays live: the capacity it plans with
+ is the lock's budget with the working memory given back. 10 GB available and 2 GB the driver holds, 3 GB live:
+ 9 GB, or 5 GB under an 8 GB cap; less the 0.5 GB reserve."""
+ monkeypatch.setattr(model_cache_module.psutil, "virtual_memory", lambda: MagicMock(available=10 * GB))
+ monkeypatch.setattr(torch.mps, "driver_allocated_memory", lambda: 2 * GB)
+ monkeypatch.setattr(torch.mps, "current_allocated_memory", lambda: 3 * GB)
+ cache = _calibrating_cache("mps", cap_gb)
+ working = 4 * GB
+
+ assert cache.calibration_capacity() == (8.5 if cap_gb is None else 4.5) * GB
+ assert cache.calibration_capacity() == cache._get_vram_available(working) + working
+
+
+def test_a_calibration_on_a_dedicated_card_counts_the_models_its_offload_moves_out(monkeypatch: pytest.MonkeyPatch):
+ """6 GB free and 2 GB the resident models hold: the offload moves them out before the lock, so 8 GB, less the
+ reserve."""
+ monkeypatch.setattr(TorchDevice, "cuda_mem_get_info", classmethod(lambda cls, device: (6 * GB, 24 * GB)))
+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device=None: 2 * GB)
+
+ assert _calibrating_cache("cuda", None).calibration_capacity() == 7.5 * GB
diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.py
index 9ee15b6346..baf571bf60 100644
--- a/tests/backend/util/test_devices.py
+++ b/tests/backend/util/test_devices.py
@@ -379,6 +379,26 @@ def test_a_backend_that_rejects_bfloat16_falls_back_by_device(monkeypatch, devic
assert TorchDevice.choose_bfloat16_safe_dtype(torch.device(device_name)) is expected
[email protected]("dtype", [torch.float32, torch.bfloat16])
+def test_the_flux_vae_dtype_keeps_a_configured_float32_or_bfloat16(dtype):
+ assert TorchDevice.dtype_avoiding_float16(dtype, torch.device("cpu")) is dtype
+
+
[email protected]("bfloat16_supported, expected", [(True, torch.bfloat16), (False, torch.float32)])
+def test_the_flux_vae_dtype_replaces_float16_with_bfloat16_or_else_float32(monkeypatch, bfloat16_supported, expected):
+ """Full width also on CUDA, unlike `choose_bfloat16_safe_dtype`: the FLUX autoencoders are broken in float16."""
+ empty = torch.empty
+
+ def answer(*args, dtype, device):
+ if not bfloat16_supported:
+ raise TypeError("BFloat16 is not supported on this device")
+ return empty(0, dtype=dtype)
+
+ monkeypatch.setattr(torch, "empty", answer)
+
+ assert TorchDevice.dtype_avoiding_float16(torch.float16, torch.device("cuda")) is expected
+
+
# ===== choose_anima_inference_dtype (config.precision honoring) ============
diff --git a/tests/backend/working_memory/test_counters.py b/tests/backend/working_memory/test_counters.py
index 1a7806b40a..5670674324 100644
--- a/tests/backend/working_memory/test_counters.py
+++ b/tests/backend/working_memory/test_counters.py
@@ -297,3 +297,22 @@ def test_on_mps_failing_getters_read_as_unknown_and_the_sampler_still_stops(monk
"torch-only",
)
assert not device_counters._sampler.running # type: ignore[union-attr]
+
+
+ ("backend", "platform", "method", "verified"),
+ [
+ ("cuda", "win32", "windows-d3dkmt", True),
+ ("hip", "win32", "windows-d3dkmt", True),
+ ("cuda", "linux", "nvml", True),
+ ("hip", "linux", "fdinfo", False),
+ ("mps", "darwin", "mps-driver", False),
+ ("xpu", "linux", "xpu-sysman", False),
+ ("cuda", "darwin", "torch-only", False),
+ ],
+)
+def test_the_driver_reader_and_its_verification_follow_backend_and_os(
+ monkeypatch: pytest.MonkeyPatch, backend: str, platform: str, method: str, verified: bool
+) -> None:
+ monkeypatch.setattr(sys, "platform", platform)
+ assert (counters.driver_method(backend), counters.method_verified(backend)) == (method, verified) # type: ignore[arg-type]
diff --git a/tests/backend/working_memory/test_fit.py b/tests/backend/working_memory/test_fit.py
index fccee01553..65160bf37f 100644
--- a/tests/backend/working_memory/test_fit.py
+++ b/tests/backend/working_memory/test_fit.py
@@ -142,6 +142,46 @@ def test_a_line_without_enough_points_names_its_entry() -> None:
fitted_values([data])
+def _probe(px: int, mib: int) -> MeasuredPoint:
+ return MeasuredPoint.model_validate(_point("lender", "decode", px, mib).model_dump() | {"method": "probe_demand"})
+
+
+ "points",
+ [
+ pytest.param([_probe(512, 500), _probe(1024, 2000)], id="probes-only"),
+ # Together they span 4x, but the one fresh size pins nothing at 512px, where a cold run's base can lie far
+ # above the warm window.
+ pytest.param([_probe(512, 500), _point("lender", "decode", 1024, 3072)], id="one-fresh-size"),
+ ],
+)
+def test_a_line_its_fresh_process_points_do_not_span_is_not_fitted(points) -> None:
+ data = WorkingMemoryData(
+ schema_version=1, coefficients=[_entry("lender", {"k_decode_bf16": 0.0, "b_decode_bf16": 0.0})], points=points
+ )
+ with pytest.raises(ValueError, match=r"decode_bf16: its fresh-process points measure .* keep it a stand-in"):
+ fitted_values([data])
+
+
+def test_a_probe_point_never_lowers_a_half_of_the_fresh_process_fit() -> None:
+ """A probe at 2048px above the hull of the fresh points at 512px and 1024px drops the 1024px vertex: rated on the
+ fresh points, the edge from 512px to the probe wins, steeper but with a lower base than the fresh fit's 1004 MiB.
+ The shipped line keeps the larger of each half."""
+ fresh = [_point("lender", "decode", 512, 1024), _point("lender", "decode", 1024, 1229)]
+ data = WorkingMemoryData(
+ schema_version=1,
+ coefficients=[_entry("lender", {"k_decode_bf16": 0.0, "b_decode_bf16": 0.0})],
+ points=[*fresh, _probe(2048, 2560)],
+ )
+ line = fitted_values([data])[("lender", 1, (("conv_backend", "cudnn"),))]
+
+ fresh_k, fresh_b = shipped_pair([(512 * 512, 1024 * MIB), (1024 * 1024, 1229 * MIB)])
+ assert fresh_b == 1004 * MIB
+ assert line["k_decode_bf16"] > fresh_k
+ assert line["b_decode_bf16"] == fresh_b
+ assert line["k_decode_bf16"] * 2048 * 2048 + line["b_decode_bf16"] >= 2560 * MIB
+
+
def test_a_declared_stand_in_line_is_not_fitted() -> None:
entry = _entry("lender", {"k_decode_bf16": 7200.0, "b_decode_bf16": 0.0}).model_copy(
update={"stand_ins": ["k_decode_bf16", "b_decode_bf16"]}
@@ -165,3 +205,41 @@ def test_only_an_estimator_keyed_by_no_platform_trait_carries_a_value_off_a_pixe
terms=lambda features, values: (),
)
assert hand_set_values(entry, spec) == exempt
+
+
+def test_points_that_cap_nothing_are_covered_but_do_not_choose_the_line() -> None:
+ """Rated on every point, the low reading at size 1 makes the edge through the origin win; rated on the capping
+ points, the flatter edge does, and it still covers the low reading."""
+ capping = [(2, 15), (4, 20)]
+ points = [*capping, (1, 4)]
+
+ assert upper_envelope(points) == (Fraction(15, 2), 0)
+ k, b = upper_envelope(points, capping)
+ assert (k, b) == (Fraction(5, 2), 10)
+ assert all(k * x + b >= y for x, y in points)
+
+
+def test_a_probe_point_raises_a_line_but_does_not_choose_it() -> None:
+ """The fresh points at 512x1024 and 1024x1024 px make the flatter edge win: 500 B/px past the first, a 1000 MiB
+ base. A probe reading of 400 MiB at 512x512 px lies below that line; rating it would make the edge through the
+ origin win, 2.04x over it instead of 3.1x."""
+ values = {"k_decode_bf16": 0.0, "b_decode_bf16": 0.0}
+ fresh = [_point("lender", "decode", 512, 1500, width=1024), _point("lender", "decode", 1024, 2000)]
+
+ def fitted(*probes: MeasuredPoint) -> tuple[int, int]:
+ data = WorkingMemoryData(schema_version=1, coefficients=[_entry("lender", values)], points=[*fresh, *probes])
+ line = fitted_values([data])[("lender", 1, (("conv_backend", "cudnn"),))]
+ return line["k_decode_bf16"], line["b_decode_bf16"]
+
+ def probe(px: int, mib: int) -> MeasuredPoint:
+ return MeasuredPoint.model_validate(
+ _point("lender", "decode", px, mib).model_dump() | {"method": "probe_demand"}
+ )
+
+ shipped = shipped_pair([(512 * 1024, 1500 * MIB), (1024 * 1024, 2000 * MIB)])
+ assert shipped[1] > 0, "the flatter edge, with a base"
+ # Below the line, at a size the fresh points do not measure, it changes nothing.
+ assert fitted(probe(512, 400)) == shipped
+ # Above the fresh points it raises the line to cover it.
+ raised = fitted(probe(1024, 5000))
+ assert raised != shipped and raised[0] * 1024 * 1024 + raised[1] >= 5000 * MIB
diff --git a/tests/backend/working_memory/test_probe.py b/tests/backend/working_memory/test_probe.py
index 8b83c0a1d0..28f7e4ad8c 100644
--- a/tests/backend/working_memory/test_probe.py
+++ b/tests/backend/working_memory/test_probe.py
@@ -168,17 +168,35 @@ class FakeCachedModel:
class FakeCache:
"""A model cache on a `FakeDevice`: a lock puts the model's weights there, through a staging buffer of
- `staging_bytes`; `partial` caps a model's residency."""
+ `staging_bytes`, after offloading the models named in `offloads`; `partial` caps a model's residency."""
def __init__(self, device: FakeDevice, staging_bytes: int = 0):
self.device = device
self.staging_bytes = staging_bytes
self.reserved: list[Optional[int]] = []
+ self.offloads: dict[str, list[CacheRecord]] = {}
self.partial: dict[str, int] = {}
+ self.records: dict[str, CacheRecord] = {}
+ self.in_use_at_lock: list[int] = []
+ """What the device had allocated when each lock began."""
self._locks: dict[str, int] = {}
+ def offload_unlocked_models_from_vram(self, keep_cache_keys=()) -> int:
+ """`ModelCache.offload_unlocked_models_from_vram`: every unlocked record but the kept ones leaves whole."""
+ freed = 0
+ for key, record in self.records.items():
+ if key not in keep_cache_keys and not self._locks.get(key) and record.cached_model.resident:
+ self.device.free(record.cached_model.resident)
+ freed += record.cached_model.resident
+ record.cached_model.resident = 0
+ return freed
+
def lock(self, record: CacheRecord, working_mem_bytes: Optional[int], max_move_bytes: Optional[int] = None) -> bool:
self.reserved.append(working_mem_bytes)
+ self.in_use_at_lock.append(self.device.allocated)
+ for victim in self.offloads.get(record.key, []):
+ self.device.free(victim.cached_model.resident)
+ victim.cached_model.resident = 0
model = record.cached_model
if model.compute_device.type != "cpu":
target = self.partial.get(record.key, model.total)
@@ -335,9 +353,9 @@ def _estimate(reservation: int = 2 * GIB) -> WorkingMemoryEstimate:
def _model(cache: FakeCache, key: str, total_bytes: int = 1 * GIB, device: str = "meta") -> LoadedModelWithoutConfig:
- return LoadedModelWithoutConfig(
- CacheRecord(key=key, cached_model=FakeCachedModel(total_bytes, device)), cache=cache
- )
+ record = CacheRecord(key=key, cached_model=FakeCachedModel(total_bytes, device))
+ cache.records[key] = record
+ return LoadedModelWithoutConfig(record, cache=cache)
def _on_another_thread(model: LoadedModelWithoutConfig) -> None:
@@ -452,6 +470,88 @@ def test_a_co_lock_counts_its_weights_as_offset_and_its_lock_outside_the_peak(de
assert window.valid
+def _resident(cache: FakeCache, key: str, total_bytes: int) -> LoadedModelWithoutConfig:
+ """A model a previous node left on the device, unlocked."""
+ model = _model(cache, key, total_bytes=total_bytes)
+ with model:
+ pass
+ return model
+
+
+def test_a_calibration_lock_moves_every_other_unlocked_model_out_first(device: FakeDevice):
+ """Left to the lock, a UNet would be split by the predicted shortfall, and a split that freed a little less than
+ predicted ran the VAE partly resident. Moved out whole first, nothing is split."""
+ cache = FakeCache(device)
+ unet = _resident(cache, "sdxl:unet", 5 * GIB)
+ text_encoder = _resident(cache, "sdxl:text_encoder_2", 1 * GIB)
+ vae = _model(cache, "sdxl:vae", total_bytes=160 * MIB)
+
+ with _scope() as scope:
+ with vae.model_on_device(working_memory=_estimate()):
+ pass
+
+ assert cache.in_use_at_lock[-1] == 0, "both moved out before the VAE's lock began"
+ assert unet._cache_record.cached_model.resident == text_encoder._cache_record.cached_model.resident == 0
+ (window,) = scope.windows
+ assert window.resident_fraction == 1.0 and window.fit_eligible
+
+
+def test_outside_a_calibration_scope_a_lock_moves_nothing_else_out(device: FakeDevice):
+ cache = FakeCache(device)
+ unet = _resident(cache, "sdxl:unet", 5 * GIB)
+ vae = _model(cache, "sdxl:vae", total_bytes=160 * MIB)
+
+ with vae.model_on_device(working_memory=_estimate()):
+ pass
+
+ assert cache.in_use_at_lock[-1] == 5 * GIB
+ assert unet._cache_record.cached_model.resident == 5 * GIB
+
+
+def test_a_model_the_window_holds_locked_stays_on_the_device_for_a_nested_calibration_lock(device: FakeDevice):
+ """A transformer whose own window is open locks a VAE for a reference image: the transformer, a co-lock of the
+ VAE's window, stays; the text encoder the node locked and released inside the window goes."""
+ cache = FakeCache(device)
+ text_encoder = _model(cache, "flux:text_encoder", total_bytes=2 * GIB)
+ transformer = _model(cache, "flux:transformer", total_bytes=4 * GIB)
+ vae = _model(cache, "flux:vae", total_bytes=160 * MIB)
+
+ with _scope() as scope:
+ with transformer.model_on_device(working_memory=_estimate(8 * GIB)):
+ with text_encoder:
+ pass
+ with vae.model_on_device(working_memory=_estimate(2 * GIB)):
+ assert cache.in_use_at_lock[-1] == 4 * GIB, "the transformer only"
+ assert text_encoder._cache_record.cached_model.resident == 0
+ assert transformer._cache_record.cached_model.resident == 4 * GIB
+
+ child, parent = scope.windows
+ assert child.co_locked_models == ["flux:transformer"] and child.valid and parent.valid
+
+
+def test_a_co_lock_that_offloads_more_than_it_loads_takes_its_offload_off_the_offset(device: FakeDevice):
+ """A text encoder locked inside the window stays resident after its unlock (+1 GiB); the adapter's co-lock then
+ moves it out to load its own 512 MiB, a co-lock offset of -512 MiB."""
+ cache = FakeCache(device)
+ text_encoder = _model(cache, "text-encoder", total_bytes=1 * GIB)
+ vae = _model(cache, "vae")
+ adapter = _model(cache, "adapter", total_bytes=512 * MIB)
+ cache.offloads["adapter"] = [text_encoder._cache_record]
+
+ with _scope() as scope:
+ with vae.model_on_device(working_memory=_estimate()):
+ with text_encoder:
+ pass
+ with adapter:
+ pass
+ device.alloc(2 * GIB)
+ device.free(2 * GIB)
+
+ (window,) = scope.windows
+ assert window.reserved is not None and window.reserved.offset == 1 * GIB - 512 * MIB
+ assert window.demand_bytes == 2 * GIB
+
+
def test_a_co_lock_that_offloads_more_than_it_loads_has_a_negative_offset(
device: FakeDevice, model_cache: CacheOnFakeDevice
):
diff --git a/tests/backend/working_memory/test_shipped_coefficients.py b/tests/backend/working_memory/test_shipped_coefficients.py
index 2c84b5aefa..14bc4806dd 100644
--- a/tests/backend/working_memory/test_shipped_coefficients.py
+++ b/tests/backend/working_memory/test_shipped_coefficients.py
@@ -3,17 +3,15 @@
Every coefficient entry resolves for the spec it names on a measured platform, or on every platform for a spec keyed by
no platform trait. Every value an entry carries is either a declared stand-in or decided by at least one in-fit point,
and on a pixel line also the shipped fit (`fit.py`) of the points it is resolved for; only an estimator keyed by no
-platform trait carries values off one. A point is a peak over the operation (see its `method` and `provenance`), and
-bounds its estimate from both sides. The model cache consumes an estimate as `free >= estimate`, so the estimate must be
-at least the point. Where a fitted term decides an in-fit point, it must also be at most 1.3 times the point, or the
-point's tighter `max_ratio`: a reservation the operation never uses is model weights evicted for nothing. The points no
-line can hold that close are listed in `UPPER_BOUND_EXCEPTIONS`. Where an analytic term (a materialized score matrix)
-decides it, that term bounds rather than describes, so it gets no upper bound, and the cache's `device_working_mem_gb`
-floor counts toward the lower one. An out-of-fit point gets the lower bound only, and `OUT_OF_FIT` lists them.
+platform trait carries values off one. Every point bounds its estimate as `working_memory/bounds.py` says: from below
+always, from above where a fitted term decides an in-fit point that holds an upper bound (a fresh-process peak, not a
+`probe_demand` window). The points no line can hold within 1.3x are listed in `bounds.UPPER_BOUND_EXCEPTIONS`; the
+out-of-fit ones in `OUT_OF_FIT`.
"""
import collections
import itertools
+import platform as stdlib_platform
import re
from dataclasses import replace
from pathlib import Path
@@ -24,9 +22,16 @@ import torch
from pydantic import ValidationError
import invokeai
-from invokeai.app.services.config.config_default import InvokeAIAppConfig
from invokeai.app.util.torch_cuda_allocator import ROCM_WINDOWS_ALLOC_CONF
+from invokeai.backend.util import nvml
from invokeai.backend.working_memory import platform as platform_module
+from invokeai.backend.working_memory.bounds import (
+ MAX_OVER_RESERVATION,
+ UPPER_BOUND_EXCEPTIONS,
+ bound_violation,
+ evaluate_point,
+ point_id,
+)
from invokeai.backend.working_memory.coefficients import (
CoefficientEntry,
MeasuredPoint,
@@ -38,31 +43,27 @@ from invokeai.backend.working_memory.coefficients import (
shipped_coefficients,
shipped_data,
)
+from invokeai.backend.working_memory.counters import backend_for
from invokeai.backend.working_memory.estimate import WorkingMemoryEstimate
-from invokeai.backend.working_memory.fit import carrier_of, entry_key, fit_points, fitted_values, hand_set_values
-from invokeai.backend.working_memory.platform import MEASURED, Platform, is_measured, platform_for, priced_as
+from invokeai.backend.working_memory.fingerprint import environment_for
+from invokeai.backend.working_memory.fit import (
+ capping_spans,
+ carrier_of,
+ entry_key,
+ fit_points,
+ fitted_values,
+ hand_set_values,
+)
+from invokeai.backend.working_memory.platform import (
+ MEASURED,
+ Platform,
+ is_measured,
+ platform_for,
+ platform_for_environment,
+ priced_as,
+)
from invokeai.backend.working_memory.spec import ESTIMATOR_MODULES, EstimatorSpec, import_estimator_modules
-MAX_OVER_RESERVATION = 1.3
-"""How far above a measured point a reservation may sit where a fitted coefficient decides it, unless the point
-carries a tighter `max_ratio`."""
-
-WORKING_MEMORY_FLOOR = int(InvokeAIAppConfig.model_fields["device_working_mem_gb"].default * 2**30)
-"""What `ModelCache._working_mem_reserve` floors every reservation at. The field default, not a config instance an
-environment variable could move."""
-
-UPPER_BOUND_EXCEPTIONS = {
- "vae.sd-miopen,native,windows-decode-fp16-1280x1280-scores-RX9060XT-demand_peak": 1.33,
- "vae.sd-miopen,native,windows-encode-fp16-1024x1024-scores-RX9060XT-demand_peak": 1.57,
- "vae.sd-miopen,native,windows-encode-fp16-1280x1280-scores-RX9060XT-demand_peak": 1.78,
- "vae.flux-miopen,native,windows-decode-bf16-512x512-scores-RX9060XT-demand_peak": 1.33,
- "vae.flux2-miopen,native,windows-decode-bf16-512x512-scores-RX9060XT-demand_peak": 1.33,
-}
-"""In-fit points whose envelope sits more than 1.3x above them, with the ratio they are held to instead. All are MIOpen
-with the native allocator on Windows, where the demand is concave in the size: first-run driver spikes at small sizes
-and a second run reserving up to 1.6x the first at large ones, so a line that covers every point cannot stay within
-1.3x of all of them. Windows ROCm defaults to expandable segments; this is the override's price."""
-
OUT_OF_FIT = {((("allocator", "native"), ("conv_backend", "cudnn")), "RTX 4090", "reserved_peak"): 6}
"""The out-of-fit points by platform, device and method: the six CUDA forced-math-kernel decodes and encodes, which
check the score-matrix term. A point that leaves the fit needs an edit here."""
@@ -83,41 +84,14 @@ def _keys(platform: Platform, spec: EstimatorSpec) -> dict[str, str]:
return {key: getattr(platform, key) for key in spec.platform_keys}
-def _platform_of(point: MeasuredPoint) -> Platform:
- """The platform a point is evaluated on. One that names no OS measured what holds on every OS. One of a spec keyed
- by no platform trait names nothing, and its one entry resolves alike on every platform, so any measured one will
- do."""
- if not SPECS[point.estimator].platform_keys:
- return MEASURED_PLATFORMS[0]
- return Platform(**({"os": "other"} | point.platform))
-
-
-def _point_id(point: MeasuredPoint) -> str:
- features = point.features
- shape = f"{features.get('height')}x{features.get('width')}"
- tile = f"-tile{features['tile']}" if features.get("tile") is not None else ""
- batch = f"-b{features['batch_size']}" if features.get("batch_size", 1) != 1 else ""
- text = f"-text{features['text_tokens']}" if "text_tokens" in features else ""
- scores = "-scores" if features.get("score_matrix_bytes") else ""
- out_of_fit = "-outfit" if not point.in_fit else ""
- card = point.device.split(" (")[0].replace(" ", "")
- head = [point.estimator, ",".join(point.platform.values())] if point.platform else [point.estimator]
- head += [str(features[key]) for key in ("operation", "dtype") if key in features]
- return f"{'-'.join(head)}-{shape}{tile}{batch}{text}{scores}{out_of_fit}-{card}-{point.method}"
-
-
def _evaluate(point: MeasuredPoint) -> WorkingMemoryEstimate:
spec = SPECS[point.estimator]
assert point.version == spec.version
- return spec.evaluate(point.features, shipped_coefficients(spec, _platform_of(point)))
-
-
-def _fitted_decides(estimate: WorkingMemoryEstimate) -> bool:
- return any(term.included and term.coefficient is not None for term in estimate.terms)
+ return evaluate_point(point, spec, shipped_data().values())
ALL_POINTS = [point for data in shipped_data().values() for point in data.points]
-POINTS = [pytest.param(point, id=_point_id(point)) for point in ALL_POINTS]
+POINTS = [pytest.param(point, id=point_id(point)) for point in ALL_POINTS]
ENTRIES = [entry for data in shipped_data().values() for entry in data.coefficients]
@@ -224,14 +198,15 @@ def test_every_fitted_value_is_the_shipped_fit_of_its_points() -> None:
assert not stale, f"ship these fitted values: {stale}"
-def test_a_stand_in_is_a_whole_line_no_in_fit_point_measures() -> None:
- """A stand-in is for what a platform has not measured. Once an in-fit point measures its line, the line is fitted
- instead, and this names it."""
+def test_a_stand_in_is_a_whole_line_its_fresh_process_points_cannot_fit() -> None:
+ """A stand-in is for what a platform has not measured. Once in-fit fresh-process points measure its line at sizes
+ a fit needs (`capping_spans`), the line is fitted instead, and this names it. `probe_demand` points bound a
+ stand-in from below only: warm windows never fit a line below what a cold first run needs."""
groups = fit_points(shipped_data().values())
for entry in ENTRIES:
lines = {name[2:] for name in entry.stand_ins}
assert {f"{part}_{line}" for line in lines for part in ("k", "b")} == set(entry.stand_ins), entry.platform
- measured = sorted(line for line in lines if (entry_key(entry), line) in groups)
+ measured = sorted(line for line in lines if capping_spans(groups.get((entry_key(entry), line), [])))
assert not measured, f"{entry.estimator} on {entry.platform}: fit {measured}, they are measured now"
@@ -245,38 +220,25 @@ def test_the_out_of_fit_points_are_the_listed_ones() -> None:
def test_every_listed_upper_bound_exception_is_a_shipped_point_that_needs_it() -> None:
"""A stale exception would let a new point at that id over-reserve unseen."""
- ids = {_point_id(point): point for point in ALL_POINTS}
- for point_id, ratio in UPPER_BOUND_EXCEPTIONS.items():
- point = ids.get(point_id)
- assert point is not None, f"{point_id}: no such point"
+ ids = {point_id(point): point for point in ALL_POINTS}
+ for listed, ratio in UPPER_BOUND_EXCEPTIONS.items():
+ point = ids.get(listed)
+ assert point is not None, f"{listed}: no such point"
assert point.in_fit
reserved = _evaluate(point).reservation_bytes / point.measured_bytes
- assert MAX_OVER_RESERVATION < reserved <= ratio, f"{point_id}: {reserved:.3f}x"
+ assert MAX_OVER_RESERVATION < reserved <= ratio, f"{listed}: {reserved:.3f}x"
@pytest.mark.parametrize("point", POINTS)
def test_every_measured_point_is_bounded_by_its_estimate(point: MeasuredPoint) -> None:
- estimate = _evaluate(point)
- fitted = _fitted_decides(estimate)
-
- reserved = estimate.reservation_bytes if fitted else max(estimate.reservation_bytes, WORKING_MEMORY_FLOOR)
- assert reserved >= point.measured_bytes, (
- f"reserves {reserved / 2**30:.3f} GiB for a measured {point.measured_bytes / 2**30:.3f} GiB"
- )
- # An out-of-fit point checks another term: it gets the lower bound only.
- if point.max_ratio is not None or (fitted and point.in_fit):
- default = UPPER_BOUND_EXCEPTIONS.get(_point_id(point), MAX_OVER_RESERVATION)
- max_ratio = point.max_ratio if point.max_ratio is not None else default
- assert estimate.reservation_bytes <= max_ratio * point.measured_bytes, (
- f"reserves {estimate.reservation_bytes / point.measured_bytes:.2f}x the measured peak, over {max_ratio}x"
- )
+ assert bound_violation(point, _evaluate(point)) is None
def test_a_point_bound_is_never_looser_than_the_default() -> None:
"""`max_ratio` tightens the bound for a point the estimate has to stay close to; it never excuses one."""
for point in ALL_POINTS:
if point.max_ratio is not None:
- assert 1.0 <= point.max_ratio < MAX_OVER_RESERVATION, _point_id(point)
+ assert 1.0 <= point.max_ratio < MAX_OVER_RESERVATION, point_id(point)
@pytest.mark.parametrize(
@@ -342,6 +304,69 @@ def test_the_platform_is_the_os_the_process_runs_on(sys_platform, os, monkeypatc
assert platform_for(torch.device("cpu")).os == os
+def _recorded_hard_facts(device: torch.device) -> dict[str, str]:
+ """The hard facts a calibration store records for `device` in this process."""
+ return dict(environment_for(device, {"attention_type": "sdpa"}).hard)
+
+
+def host_os_unpinned(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The platform reads the OS from `sys.platform` again, as `environment_for` does, instead of the suite's pin."""
+ monkeypatch.setattr(platform_module, "_host_os", HOST_OS)
+
+
[email protected]("hip", [None, "7.14.0"], ids=["cuda", "hip"])
+ "allocator_backend, alloc_var, alloc_conf",
+ [
+ ("native", None, None),
+ ("native", "PYTORCH_HIP_ALLOC_CONF", "expandable_segments:True"),
+ ("native", "PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:False"),
+ ("cudaMallocAsync", "PYTORCH_ALLOC_CONF", "backend:cudaMallocAsync,expandable_segments:True"),
+ ],
+)
[email protected]("sys_platform", ["win32", "linux", "darwin"])
+def test_a_recorded_gpu_environment_names_the_platform_its_operations_are_priced_on(
+ hip, allocator_backend, alloc_var, alloc_conf, sys_platform, host_os_unpinned, monkeypatch
+) -> None:
+ """Shipped points are keyed by the platform their calibration store's environment names; it must be the one
+ `platform_for` prices the same machine on."""
+ monkeypatch.setattr(torch.version, "hip", hip)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_allocator_backend", lambda: allocator_backend)
+ monkeypatch.setattr(nvml, "driver_version", lambda: None)
+ monkeypatch.setattr(platform_module.sys, "platform", sys_platform)
+ monkeypatch.setattr(stdlib_platform, "platform", lambda: "Test-1.0")
+ if alloc_var is not None:
+ monkeypatch.setenv(alloc_var, alloc_conf)
+ cuda = torch.device("cuda", 0)
+
+ assert platform_for_environment(backend_for(cuda), _recorded_hard_facts(cuda)) == platform_for(cuda)
+
+
[email protected]("device", [torch.device("mps"), torch.device("xpu")], ids=str)
+def test_a_recorded_environment_of_a_device_without_a_caching_allocator_names_its_platform(
+ device, host_os_unpinned, monkeypatch
+) -> None:
+ # An allocator variable configures CUDA/HIP only.
+ monkeypatch.setenv("PYTORCH_ALLOC_CONF", "expandable_segments:True")
+
+ assert platform_for_environment(backend_for(device), _recorded_hard_facts(device)) == platform_for(device)
+
+
+def test_an_environment_without_the_platforms_facts_is_refused(monkeypatch) -> None:
+ monkeypatch.setattr(torch.version, "hip", None)
+ # A CPU wheel (macOS, Windows) has no allocator binding to ask.
+ monkeypatch.setattr(torch.cuda, "get_allocator_backend", lambda: "native")
+ monkeypatch.setattr(nvml, "driver_version", lambda: None)
+ hard = _recorded_hard_facts(torch.device("cuda", 0))
+
+ with pytest.raises(ValueError, match="no operating system"):
+ platform_for_environment("cuda", {key: value for key, value in hard.items() if key != "os"})
+ with pytest.raises(ValueError, match="no allocator_backend"):
+ platform_for_environment("cuda", {key: value for key, value in hard.items() if key != "allocator_backend"})
+
+
@pytest.mark.parametrize(
"platform, measured",
[
@@ -523,3 +548,29 @@ def test_every_module_that_declares_an_estimator_is_listed() -> None:
unlisted = sorted(set(declaring) - set(ESTIMATOR_MODULES))
stale = sorted(set(ESTIMATOR_MODULES) - set(declaring))
assert not unlisted and not stale, f"add to ESTIMATOR_MODULES: {unlisted}; declares no spec: {stale}"
+
+
+def _measured(method: str, max_ratio: float | None = None) -> MeasuredPoint:
+ return MeasuredPoint(
+ estimator="vae.sd3",
+ version=2,
+ platform={"conv_backend": "cudnn", "allocator": "native"},
+ features={},
+ measured_bytes=1,
+ method=method,
+ device="-",
+ provenance="-",
+ max_ratio=max_ratio,
+ )
+
+
[email protected]("method", get_args(get_type_hints(MeasuredPoint)["method"]))
+def test_only_fresh_process_points_bound_an_estimate_from_above(method: str) -> None:
+ """A probe window is a warm operation in a running server; the cold first run after a server start can exceed it,
+ so it may raise a line but never caps one."""
+ assert _measured(method).holds_upper_bound == (method != "probe_demand")
+ if method == "probe_demand":
+ with pytest.raises(ValidationError, match="from below only"):
+ _measured(method, max_ratio=1.2)
+ else:
+ assert _measured(method, max_ratio=1.2).max_ratio == 1.2
diff --git a/tests/backend/working_memory/test_user_fit.py b/tests/backend/working_memory/test_user_fit.py
new file mode 100644
index 0000000000..64a197a430
--- /dev/null
+++ b/tests/backend/working_memory/test_user_fit.py
@@ -0,0 +1,202 @@
+"""A user's calibration lines: how they are fitted, and how an estimate reads them in place of the shipped values."""
+
+from collections.abc import Iterator
+
+import pytest
+import torch
+
+from invokeai.backend.util.vae_working_memory import VAE_FLUX_SPEC, VAE_SD_SPEC
+from invokeai.backend.working_memory import user_fit
+from invokeai.backend.working_memory.coefficients import shipped_coefficients
+from invokeai.backend.working_memory.fit import shipped_pair, user_pair
+from invokeai.backend.working_memory.platform import Platform, platform_for
+from invokeai.backend.working_memory.spec import EstimatorSpec
+from invokeai.backend.working_memory.user_fit import UserFit, UserPoint, fit_user_lines
+
+MIB = 2**20
+DEVICE = torch.device("cuda:0")
+PLATFORM = platform_for(DEVICE)
+
+
+def _features(side: int, dtype: str = "fp16", tile: int | None = None, **extra: object) -> dict:
+ return {
+ "operation": "decode",
+ "height": side,
+ "width": side,
+ "tile": tile,
+ "dtype": dtype,
+ "vae_class": "AutoencoderKL",
+ "upcast_weight_bytes": 0,
+ "score_matrix_bytes": 0,
+ **extra,
+ }
+
+
+def _points(slope: int, base: int, sides: tuple[int, ...] = (512, 768, 1024), dtype: str = "fp16") -> list[UserPoint]:
+ """Windows on an exact line ``slope * pixels + base``."""
+ return [UserPoint("vae.sd", VAE_SD_SPEC.version, _features(side, dtype), slope * side**2 + base) for side in sides]
+
+
+def _fit(points: list[UserPoint]) -> UserFit:
+ lines, problems = fit_user_lines(points, PLATFORM)
+ assert lines, problems
+ return UserFit(label="user:dc:env", platform=PLATFORM, lines=lines)
+
+
+def provide() -> Iterator:
+ """Register a provider that answers `fit` for every estimate; unregistered after the test."""
+ registered: list[user_fit.UserFitProvider] = []
+
+ def install(fit: UserFit | None) -> None:
+ def provider(spec: EstimatorSpec, platform: Platform, device: torch.device) -> UserFit | None:
+ return fit
+
+ registered.append(provider)
+ user_fit.set_user_fit_provider(provider)
+
+ yield install
+ for provider in registered:
+ user_fit.clear_user_fit_provider(provider)
+
+
+def _shipped(spec: EstimatorSpec, features: dict) -> int:
+ return spec.evaluate(features, shipped_coefficients(spec, PLATFORM)).reservation_bytes
+
+
+GRID = [
+ _features(side, dtype, tile)
+ for side in (256, 512, 1024, 1536, 2048, 4096)
+ for dtype in ("fp16", "fp32")
+ for tile in (None, 512)
+]
+
+
+def test_without_a_user_line_estimates_are_the_shipped_ones_bit_for_bit(provide) -> None:
+ before = [VAE_SD_SPEC.estimate(features, DEVICE) for features in GRID]
+
+ provide(None)
+ without_fit = [VAE_SD_SPEC.estimate(features, DEVICE) for features in GRID]
+ # A fit that measured another line only: an encode.
+ encode = [
+ UserPoint("vae.sd", VAE_SD_SPEC.version, _features(side) | {"operation": "encode"}, 10**9)
+ for side in (512, 1024)
+ ]
+ provide(_fit(encode))
+ other_line = [VAE_SD_SPEC.estimate(features, DEVICE) for features in GRID]
+
+ assert before == without_fit == other_line
+ assert [estimate.reservation_bytes for estimate in before] == [_shipped(VAE_SD_SPEC, f) for f in GRID]
+
+
+def test_within_and_below_its_measured_sizes_the_user_line_replaces_the_shipped_one(provide) -> None:
+ # Windows on 900 B/px + 400 MiB; the user line adds 5%: 945 B/px and 420 MiB.
+ provide(_fit(_points(900, 400 * MIB)))
+
+ for side in (256, 512, 900, 1024):
+ estimate = VAE_SD_SPEC.estimate(_features(side), DEVICE)
+ assert estimate.reservation_bytes == 945 * side**2 + 420 * MIB
+ assert estimate.source.startswith("user:dc:env (decode_fp16 within its measured sizes) + shipped:")
+
+ # The fp32 line was not measured: shipped.
+ fp32 = _features(1024, "fp32")
+ assert VAE_SD_SPEC.estimate(fp32, DEVICE).reservation_bytes == _shipped(VAE_SD_SPEC, fp32)
+
+
+def test_above_its_measured_sizes_the_larger_of_the_user_and_the_shipped_estimate_wins(provide) -> None:
+ large = _features(2048)
+ shipped = _shipped(VAE_SD_SPEC, large)
+
+ provide(_fit(_points(20000, 400 * MIB)))
+ high = VAE_SD_SPEC.estimate(large, DEVICE)
+ assert high.reservation_bytes == 21000 * 2048**2 + 420 * MIB > shipped
+ assert "above its measured sizes, over shipped" in high.source
+
+ provide(_fit(_points(1, 1 * MIB)))
+ low = VAE_SD_SPEC.estimate(large, DEVICE)
+ assert low.reservation_bytes == shipped
+ assert low.source.startswith("shipped:") and "over user:dc:env decode_fp16" in low.source
+ # Within the measured sizes the low user line still decides.
+ assert VAE_SD_SPEC.estimate(_features(1024), DEVICE).reservation_bytes == 2 * 1024**2 + 2 * MIB
+
+
+def test_a_tiled_decode_is_placed_by_its_image_and_priced_on_its_tile(provide) -> None:
+ provide(_fit(_points(900, 400 * MIB)))
+ # 2048px is above the measured 1024px, so the larger estimate wins; both price the 512px tile, 1.25x.
+ tiled = _features(2048, tile=512)
+ user = 945 * 512 * 512 * 1.25 + 420 * MIB
+ assert VAE_SD_SPEC.estimate(tiled, DEVICE).reservation_bytes == max(int(user), _shipped(VAE_SD_SPEC, tiled))
+
+
+def test_a_line_carried_for_several_estimators_moves_all_of_them(provide) -> None:
+ """vae.sd and vae.flux borrow one entry's values, so an SD fp16 decode calibrates FLUX.1's fp16 decode too."""
+ assert user_fit.carrier_key("vae.sd", 2, PLATFORM) == user_fit.carrier_key("vae.flux", 2, PLATFORM)
+ provide(_fit(_points(900, 400 * MIB)))
+ flux = {
+ "operation": "decode",
+ "height": 1024,
+ "width": 1024,
+ "dtype": "fp16",
+ "tile": None,
+ "score_matrix_bytes": 0,
+ }
+ assert VAE_FLUX_SPEC.estimate(flux, DEVICE).reservation_bytes == 945 * 1024**2 + 420 * MIB
+
+
+def test_the_user_margin_is_the_shipped_five_percent() -> None:
+ points = [(512 * 512, 900 * 512 * 512 + 400 * MIB), (1024 * 1024, 900 * 1024 * 1024 + 400 * MIB)]
+ assert user_pair(points) == (945, 420 * MIB)
+ assert shipped_pair(points) == (945, 420 * MIB)
+
+
+def test_the_margin_covers_the_fitted_line_only_and_analytic_terms_stay_as_they_are(provide) -> None:
+ """An upcast decode reserves the VAE's growth on top of the line: the user margin must not grow it too."""
+ provide(_fit(_points(900, 400 * MIB)))
+ upcast = 160 * MIB
+
+ estimate = VAE_SD_SPEC.estimate(_features(1024, upcast_weight_bytes=upcast), DEVICE)
+
+ assert estimate.reservation_bytes == 945 * 1024**2 + 420 * MIB + upcast
+
+
+def test_only_untiled_single_sample_autoencoder_kl_windows_with_demand_and_a_known_version_fit_a_line() -> None:
+ good = _points(900, 400 * MIB, sides=(512, 1024))
+ ignored = [
+ UserPoint("vae.sd", 2, _features(2048, tile=512), 10**12),
+ UserPoint("vae.sd", 2, _features(2048, upcast_weight_bytes=160 * MIB), 10**12),
+ UserPoint("vae.sd", 2, _features(2048, vae_class="AutoencoderTiny"), 10**12),
+ UserPoint("vae.sd", 2, _features(2048, batch_size=2), 10**12),
+ UserPoint("vae.sd", 2, _features(2048), 0),
+ UserPoint("vae.sd", 1, _features(2048), 10**12),
+ UserPoint("vae.unknown", 2, _features(2048), 10**12),
+ ]
+
+ lines, _ = fit_user_lines(good + ignored, PLATFORM)
+
+ [line] = lines.values()
+ assert (line.k, line.b, line.x_min, line.x_max, line.points) == (945, 420 * MIB, 512**2, 1024**2, 2)
+
+
+def test_a_line_measured_at_sizes_too_close_together_fits_nothing_and_says_why() -> None:
+ lines, problems = fit_user_lines(_points(900, 400 * MIB, sides=(1024, 1280)), PLATFORM)
+ assert not lines
+ [problem] = problems.values()
+ assert "measure more sizes" in problem
+
+
+def test_a_provider_that_raises_leaves_estimates_shipped_and_only_its_own_registration_is_cleared(provide) -> None:
+ features = _features(1024)
+ shipped = VAE_SD_SPEC.estimate(features, DEVICE)
+
+ def broken(spec: EstimatorSpec, platform: Platform, device: torch.device) -> UserFit | None:
+ raise RuntimeError("store gone")
+
+ user_fit.set_user_fit_provider(broken)
+ try:
+ assert VAE_SD_SPEC.estimate(features, DEVICE) == shipped
+ finally:
+ user_fit.clear_user_fit_provider(broken)
+
+ provide(_fit(_points(900, 400 * MIB)))
+ user_fit.clear_user_fit_provider(broken)
+ assert VAE_SD_SPEC.estimate(features, DEVICE).source.startswith("user:")
diff --git a/tests/family_e2e/fake_invokeai_server.py b/tests/family_e2e/fake_invokeai_server.py
index ad8763f66d..5176e9e4d5 100644
--- a/tests/family_e2e/fake_invokeai_server.py
+++ b/tests/family_e2e/fake_invokeai_server.py
@@ -5,6 +5,11 @@ launch InvokeAI. It reads the scratch root's `invokeai.yaml` for its port and lo
format, and executes a queued graph by walking its nodes: the model loader logs a full load once per cache flush, the
`fake_denoise` node sends preview frames, and the non-intermediate node returns a PNG of its width and height.
When `<code_dir>/crash-at-enqueue` holds N, the server deletes the file and dies while running its N-th queue item.
+The working-memory calibrate route enqueues like enqueue_batch and records one point per model node in a store file
+under the root's db_dir, as the real server does, and the request's `graph_models` with each run; a request without
+them is refused with 422, as the real server refuses it. `<code_dir>/calibration-refused` holds `{"at": N or null, "status":
+"<HTTP status line>", "detail": ...}`: the route answers the N-th request (every one for null) with that error.
+`<code_dir>/calibration-unavailable` makes the status report calibration unavailable, with the file's text as reason.
Self-contained on purpose: it runs in a fresh interpreter with only the code directory on the path.
"""
@@ -26,13 +31,18 @@ import yaml
from PIL import Image
STEP_S = 0.01
-CRASH_MARKER = Path(__file__).resolve().parents[1] / "crash-at-enqueue"
+CODE_DIR = Path(__file__).resolve().parents[1]
+CRASH_MARKER = CODE_DIR / "crash-at-enqueue"
+CALIBRATION_REFUSED = CODE_DIR / "calibration-refused"
+CALIBRATION_UNAVAILABLE = CODE_DIR / "calibration-unavailable"
+DEVICE_CLASS_ID = "0123456789abcdef"
MODEL_CONFIG = {
"key": "fake-model",
"name": "Fake",
"base": "fake",
"type": "main",
"format": "checkpoint",
+ "variant": "normal",
"hash": "blake3:fakehash",
"path": "/models/fake.safetensors",
"source": "https://example.com/fake.safetensors?token=fake-token",
@@ -51,8 +61,11 @@ class _QuietHandler(WSGIRequestHandler):
class FakeInvoke:
- def __init__(self, logger: logging.Logger) -> None:
+ def __init__(self, logger: logging.Logger, store_dir: Path) -> None:
self.logger = logger
+ self.store_file = store_dir / f"{DEVICE_CLASS_ID}.json"
+ self.calibrate_requests = 0
+ self.calibration_runs = 0
self.sio = socketio.Server(async_mode="threading")
self.sio.on("subscribe_queue", self.subscribe)
self.lock = threading.Lock()
@@ -109,6 +122,11 @@ class FakeInvoke:
results[prepared] = result
time.sleep(STEP_S)
self.emit("invocation_complete", base | {"result": result})
+ run_id = item["batch"].get("origin", "").removeprefix("invokeai:wm-calibration:")
+ if run_id != item["batch"].get("origin", ""):
+ self.record_points(
+ run_id, item_id, [node_id for node_id, node in graph["nodes"].items() if "model" in node]
+ )
item.update(
status="completed",
completed_at=str(datetime.now()),
@@ -116,6 +134,46 @@ class FakeInvoke:
)
self.emit("queue_item_status_changed", {"item_id": item_id, "status": "completed"})
+ def enqueue(self, batch: dict) -> int:
+ with self.lock:
+ item_id = len(self.items) + 1
+ self.items[item_id] = {"item_id": item_id, "status": "pending", "batch": batch, "session": {}}
+ crash = CRASH_MARKER.exists() and CRASH_MARKER.read_text() == str(item_id)
+ if crash:
+ CRASH_MARKER.unlink()
+ threading.Thread(target=self.execute, args=(item_id, crash), daemon=True).start()
+ return item_id
+
+ def store(self) -> dict:
+ if self.store_file.is_file():
+ return json.loads(self.store_file.read_text(encoding="utf-8"))
+ return {"schema_version": 1, "device_class": {"id": DEVICE_CLASS_ID}, "runs": [], "points": [], "envs": []}
+
+ def record_points(self, run_id: str, item_id: int, node_ids: list[str]) -> None:
+ with self.lock:
+ store = self.store()
+ store["points"] += [{"run_id": run_id, "queue_item_id": item_id, "node_id": n} for n in node_ids]
+ self.store_file.parent.mkdir(parents=True, exist_ok=True)
+ self.store_file.write_text(json.dumps(store), encoding="utf-8")
+
+ def calibrate(self, model_key: str, body: dict) -> tuple[dict, str]:
+ self.calibrate_requests += 1
+ if CALIBRATION_REFUSED.exists():
+ refusal = json.loads(CALIBRATION_REFUSED.read_text())
+ if refusal["at"] in (None, self.calibrate_requests):
+ return {"detail": refusal["detail"]}, refusal["status"]
+ if not isinstance(body.get("graph_models"), dict):
+ return {"detail": "graph_models: Field required"}, "422 Unprocessable Entity"
+ self.calibration_runs += 1
+ run_id = f"run-{self.calibration_runs}"
+ with self.lock:
+ store = self.store()
+ store["runs"].append({"run_id": run_id, "model_key": model_key, "graph_models": body["graph_models"]})
+ self.store_file.parent.mkdir(parents=True, exist_ok=True)
+ self.store_file.write_text(json.dumps(store), encoding="utf-8")
+ batch = {"graph": body["graph"], "data": body.get("data"), "origin": f"invokeai:wm-calibration:{run_id}"}
+ return {"run_id": run_id, "device_class_id": DEVICE_CLASS_ID, "item_ids": [self.enqueue(batch)]}, "201 Created"
+
def __call__(self, environ, start_response):
method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"]
length = int(environ.get("CONTENT_LENGTH") or 0)
@@ -145,19 +203,18 @@ class FakeInvoke:
self.uploads += 1
return reply({"image_name": f"upload-{self.uploads}.png"}, status="201 Created")
if path == "/api/v1/queue/default/enqueue_batch":
- with self.lock:
- item_id = len(self.items) + 1
- self.items[item_id] = {
- "item_id": item_id,
- "status": "pending",
- "batch": json.loads(body)["batch"],
- "session": {},
- }
- crash = CRASH_MARKER.exists() and CRASH_MARKER.read_text() == str(item_id)
- if crash:
- CRASH_MARKER.unlink()
- threading.Thread(target=self.execute, args=(item_id, crash), daemon=True).start()
- return reply({"item_ids": [item_id]}, status="201 Created")
+ return reply({"item_ids": [self.enqueue(json.loads(body)["batch"])]}, status="201 Created")
+ if match := re.fullmatch(r"/api/v2/models/i/([^/]+)/working_memory/calibrate", path):
+ payload, status = self.calibrate(match[1], json.loads(body))
+ return reply(payload, status=status)
+ if path == "/api/v2/models/working_memory/status":
+ reason = CALIBRATION_UNAVAILABLE.read_text() if CALIBRATION_UNAVAILABLE.exists() else None
+ status = {"available": reason is None, "unavailable_reason": reason}
+ return reply(status | {"current_device_class_id": DEVICE_CLASS_ID})
+ if path == "/api/v2/models/working_memory/export":
+ if not self.store_file.is_file() or environ.get("QUERY_STRING") != f"device_class_id={DEVICE_CLASS_ID}":
+ return reply({"detail": "no store"}, status="404 Not Found")
+ return reply(self.store_file.read_bytes())
if path == "/api/v1/queue/default/status":
states = [item["status"] for item in self.items.values()]
return reply(
@@ -186,7 +243,7 @@ def main() -> None:
logger.setLevel(logging.INFO)
logger.addHandler(handler)
- fake = FakeInvoke(logger)
+ fake = FakeInvoke(logger, root / config.get("db_dir", "databases") / "working_memory")
app = socketio.WSGIApp(fake.sio, fake, socketio_path="/ws/socket.io")
port = config["port"]
while True:
diff --git a/tests/family_e2e/test_calibration.py b/tests/family_e2e/test_calibration.py
new file mode 100644
index 0000000000..fd75be6958
--- /dev/null
+++ b/tests/family_e2e/test_calibration.py
@@ -0,0 +1,292 @@
+"""Calibration runs against the fake server: the calibrate route instead of enqueue_batch, refusals per case or for
+the run, and the store of every server lifetime saved into the run."""
+
+import json
+from pathlib import Path
+
+import pytest
+
+from scripts.family_e2e import calibration, runner
+from scripts.family_e2e.calibration import PROBE_REASON, CalibrationError
+from scripts.family_e2e.records import Record, load_records, load_run_info, write_run_info
+from tests.family_e2e.test_flow import FOREIGN_PID, MODEL, FakeGpu, isolated_runner, setup # noqa: F401 - fixtures
+
+DEVICE_CLASS_ID = "0123456789abcdef"
+
+
+def _export(request: dict, work_dir: Path) -> dict:
+ graph = {
+ "id": "fake-graph",
+ "nodes": {
+ "loader": {"id": "loader", "type": "fake_loader", "is_intermediate": True, "model": MODEL},
+ "output": {"id": "output", "type": "fake_l2i", "is_intermediate": False, "width": 64, "height": 48},
+ },
+ "edges": [],
+ }
+ batch = {"graph": graph, "data": [], "origin": "test", "destination": "test"}
+ return {"version": 1, "cases": [{"id": request["cases"][0]["id"], "batch": batch, "components": {}}]}
+
+
+def _store(run_dir: Path, path: str) -> dict:
+ return json.loads((run_dir / path).read_text())
+
+
+def test_a_calibration_run_measures_every_step_once_and_saves_every_lifetimes_store(
+ setup: tuple[Path, Path], # noqa: F811 - fixture
+ isolated_runner: None, # noqa: F811 - fixture
+) -> None:
+ manifest_path, _ = setup
+ # The first server dies in its second queue item, the first measure.
+ (manifest_path.parent / "code" / "crash-at-enqueue").write_text("2")
+ gpu = FakeGpu()
+
+ run_dir = runner.new_run(manifest_path, [], [], calibrate=True)
+ assert runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export) == 0
+
+ records = load_records(run_dir)
+ # The second server warms up again and repeats the crashed measure. Foreign load spoils that one, and it is kept:
+ # the server keeps every window it measured.
+ assert [(r.kind, r.rep, r.attempt) for r in records] == [
+ ("warmup", 0, 1),
+ ("measure", 0, 1),
+ ("warmup", 0, 2),
+ ("measure", 0, 2),
+ ("measure", 1, 1),
+ ]
+ crashed, spoiled = records.pop(1), records.pop(2)
+ assert crashed.status == "error" and crashed.calibration is None
+ assert spoiled.invalid_reasons == [f"foreign GPU load: pid {FOREIGN_PID} (?) 2048 MiB", PROBE_REASON]
+ for record in records:
+ assert record.status == "completed", record.error
+ # The probe alone makes time and VRAM invalid; the residency is known.
+ assert record.invalid_reasons == [PROBE_REASON]
+ assert (record.valid_timing, record.valid_memory, record.valid_psnr) == (False, False, True)
+ assert (run_dir / record.image_path).is_file()
+
+ info = load_run_info(run_dir)
+ assert [(e.lifetime, e.source, e.device_class_id) for e in info.calibration_exports] == [
+ (1, "store_file", DEVICE_CLASS_ID),
+ (2, "api", DEVICE_CLASS_ID),
+ ]
+ first, second = info.calibration_exports
+ assert first.status is None
+ assert json.loads((run_dir / second.status).read_text())["current_device_class_id"] == DEVICE_CLASS_ID
+ # Each lifetime's store holds the runs its server created; the crashed one's item never ran a node.
+ first_store, second_store = _store(run_dir, first.export), _store(run_dir, second.export)
+ assert [run["run_id"] for run in first_store["runs"]] == ["run-1", "run-2"]
+ # Every step states the graph's model as the config the case was compiled from has it.
+ compiled = {"hash": "blake3:fakehash", "base": "fake", "type": "main", "format": "checkpoint", "variant": "normal"}
+ assert [run["graph_models"] for run in first_store["runs"] + second_store["runs"]] == [{"fake-model": compiled}] * (
+ len(first_store["runs"]) + len(second_store["runs"])
+ )
+ assert [p["queue_item_id"] for p in first_store["points"]] == [records[0].queue_item_id]
+ later = [records[1], spoiled, records[2]]
+ assert [run["run_id"] for run in second_store["runs"]] == [r.calibration.run_id for r in later]
+ assert [p["queue_item_id"] for p in second_store["points"]] == [r.queue_item_id for r in later]
+
+ # A runner killed before the last measure: the resumed run's server saves its own store.
+ lines = (run_dir / "records.jsonl").read_text().splitlines(keepends=True)
+ (run_dir / "records.jsonl").write_text("".join(lines[:4]))
+ write_run_info(run_dir, info.model_copy(update={"status": "running"}))
+ assert runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export) == 0
+
+ resumed = load_records(run_dir)
+ assert [(r.kind, r.rep, r.attempt) for r in resumed[4:]] == [("warmup", 0, 3), ("measure", 1, 1)]
+ assert runner.remaining_steps(info.plan, resumed) == []
+ third = load_run_info(run_dir).calibration_exports[-1]
+ assert (third.lifetime, third.source) == (3, "api")
+ assert [p["queue_item_id"] for p in _store(run_dir, third.export)["points"]] == [
+ r.queue_item_id for r in resumed[4:]
+ ]
+
+
+def _refuse(manifest_path: Path, at: int | None, status: str, detail: str) -> None:
+ refusal = {"at": at, "status": status, "detail": detail}
+ (manifest_path.parent / "code" / "calibration-refused").write_text(json.dumps(refusal))
+
+
+def test_a_refused_case_gets_an_error_record_and_the_run_goes_on(
+ setup: tuple[Path, Path], # noqa: F811 - fixture
+ isolated_runner: None, # noqa: F811 - fixture
+) -> None:
+ manifest_path, _ = setup
+ _refuse(manifest_path, 2, "422 Unprocessable Entity", "Node n1 calls a saved workflow.")
+ gpu = FakeGpu()
+ run_dir = runner.new_run(manifest_path, [], [], calibrate=True)
+
+ # The case's error record fails the report, and the run completes.
+ assert runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export) == 1
+
+ records = load_records(run_dir)
+ assert [(r.kind, r.rep, r.status) for r in records] == [
+ ("warmup", 0, "completed"),
+ ("measure", 0, "error"),
+ ("measure", 1, "completed"),
+ ]
+ assert "-> 422: " in records[1].error and "saved workflow" in records[1].error
+ info = load_run_info(run_dir)
+ assert info.status == "completed"
+ [export] = info.calibration_exports
+ assert export.source == "api"
+ assert [p["queue_item_id"] for p in _store(run_dir, export.export)["points"]] == [
+ records[0].queue_item_id,
+ records[2].queue_item_id,
+ ]
+
+
+ "status, detail",
+ [
+ ("403 Forbidden", "Admin access required"),
+ ("409 Conflict", "Calibration runs on a single generation device, and this machine generates on 2."),
+ ("429 Too Many Requests", "Too many unacknowledged idempotency keys"),
+ ],
+)
+def test_a_refusal_that_concerns_every_case_fails_the_run_and_keeps_its_windows(
+ status: str,
+ detail: str,
+ setup: tuple[Path, Path], # noqa: F811 - fixture
+ isolated_runner: None, # noqa: F811 - fixture
+) -> None:
+ manifest_path, _ = setup
+ _refuse(manifest_path, 2, status, detail)
+ gpu = FakeGpu()
+ run_dir = runner.new_run(manifest_path, [], [], calibrate=True)
+
+ with pytest.raises(CalibrationError, match=rf"refused the calibration run: POST .* -> {status[:3]}: "):
+ runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export)
+
+ records = load_records(run_dir)
+ assert [(r.kind, r.status) for r in records] == [("warmup", "completed")]
+ info = load_run_info(run_dir)
+ assert info.status == "failed"
+ # The scratch root's store is copied before the root goes: the warm-up's windows are kept.
+ [export] = info.calibration_exports
+ assert export.source == "store_file"
+ assert [p["queue_item_id"] for p in _store(run_dir, export.export)["points"]] == [records[0].queue_item_id]
+
+
+def test_a_store_neither_the_export_nor_the_copy_saves_stays_in_its_scratch_root(
+ setup: tuple[Path, Path], # noqa: F811 - fixture
+ isolated_runner: None, # noqa: F811 - fixture
+) -> None:
+ manifest_path, _ = setup
+ gpu = FakeGpu()
+ run_dir = runner.new_run(manifest_path, [], [], calibrate=True)
+ # A file where the run's calibration/ directory goes: the export's write and the copy's both raise.
+ (run_dir / "calibration").write_text("")
+
+ with pytest.raises(runner.RunnerError, match="kept the scratch root"):
+ runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export)
+
+ info = load_run_info(run_dir)
+ assert (info.status, info.calibration_exports) == ("failed", [])
+ # The only copy of the lifetime's windows: the scratch root is not deleted.
+ root = runner.scratch_root(manifest_path.parent / "data", info.run_id, runner.DEFAULT_ARM)
+ store_file = root / "databases" / "working_memory" / f"{DEVICE_CLASS_ID}.json"
+ kept = store_file.read_bytes()
+ item_ids = [r.queue_item_id for r in load_records(run_dir)]
+ assert [p["queue_item_id"] for p in json.loads(kept)["points"]] == item_ids
+
+ # A resume that cannot save the kept store either refuses before a new server's root replaces it.
+ write_run_info(run_dir, info.model_copy(update={"status": "running"}))
+ with pytest.raises(runner.RunnerError, match="not resuming"):
+ runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export)
+ assert store_file.read_bytes() == kept
+
+ # With the cause fixed, the resume saves the kept store first, then removes the root.
+ (run_dir / "calibration").unlink()
+ write_run_info(run_dir, load_run_info(run_dir).model_copy(update={"status": "running"}))
+ assert runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export) == 0
+
+ [export] = load_run_info(run_dir).calibration_exports
+ assert (export.lifetime, export.source) == (1, "store_file")
+ assert (run_dir / export.export).read_bytes() == kept
+ assert not root.exists()
+
+
+def test_a_stop_whose_store_cannot_be_saved_ends_stopped_and_keeps_the_root(
+ setup: tuple[Path, Path], # noqa: F811 - fixture
+ isolated_runner: None, # noqa: F811 - fixture
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ manifest_path, _ = setup
+ gpu = FakeGpu()
+ run_dir = runner.new_run(manifest_path, [], [], calibrate=True)
+ (run_dir / "calibration").write_text("")
+
+ def stopped(*args, **kwargs):
+ # A Ctrl-C, or the SIGTERM `__main__` turns into one, while the runner saves the export.
+ raise KeyboardInterrupt
+
+ monkeypatch.setattr(calibration, "fetch_exports", stopped)
+
+ with pytest.raises(KeyboardInterrupt):
+ runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export)
+
+ info = load_run_info(run_dir)
+ assert info.status == "stopped"
+ assert "could not save the calibration store" in caplog.text and "kept the scratch root" in caplog.text
+ root = runner.scratch_root(manifest_path.parent / "data", info.run_id, runner.DEFAULT_ARM)
+ assert (root / "databases" / "working_memory" / f"{DEVICE_CLASS_ID}.json").is_file()
+
+
[email protected]("save", ["works", "fails"])
+def test_a_runner_that_finds_the_run_stopped_saves_its_store_and_keeps_the_stop(
+ save: str,
+ setup: tuple[Path, Path], # noqa: F811 - fixture
+ isolated_runner: None, # noqa: F811 - fixture
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ manifest_path, data_dir = setup
+ gpu = FakeGpu()
+ run_dir = runner.new_run(manifest_path, [], [], calibrate=True)
+ if save == "fails":
+ # A file where the run's calibration/ directory goes: the copy raises, as on a full disk.
+ (run_dir / "calibration").write_text("")
+ store = runner._Session.store
+
+ def store_then_stop(session: runner._Session, record: Record) -> None:
+ store(session, record)
+ # `stop` marks the run after the first record, and its kill has not reached the runner yet.
+ runner.finish_run(run_dir, "stopped")
+
+ monkeypatch.setattr(runner._Session, "store", store_then_stop)
+ with pytest.raises(runner.RunStopped):
+ runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export)
+
+ records = load_records(run_dir)
+ assert [(r.kind, r.rep) for r in records] == [("warmup", 0)]
+ info = load_run_info(run_dir)
+ # The store is recorded, or kept with its root, without undoing the stop.
+ assert info.status == "stopped"
+ assert not (run_dir / "report.html").exists()
+ root = data_dir / "scratch-roots" / f"{run_dir.name}-default"
+ if save == "works":
+ [export] = info.calibration_exports
+ assert (export.lifetime, export.source) == (1, "store_file")
+ assert [p["queue_item_id"] for p in _store(run_dir, export.export)["points"]] == [records[0].queue_item_id]
+ assert not root.exists()
+ else:
+ assert info.calibration_exports == []
+ kept = json.loads((root / "databases" / "working_memory" / f"{DEVICE_CLASS_ID}.json").read_text())
+ assert [p["queue_item_id"] for p in kept["points"]] == [records[0].queue_item_id]
+
+
+def test_a_server_that_cannot_calibrate_fails_the_run_before_any_step(
+ setup: tuple[Path, Path], # noqa: F811 - fixture
+ isolated_runner: None, # noqa: F811 - fixture
+) -> None:
+ manifest_path, _ = setup
+ reason = "Calibration measures GPU memory, and this machine generates on cpu."
+ (manifest_path.parent / "code" / "calibration-unavailable").write_text(reason)
+ gpu = FakeGpu()
+ run_dir = runner.new_run(manifest_path, [], [], calibrate=True)
+
+ with pytest.raises(CalibrationError, match=f"the server cannot calibrate: {reason}"):
+ runner.run(run_dir, gpu_factory=lambda _: gpu.gpu(), export=_export)
+
+ assert load_records(run_dir) == []
+ info = load_run_info(run_dir)
+ assert (info.status, info.calibration_exports) == ("failed", [])
diff --git a/tests/family_e2e/test_cli.py b/tests/family_e2e/test_cli.py
index 8031024ab2..6aa8f0dcc7 100644
--- a/tests/family_e2e/test_cli.py
+++ b/tests/family_e2e/test_cli.py
@@ -16,6 +16,7 @@ from scripts.family_e2e.__main__ import UsageError, _resolve_run, main
from scripts.family_e2e.gpu_memory import Adapter
from scripts.family_e2e.records import RUN_INFO_FILE, RunInfo, load_run_info, write_run_info
from scripts.family_e2e.runner import HEARTBEAT_FILE, now_iso, process_identity
+from tests.family_e2e.test_records import make_run_info
REPO_ROOT = Path(__file__).parents[2]
CHILD_TIMEOUT_S = 60.0
@@ -158,6 +159,73 @@ def test_stop_kills_the_runner_tree_but_no_process_whose_pid_was_reused(
runner_process.wait()
+def test_stop_saves_the_calibration_store_its_killed_server_left(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # No runner left a heartbeat to wait for.
+ monkeypatch.setattr(cli, "STOP_HEARTBEAT_WAIT_S", 0.0)
+ run_id = "20261017-000000-box"
+ run_dir = tmp_path / "data" / "runs" / run_id
+ run_dir.mkdir(parents=True)
+ write_run_info(
+ run_dir, make_run_info(run_id, profile="box", status="running").model_copy(update={"calibrate": True})
+ )
+ store_dir = tmp_path / "data" / "scratch-roots" / f"{run_id}-default" / "databases" / "working_memory"
+ store_dir.mkdir(parents=True)
+ store = b'{"schema_version": 1, "points": ["window"]}'
+ (store_dir / "0123456789abcdef.json").write_bytes(store)
+ (store_dir / "0123456789abcdef.json.lock").write_bytes(b"")
+
+ assert main(["stop", str(run_dir)]) == 0
+
+ info = load_run_info(run_dir)
+ # Saved under the mark `stop` set first, which stays.
+ assert info.status == "stopped"
+ assert [(e.lifetime, e.source, e.device_class_id, e.status) for e in info.calibration_exports] == [
+ (1, "store_file", "0123456789abcdef", None)
+ ]
+ assert (run_dir / info.calibration_exports[0].export).read_bytes() == store
+ assert not store_dir.exists()
+
+
+def test_a_stop_that_cannot_save_the_store_marks_the_run_stopped_and_keeps_the_root(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(cli, "STOP_HEARTBEAT_WAIT_S", 0.0)
+ run_id = "20261017-000000-box"
+ run_dir = tmp_path / "data" / "runs" / run_id
+ run_dir.mkdir(parents=True)
+ write_run_info(
+ run_dir,
+ make_run_info(run_id, profile="box", status="running", arms=("default", "patched")).model_copy(
+ update={"calibrate": True}
+ ),
+ )
+ roots = tmp_path / "data" / "scratch-roots"
+ kept_root = roots / f"{run_id}-default"
+ store_file = kept_root / "databases" / "working_memory" / "0123456789abcdef.json"
+ store_file.parent.mkdir(parents=True)
+ store = b'{"schema_version": 1, "points": ["window"]}'
+ store_file.write_bytes(store)
+ # The other arm's server had recorded no store yet; with nothing to save, its root goes.
+ (roots / f"{run_id}-patched" / "databases").mkdir(parents=True)
+ # A file where the run's calibration/ directory goes: the copy raises, as on a full disk.
+ (run_dir / "calibration").write_text("")
+
+ assert main(["stop", str(run_dir)]) == 2
+
+ info = load_run_info(run_dir)
+ assert (info.status, info.calibration_exports) == ("stopped", [])
+ assert info.finished_at is not None
+ captured = capsys.readouterr()
+ assert f"{run_id} stopped; continue with" in captured.out
+ assert "could not save the calibration store" in captured.err
+ assert f"kept the scratch root {kept_root} with it" in captured.err
+ # The only copy of the lifetime's windows, for `resume` to save.
+ assert store_file.read_bytes() == store
+ assert not (roots / f"{run_id}-patched").exists()
+
+
@pytest.mark.platform_independent
def test_the_tool_imports_neither_torch_nor_invokeai() -> None:
# A CUDA context in the client would land on the GPU it measures. In-process checks prove nothing here: the
diff --git a/tests/family_e2e/test_flow.py b/tests/family_e2e/test_flow.py
index d026540a46..e07d3128b2 100644
--- a/tests/family_e2e/test_flow.py
+++ b/tests/family_e2e/test_flow.py
@@ -253,7 +253,7 @@ def test_run_survives_a_server_crash_retries_foreign_load_and_resumes(
base="fake",
type="main",
format="checkpoint",
- variant=None,
+ variant="normal",
hash="blake3:fakehash",
source=None,
)
diff --git a/tests/family_e2e/test_graphs.py b/tests/family_e2e/test_graphs.py
index 5703c95c29..84f916d205 100644
--- a/tests/family_e2e/test_graphs.py
+++ b/tests/family_e2e/test_graphs.py
@@ -21,6 +21,22 @@ def _batch(image_name: str = "upload-1.png", seed: int = 1234, reverse: bool = F
return {"graph": {"id": "g", "nodes": nodes, "edges": []}, "data": data, "origin": "o", "destination": "gallery"}
+def test_the_model_keys_are_the_models_the_server_finds_in_the_nodes() -> None:
+ """What the calibrate route takes the identities of: identifiers in node fields, nested ones included."""
+ batch = _batch()
+ nodes = batch["graph"]["nodes"]
+ nodes["metadata"] = {"id": "metadata", "type": "core_metadata", "model": MAIN, "t5_encoder": {**LORA, "key": "enc"}}
+ # Neither counts on the server: a mapping without a hash, and a config inside an identifier.
+ nodes["other"] = {
+ "id": "other",
+ "type": "other",
+ "value": {"key": "no-hash", "name": "No hash", "base": "sdxl", "type": "main"},
+ "loaded": {**MAIN, "key": "outer", "source_config": {**LORA, "key": "inner"}},
+ }
+
+ assert prepare_batch(batch, {}, {}).model_keys == {"main-key", "lora-key", "enc", "outer"}
+
+
def test_prepare_disables_the_cache_on_every_node_and_runs_once() -> None:
original = _batch()
prepared = prepare_batch(original, {"vae": "vae-key"}, {})
diff --git a/tests/family_e2e/test_references.py b/tests/family_e2e/test_references.py
index ebb1f2caa0..39e2c88875 100644
--- a/tests/family_e2e/test_references.py
+++ b/tests/family_e2e/test_references.py
@@ -5,7 +5,7 @@ from pathlib import Path
import numpy as np
import pytest
-from scripts.family_e2e.records import Record, append_record, write_run_info
+from scripts.family_e2e.records import Record, append_record, load_run_info, write_run_info
from scripts.family_e2e.references import AcceptError, accept, load_reference
from tests.family_e2e.test_records import MB, make_record, make_run_info, write_png
@@ -60,6 +60,16 @@ def test_accept_refuses_runs_with_ab_arms(tmp_path: Path) -> None:
assert not (tmp_path / "references").exists()
+def test_accept_refuses_a_calibration_run(tmp_path: Path) -> None:
+ """The probe changes time and VRAM, so a calibration run's results never become references."""
+ run_dir = _run(tmp_path, [make_record(CASE, rep=0)])
+ write_run_info(run_dir, load_run_info(run_dir).model_copy(update={"calibrate": True}))
+
+ with pytest.raises(AcceptError, match="is a calibration run"):
+ accept(tmp_path, run_dir, None)
+ assert not (tmp_path / "references").exists()
+
+
def test_accept_writes_nothing_when_one_requested_case_has_no_valid_image(tmp_path: Path) -> None:
records = [
make_record(CASE, rep=0),
diff --git a/tests/family_e2e/test_report.py b/tests/family_e2e/test_report.py
index 0ed154f563..b3f022b11e 100644
--- a/tests/family_e2e/test_report.py
+++ b/tests/family_e2e/test_report.py
@@ -15,6 +15,7 @@ from scripts.family_e2e.records import (
Residency,
Thresholds,
append_record,
+ load_run_info,
write_run_info,
)
from scripts.family_e2e.references import accept
@@ -344,6 +345,22 @@ def test_previous_run_is_the_latest_earlier_one_of_the_profile_with_the_case(tmp
assert not any(run_id in report for run_id in ("20261002-", "20261004-"))
+def test_a_calibration_run_is_never_the_previous_run(tmp_path: Path) -> None:
+ """The probe changes time and VRAM, so a calibration run in between is passed over."""
+ current = "20261003-000000-rtx4090"
+ _write_run(tmp_path, "20261001-000000-rtx4090", _case_records("20261001-000000-rtx4090", totals=(20.0,) * 3))
+ calibration = _write_run(
+ tmp_path, "20261002-000000-rtx4090", _case_records("20261002-000000-rtx4090", totals=(5.0,) * 3)
+ )
+ write_run_info(calibration, load_run_info(calibration).model_copy(update={"calibrate": True}))
+ run_dir = _write_run(tmp_path, current, _case_records(current))
+
+ result = write_report(tmp_path, run_dir)
+
+ assert _summary(result)[CASE][4] == "**-50.0%**"
+ assert "20261002-000000-rtx4090" not in result.report_html.read_text(encoding="utf-8")
+
+
def test_runs_of_other_profiles_are_never_read_but_an_unreadable_run_of_this_one_is_noted(tmp_path: Path) -> None:
current = "20261003-000000-rtx4090"
_write_run(tmp_path, "20261001-000000-rtx4090", _case_records("20261001-000000-rtx4090", totals=(20.0,) * 3))
@@ -351,7 +368,7 @@ def test_runs_of_other_profiles_are_never_read_but_an_unreadable_run_of_this_one
# starts like this run's.
for run_id in ("20261002-000000-rtx4090-vae", "20261002-060000-rtx4090"):
(tmp_path / "runs" / run_id).mkdir()
- (tmp_path / "runs" / run_id / "run.json").write_text(json.dumps({"calibrate": False}))
+ (tmp_path / "runs" / run_id / "run.json").write_text(json.dumps({"field_of_a_later_tool": False}))
run_dir = _write_run(tmp_path, current, _case_records(current))
result = write_report(tmp_path, run_dir)
diff --git a/tests/family_e2e/test_runner.py b/tests/family_e2e/test_runner.py
index 3680e298c9..cee8e13c28 100644
--- a/tests/family_e2e/test_runner.py
+++ b/tests/family_e2e/test_runner.py
@@ -2,18 +2,22 @@ import errno
import json
import os
import socket
+import sqlite3
import subprocess
import sys
+import threading
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from pathlib import Path
+from typing import BinaryIO
import psutil
import pytest
import yaml
-from scripts.family_e2e import runner, server
+import scripts.family_e2e.__main__ as cli
+from scripts.family_e2e import calibration, runner, server
from scripts.family_e2e.__main__ import main
from scripts.family_e2e.gpu_memory import Adapter, MemoryTrace, ProcessUsage, UnsupportedPlatformError
from scripts.family_e2e.manifest import DEFAULT_ARM, Manifest
@@ -480,6 +484,301 @@ def test_a_runner_refuses_and_keeps_heartbeat_and_scratch_root_while_a_left_serv
assert runner.is_alive(surviving_server)
[email protected]("failure", ["survives the kill", "kill refused"])
+def test_stop_keeps_the_run_while_a_recorded_process_survives_the_kill(
+ killed_run: Path,
+ surviving_server: list[float],
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ failure: str,
+) -> None:
+ write_run_info(killed_run, load_run_info(killed_run).model_copy(update={"calibrate": True}))
+ store = _scratch_file(killed_run).parent / "databases" / calibration.STORE_DIR / "0123456789abcdef.json"
+ store.parent.mkdir(parents=True)
+ store.write_text('{"points": []}')
+ _write_heartbeat(killed_run, server=surviving_server, server_launcher=surviving_server)
+
+ def kill_process(process: psutil.Process) -> None:
+ if failure == "kill refused":
+ raise psutil.AccessDenied(process.pid)
+
+ def killpg(pgid: int, sig: int) -> None:
+ if failure == "kill refused":
+ raise PermissionError(errno.EPERM, "Operation not permitted")
+
+ with monkeypatch.context() as m:
+ m.setattr(runner, "KILL_WAIT_S", 0.05)
+ m.setattr(psutil.Process, "kill", kill_process)
+ if sys.platform != "win32":
+ m.setattr(os, "killpg", killpg)
+ capsys.readouterr()
+ assert main(["stop", str(killed_run)]) == 2
+
+ cause = "the kill was refused: AccessDenied" if failure == "kill refused" else "0.05s after the kill; still running"
+ assert f"survived the kill: pid {int(surviving_server[0])} ({cause}" in capsys.readouterr().err
+ assert runner.is_alive(surviving_server)
+ # The server may still write to its scratch root and store: neither is saved nor removed.
+ assert _scratch_file(killed_run).read_text() == "left by the killed runner"
+ assert store.read_text() == '{"points": []}'
+ info = load_run_info(killed_run)
+ assert (info.status, info.calibration_exports) == ("stopped", [])
+
+ # Once the kill works, a second stop saves the store and removes the root.
+ assert main(["stop", str(killed_run)]) == 0
+ assert not runner.is_alive(surviving_server)
+ assert not _scratch_file(killed_run).exists()
+ assert [e.source for e in load_run_info(killed_run).calibration_exports] == ["store_file"]
+
+
+def test_the_heartbeat_names_the_serving_process_as_captured_at_its_start(killed_run: Path, tmp_path: Path) -> None:
+ # Once the serving process has exited, its pid can name an unrelated process that `stop` would then kill.
+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ serving = psutil.Process(process.pid)
+ captured = [process.pid, serving.create_time()]
+ session = runner._Session(killed_run, runner.load_run_manifest(load_run_info(killed_run)), _fake_gpu("Fake"), None)
+ with open(tmp_path / "console.log", "wb") as console:
+ session.server = server.ServerProcess(
+ process, console, tmp_path / "server.log", "http://127.0.0.1:1", serving, [], "", None
+ )
+ process.kill()
+ process.wait()
+
+ session.heartbeat()
+
+ assert runner.read_heartbeat(killed_run)["server"] == captured
+
+
+class _ServerStarting(Exception):
+ pass
+
+
+def _launchable_server(run_dir: Path) -> None:
+ """Gives the killed run a server that `launch_server` starts: one that sleeps and never answers."""
+ code, template = run_dir.parents[2] / "code", run_dir.parents[2] / "template"
+ (code / "scripts" / "invokeai-web.py").write_text("import time\ntime.sleep(60)\n")
+ (code / "invokeai").mkdir()
+ (code / "invokeai" / "__init__.py").write_text("")
+ (template / "databases").mkdir()
+ sqlite3.connect(template / "databases" / "invokeai.db").close()
+
+
+def _run_lock_held(run_dir: Path, lock_file: Callable[[BinaryIO, bool], None]) -> bool:
+ """Whether a holder keeps `run.lock`: a fresh handle is refused it."""
+ with open(run_dir / runner.RUN_LOCK_FILE, "a+b") as f:
+ try:
+ lock_file(f, True)
+ except OSError:
+ return True
+ lock_file(f, False)
+ return False
+
+
+def test_a_runner_records_the_server_launcher_before_it_waits_for_the_server_to_start(
+ killed_run: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # On POSIX a runner killed while its server starts leaves the server running: what heartbeat.json names by then
+ # is all `stop` and `resume` find it by. The status check, the spawn and that record share one hold of the run
+ # lock, so a stop's mark comes before the check or after the record; a stop's lock polls are too coarse to show it.
+ _launchable_server(killed_run)
+ seen: list[tuple[object, object]] = []
+ lock_file, raise_unless_running = runner._lock_file, runner._raise_unless_running
+ server_spawned = runner._Session.server_spawned
+ holds = 0
+ # Per status check and per record: the hold of the run lock it ran in, and whether the lock was held.
+ checks: list[tuple[int, bool]] = []
+ records: list[tuple[int, bool]] = []
+
+ def counted_lock_file(f: BinaryIO, lock: bool) -> None:
+ nonlocal holds
+ lock_file(f, lock)
+ holds += lock
+
+ def checked_status(run_dir: Path) -> None:
+ checks.append((holds, _run_lock_held(run_dir, lock_file)))
+ raise_unless_running(run_dir)
+
+ def recorded_launcher(session: runner._Session, pid: int) -> None:
+ records.append((holds, _run_lock_held(session.run_dir, lock_file)))
+ server_spawned(session, pid)
+
+ def wait_for_port(process: subprocess.Popen[bytes], *args: object) -> int:
+ seen.append((runner.read_heartbeat(killed_run).get("server_launcher"), runner.process_identity(process.pid)))
+ raise _ServerStarting
+
+ monkeypatch.setattr(runner, "_lock_file", counted_lock_file)
+ monkeypatch.setattr(runner, "_raise_unless_running", checked_status)
+ monkeypatch.setattr(runner._Session, "server_spawned", recorded_launcher)
+ monkeypatch.setattr(server, "_wait_for_port", wait_for_port)
+ with pytest.raises(_ServerStarting):
+ runner.run(killed_run, gpu_factory=_fake_gpu)
+
+ [(recorded, launched)] = seen
+ assert launched is not None
+ assert recorded == launched
+ [(record_hold, held)] = records
+ assert held
+ # The last status check before the record ran in the record's hold.
+ assert [check for check in checks if check[0] <= record_hold][-1] == (record_hold, True)
+
+
+class _RecordingFailed(Exception):
+ pass
+
+
+def test_a_server_whose_launcher_cannot_be_recorded_is_dead_before_the_run_lock_is_let_go(
+ killed_run: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # Unrecorded, the server is in no heartbeat: a stop that took the lock once it is let go would miss the server.
+ _launchable_server(killed_run)
+ spawned: list[psutil.Process] = []
+ alive_at_release: list[bool] = []
+ lock_file, spawn_in_job = runner._lock_file, server.spawn_in_job
+
+ def watched_lock_file(f: BinaryIO, lock: bool) -> None:
+ if not lock and spawned and not alive_at_release:
+ alive_at_release.append(not _gone(spawned[0]))
+ lock_file(f, lock)
+
+ def spawn(*args: object, **kwargs: object) -> tuple[subprocess.Popen[bytes], object]:
+ process, job = spawn_in_job(*args, **kwargs)
+ spawned.append(psutil.Process(process.pid))
+ return process, job
+
+ def recording_fails(session: runner._Session, pid: int) -> None:
+ raise _RecordingFailed
+
+ monkeypatch.setattr(runner, "_lock_file", watched_lock_file)
+ monkeypatch.setattr(server, "spawn_in_job", spawn)
+ monkeypatch.setattr(runner._Session, "server_spawned", recording_fails)
+ with pytest.raises(_RecordingFailed):
+ runner.run(killed_run, gpu_factory=_fake_gpu)
+
+ assert len(spawned) == 1
+ assert alive_at_release == [False]
+
+
[email protected]("arrives", ["before the spawn", "during the spawn"])
+def test_a_stop_that_meets_the_server_spawn_kills_the_server_before_it_removes_the_scratch_root_or_none_starts(
+ killed_run: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], arrives: str
+) -> None:
+ # `stop` captured the runner's tree before the runner spawned its server. On POSIX that server runs in a session of
+ # its own and outlives the runner's kill, unless the heartbeat `stop` reads names it. The stop runs on a thread of
+ # this process, which is also the runner, so its kill of the runner is left out.
+ _launchable_server(killed_run)
+ spawned: list[psutil.Process] = []
+ alive_at_cleanup: dict[int, bool] = {}
+ stop_codes: list[int] = []
+ stop_thread: threading.Thread | None = None
+ settled = threading.Event() # the stop has finished, or waits for the run lock
+
+ def stop() -> None:
+ try:
+ stop_codes.append(main(["stop", str(killed_run)]))
+ finally:
+ settled.set()
+
+ def stop_arrives() -> None:
+ nonlocal stop_thread
+ stop_thread = threading.Thread(target=stop)
+ stop_thread.start()
+ assert settled.wait(CHILD_TIMEOUT_S)
+
+ lock_file, kill_recorded, remove_tree = runner._lock_file, cli.kill_recorded, cli.remove_tree
+ verify_interpreter, spawn_in_job = server.verify_interpreter, server.spawn_in_job
+
+ def watched_lock_file(f: BinaryIO, lock: bool) -> None:
+ try:
+ lock_file(f, lock)
+ except OSError:
+ if threading.current_thread() is stop_thread:
+ settled.set()
+ raise
+
+ def remove_after_kill(path: Path) -> list[str]:
+ alive_at_cleanup.update((p.pid, not _gone(p)) for p in spawned)
+ return remove_tree(path)
+
+ def verify_then_stop(*args: object) -> str:
+ result = verify_interpreter(*args)
+ if arrives == "before the spawn":
+ stop_arrives()
+ return result
+
+ def spawn_then_stop(*args: object, **kwargs: object) -> tuple[subprocess.Popen[bytes], object]:
+ process, job = spawn_in_job(*args, **kwargs)
+ spawned.append(psutil.Process(process.pid))
+ if arrives == "during the spawn":
+ stop_arrives()
+ return process, job
+
+ def wait_for_port(*args: object) -> int:
+ if stop_thread is not None:
+ stop_thread.join(CHILD_TIMEOUT_S)
+ raise _ServerStarting
+
+ monkeypatch.setattr(runner, "_lock_file", watched_lock_file)
+ monkeypatch.setattr(
+ cli, "kill_recorded", lambda processes: kill_recorded([p for p in processes if p[0] != "runner"])
+ )
+ monkeypatch.setattr(cli, "remove_tree", remove_after_kill)
+ monkeypatch.setattr(server, "verify_interpreter", verify_then_stop)
+ monkeypatch.setattr(server, "spawn_in_job", spawn_then_stop)
+ monkeypatch.setattr(server, "_wait_for_port", wait_for_port)
+ capsys.readouterr()
+ with pytest.raises((runner.RunStopped, _ServerStarting)):
+ runner.run(killed_run, gpu_factory=_fake_gpu)
+ assert stop_thread is not None
+ stop_thread.join(CHILD_TIMEOUT_S)
+
+ assert stop_codes == [0]
+ # A server spawned before the stop's mark is in the heartbeat the stop reads and is gone before its scratch root
+ # goes; none is spawned after the mark.
+ assert len(spawned) == (1 if arrives == "during the spawn" else 0)
+ assert {p.pid: alive_at_cleanup.get(p.pid) for p in spawned} == {p.pid: False for p in spawned}
+ assert ("killed server_launcher" in capsys.readouterr().out) == bool(spawned)
+ assert not _scratch_file(killed_run).exists()
+ assert load_run_info(killed_run).status == "stopped"
+
+
+class _SavingStore(Exception):
+ pass
+
+
[email protected]("kill", ["works", "has no effect"])
+def test_a_resumed_calibration_run_saves_a_kept_store_only_once_the_left_server_is_stopped(
+ killed_run: Path, surviving_server: list[float], monkeypatch: pytest.MonkeyPatch, kill: str
+) -> None:
+ # The killed runner's calibration store in its scratch root; its server may still be writing to it.
+ write_run_info(killed_run, load_run_info(killed_run).model_copy(update={"calibrate": True}))
+ store = _scratch_file(killed_run).parent / "databases" / calibration.STORE_DIR / "0123456789abcdef.json"
+ store.parent.mkdir(parents=True)
+ store.write_text('{"points": []}')
+ _write_heartbeat(killed_run, server=surviving_server, server_launcher=surviving_server)
+ server_running_at_save: list[bool] = []
+
+ def read_store_files(root: Path) -> list:
+ server_running_at_save.append(runner.is_alive(surviving_server))
+ raise _SavingStore
+
+ monkeypatch.setattr(calibration, "read_store_files", read_store_files)
+ if kill == "works":
+ with pytest.raises(_SavingStore):
+ runner.run(killed_run, gpu_factory=_fake_gpu)
+ assert server_running_at_save == [False]
+ else:
+ with monkeypatch.context() as m:
+ m.setattr(runner, "KILL_WAIT_S", 0.05)
+ m.setattr(psutil.Process, "kill", lambda process: None)
+ if sys.platform != "win32":
+ m.setattr(os, "killpg", lambda pgid, sig: None)
+ with pytest.raises(RunnerError, match="cannot be stopped"):
+ runner.run(killed_run, gpu_factory=_fake_gpu)
+ # A refusal leaves the kept store where the server writes it, for `stop` or the next resume to save.
+ assert server_running_at_save == []
+ assert store.read_text() == '{"points": []}'
+ assert load_run_info(killed_run).calibration_exports == []
+
+
def _gone(process: psutil.Process) -> bool:
try:
return not process.is_running() or process.status() == psutil.STATUS_ZOMBIE
diff --git a/tests/fixtures/working_memory_calibration.py b/tests/fixtures/working_memory_calibration.py
index 8bcf26d239..64d189e5c5 100644
--- a/tests/fixtures/working_memory_calibration.py
+++ b/tests/fixtures/working_memory_calibration.py
@@ -8,16 +8,18 @@ them, without measuring anything.
import threading
from collections.abc import Mapping
from pathlib import Path
-from typing import Any, Callable, Optional
+from typing import Any, Callable, Literal, Optional
import pytest
import torch
from invokeai.app.services.session_queue import session_queue_default
from invokeai.app.services.working_memory_calibration.working_memory_calibration_default import (
+ DeviceMemory,
SettingValue,
WorkingMemoryCalibrationService,
)
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_plan import VaeDtypes
from invokeai.app.services.working_memory_calibration.working_memory_calibration_store import CalibrationStore
from invokeai.backend.working_memory.estimate import WorkingMemoryTerm
from invokeai.backend.working_memory.fingerprint import DeviceClass, Environment
@@ -25,12 +27,13 @@ from invokeai.backend.working_memory.probe import MeasuredWindow, Reason
GPU = torch.device("cuda:0")
GPU_CLASS = DeviceClass(vendor="nvidia", name="Test GPU 24GB", total_mib=24564, backend="cuda", arch="sm_89")
+GPU_VAE_DTYPES = VaeDtypes(standalone_flux="bf16", z_image_pipeline="bf16", sdnq_quantized_vae=lambda config: False)
OTHER_CLASS = DeviceClass(vendor="amd", name="Test GPU 16GB", total_mib=16304, backend="hip", arch="gfx1200")
def fake_environment(device: torch.device, settings: Mapping[str, SettingValue]) -> Environment:
hard = {"torch": "2.7", **{f"setting.{key}": str(value) for key, value in settings.items()}}
- return Environment(hard=hard, soft={"driver": "1.0", "os": "test"})
+ return Environment(hard=hard, soft={"driver": "1.0", "os_build": "test"})
class HeldEnqueue:
@@ -55,13 +58,26 @@ def calibration_service(
root: Path,
devices: Optional[Callable[[], list[torch.device]]] = None,
device_class: DeviceClass = GPU_CLASS,
+ environment_for: Callable[[torch.device, Mapping[str, SettingValue]], Environment] = fake_environment,
+ untiled_decode_reservation: Optional[Callable[[str, int, int, str, torch.device], int]] = None,
+ device_memory: Optional[Callable[[torch.device], DeviceMemory]] | Literal["whole card"] = "whole card",
+ vae_dtypes: VaeDtypes = GPU_VAE_DTYPES,
) -> WorkingMemoryCalibrationService:
- """A service storing under `root`; not started (call `start(invoker)`)."""
+ """A service storing under `root`; not started (call `start(invoker)`, and `stop(invoker)` once it registered
+ the user-fit provider estimates ask). What the cache can give a calibration's lock defaults to the whole card, with
+ nothing outside torch; None asks the model cache of the invoker's model manager, as the service does. The VAE
+ dtypes default to those of a GPU with bf16 under `precision: auto`."""
+ extra = {} if untiled_decode_reservation is None else {"untiled_decode_reservation": untiled_decode_reservation}
return WorkingMemoryCalibrationService(
CalibrationStore(root / "working_memory"),
generation_devices=devices or (lambda: [GPU]),
device_class_for=lambda device: device_class,
- environment_for=fake_environment,
+ environment_for=environment_for,
+ device_memory=(lambda device: DeviceMemory(device_class.total_mib * 2**20, 0))
+ if device_memory == "whole card"
+ else device_memory,
+ vae_dtypes=lambda device, models_path: vae_dtypes,
+ **extra,
)
diff --git a/tests/test_build_shipped_working_memory.py b/tests/test_build_shipped_working_memory.py
new file mode 100644
index 0000000000..7b789a51c0
--- /dev/null
+++ b/tests/test_build_shipped_working_memory.py
@@ -0,0 +1,689 @@
+"""scripts/working_memory/build_shipped.py: calibration store exports into shipped working-memory points and fits."""
+
+import json
+import platform as stdlib_platform
+import shutil
+from collections.abc import Callable, Iterator
+from importlib.util import module_from_spec, spec_from_file_location
+from pathlib import Path
+
+import pytest
+import torch
+
+from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import (
+ CalibrationDeviceClass,
+ CalibrationEnvironment,
+ CalibrationPoint,
+ CalibrationRun,
+ CalibrationStoreFile,
+)
+from invokeai.backend.util import nvml
+from invokeai.backend.working_memory import coefficients, fragmentation
+from invokeai.backend.working_memory import platform as working_memory_platform
+from invokeai.backend.working_memory.coefficients import CoefficientEntry, MeasuredPoint, load_data
+from invokeai.backend.working_memory.fingerprint import DeviceClass, Environment, environment_for
+from invokeai.backend.working_memory.fragmentation import Measurement
+from invokeai.backend.working_memory.platform import platform_for
+from invokeai.backend.working_memory.probe import CounterDelta
+from invokeai.backend.working_memory.spec import import_estimator_modules
+from scripts.working_memory.build_shipped import (
+ DATA_DIR,
+ RAISE_NOTE,
+ BuildError,
+ bound_violations,
+ build_points,
+ export_paths,
+ main,
+ merge_points,
+ point_identity,
+ point_platform,
+ refit,
+)
+
+CUDA0 = torch.device("cuda", 0)
+HOST_OS = working_memory_platform._host_os
+"""Bound at import, before the suite's fixture pins it."""
+SYS_PLATFORMS = {"windows": "win32", "linux": "linux"}
+RTX_4090 = DeviceClass(vendor="nvidia", name="NVIDIA GeForce RTX 4090", total_mib=24564, backend="cuda", arch="sm_89")
+RX_9060_XT = DeviceClass(vendor="amd", name="AMD Radeon RX 9060 XT", total_mib=16304, backend="hip", arch="gfx1200")
+SETTINGS = {"pytorch_cuda_alloc_conf": None, "attention_type": "sdpa"}
+GIB = 2**30
+
+
+def _decode(px: int, **changes: object) -> dict[str, object]:
+ return {"operation": "decode", "height": px, "width": px, "tile": None, "batch_size": 1, "score_matrix_bytes": 0,
+ "dtype": "bf16"} | changes # fmt: skip
+
+
+def _delta(value: int) -> CounterDelta:
+ return CounterDelta(baseline=GIB, peak=GIB + value, offset=0, delta=value)
+
+
+def _window(
+ item: int,
+ features: dict,
+ demand: int,
+ *,
+ valid=True,
+ fit_eligible=True,
+ reasons=(),
+ version=2,
+ estimator="vae.flux2",
+ allocated: int | None = None,
+):
+ delta = _delta(demand)
+ return {
+ "run_id": "calibration-run",
+ "queue_item_id": item,
+ "node_id": "l2i",
+ "node_type": "flux2_vae_decode",
+ "model_key": "flux2-vae",
+ "device": "cuda:0",
+ "estimator": estimator,
+ "version": version,
+ "features": features,
+ "terms": (),
+ "reservation_bytes": demand,
+ "source": "shipped:conv_backend=cudnn,allocator=native",
+ "reservation_applied_bytes": demand + GIB,
+ "driver": delta,
+ "reserved": delta,
+ "allocated": None if allocated is None else _delta(allocated),
+ "demand_bytes": demand,
+ "method": "windows-d3dkmt",
+ "verified": True,
+ "resident_fraction": 1.0 if fit_eligible else 0.5,
+ "co_locked_models": [],
+ "segments": 1,
+ "duration_s": 0.5,
+ "valid": valid,
+ "fit_eligible": fit_eligible,
+ "reasons": list(reasons),
+ }
+
+
+def machine(monkeypatch: pytest.MonkeyPatch):
+ """Scripts this process as a GPU machine: `as_machine(hip, os)` makes `environment_for` and `platform_for` read
+ the build and OS given, with the native allocator or the allocator configuration given."""
+
+ def as_machine(hip: str | None, os_name: str, alloc_conf: str | None = None) -> None:
+ if alloc_conf is None:
+ monkeypatch.delenv("PYTORCH_CUDA_ALLOC_CONF", raising=False)
+ else:
+ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", alloc_conf)
+ monkeypatch.setattr(torch.version, "hip", hip)
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_allocator_backend", lambda: "native")
+ monkeypatch.setattr(nvml, "driver_version", lambda: None)
+ # Both `environment_for` and `platform_for` read the OS from `sys.platform`; the suite's pin is lifted.
+ monkeypatch.setattr(working_memory_platform, "_host_os", HOST_OS)
+ monkeypatch.setattr(working_memory_platform.sys, "platform", SYS_PLATFORMS[os_name])
+ monkeypatch.setattr(stdlib_platform, "platform", lambda: "Test-1.0")
+
+ return as_machine
+
+
+def _export(path: Path, device_class: DeviceClass, windows: list[dict], *, os_fact: bool = True) -> Path:
+ """A store as the scripted machine records it; without `os_fact`, as a server that records no OS did."""
+ recorded = environment_for(CUDA0, SETTINGS)
+ hard = recorded.hard if os_fact else {key: value for key, value in recorded.hard.items() if key != "os"}
+ env = CalibrationEnvironment.of(Environment(hard=hard, soft=recorded.soft))
+ store = CalibrationStoreFile(
+ schema_version=1,
+ device_class=CalibrationDeviceClass.of(device_class),
+ runs=[
+ CalibrationRun(
+ run_id="calibration-run",
+ model_key="flux2-vae",
+ model_hash=None,
+ user_id="system",
+ created_at="2026-10-17T00:00:00Z",
+ env_id=env.id,
+ )
+ ],
+ points=[CalibrationPoint(**window, env_id=env.id) for window in windows],
+ envs=[env],
+ )
+ path.write_text(store.model_dump_json(indent=2), encoding="utf-8")
+ return path
+
+
+def exports(tmp_path: Path, machine) -> tuple[Path, Path]:
+ """A Linux RTX 4090 with two repetitions of a 1024px decode, an invalid and a partially resident window, and a
+ Windows RX 9060 XT on MIOpen's native allocator, saved as a family E2E run saves them, next to a status file."""
+ calibration = tmp_path / "calibration"
+ calibration.mkdir()
+ (calibration / "20261017-120000-box-1-status.json").write_text('{"available": true}', encoding="utf-8")
+ machine(None, "linux")
+ nvidia = _export(
+ calibration / f"20261017-120000-box-1-{RTX_4090.id}.json",
+ RTX_4090,
+ [
+ _window(1, _decode(1024), 4_600_000_000),
+ _window(2, _decode(512), 1_150_000_000),
+ _window(3, _decode(1024), 4_700_000_000),
+ _window(4, _decode(1024), 9 * GIB, valid=False, fit_eligible=False, reasons=["oom"]),
+ _window(5, _decode(1024), 9 * GIB, fit_eligible=False, reasons=["partial_residency"]),
+ ],
+ )
+ machine("7.14.0", "windows")
+ amd = _export(
+ calibration / f"20261017-120000-box-2-{RX_9060_XT.id}.json",
+ RX_9060_XT,
+ [_window(1, _decode(1024), 10_900_000_000)],
+ )
+ return nvidia, amd
+
+
+def entries():
+ return [entry for data in coefficients.shipped_data().values() for entry in data.coefficients]
+
+
+def specs():
+ return import_estimator_modules()
+
+
+def test_valid_fit_eligible_windows_become_points_at_their_largest_repetition(exports, entries, specs) -> None:
+ build = build_points(exports, specs, entries)
+
+ assert build.skipped == {"invalid": 1, "not fit-eligible": 1}
+ got = sorted((p.device, p.platform, p.features["height"], p.measured_bytes, p.method) for p in build.points)
+ amd, nvidia = f"AMD Radeon RX 9060 XT ({RX_9060_XT.id})", f"NVIDIA GeForce RTX 4090 ({RTX_4090.id})"
+ assert got == [
+ (amd, {"conv_backend": "miopen", "allocator": "native", "os": "windows"}, 1024, 10_900_000_000,
+ "probe_demand"),
+ (nvidia, {"conv_backend": "cudnn", "allocator": "native"}, 512, 1_150_000_000, "probe_demand"),
+ (nvidia, {"conv_backend": "cudnn", "allocator": "native"}, 1024, 4_700_000_000, "probe_demand"),
+ ] # fmt: skip
+ largest = next(p for p in build.points if p.measured_bytes == 4_700_000_000)
+ assert "largest of 2 valid fit-eligible windows" in largest.provenance
+ assert "item 3" in largest.provenance and "NVIDIA GeForce RTX 4090" in largest.provenance
+ assert exports[0].name in largest.provenance
+
+
+def test_the_same_store_given_twice_counts_once(exports, entries, specs) -> None:
+ once = build_points(exports, specs, entries)
+ twice = build_points([*exports, exports[0]], specs, entries)
+
+ assert twice.points == once.points
+ assert twice.spreads == once.spreads
+ assert twice.skipped["duplicate"] == 5
+
+
+ "hip, os_name", [(None, "linux"), (None, "windows"), ("7.14.0", "windows"), ("7.14.0", "linux")]
+)
+def test_a_points_platform_is_the_one_platform_for_gives_on_the_measuring_machine(
+ hip, os_name, machine, tmp_path: Path, entries, specs
+) -> None:
+ machine(hip, os_name)
+ device_class = RX_9060_XT if hip else RTX_4090
+ export = _export(tmp_path / "export.json", device_class, [_window(1, _decode(1024), 4 * GIB)])
+ measuring_machine = point_platform(platform_for(CUDA0), entries)
+ # The build runs on another OS than the export was recorded on.
+ machine(hip, "linux" if os_name == "windows" else "windows")
+
+ [point] = build_points([export], specs, entries).points
+
+ assert point.platform == measuring_machine
+ # Only MIOpen's native allocator has an entry of its own per OS; elsewhere a point names no OS.
+ assert ("os" in point.platform) == (hip is not None and os_name == "windows")
+
+
[email protected]("hip, os_name", [(None, "linux"), ("7.14.0", "windows")])
+def test_a_point_of_an_estimator_keyed_by_no_platform_names_no_platform(
+ hip, os_name, machine, tmp_path: Path, entries, specs
+) -> None:
+ # MOSS-Image's denoise entry reads alike on every platform; ROCm on Windows names even its OS for a VAE point.
+ machine(hip, os_name)
+ features = {"height": 1024, "width": 1024, "text_tokens": 64, "score_matrix_bytes": 0, "dequant_bytes": 0}
+ window = _window(1, features, 4 * GIB, estimator="moss_image.denoise", version=1)
+ export = _export(tmp_path / "export.json", RX_9060_XT if hip else RTX_4090, [window])
+
+ [point] = build_points([export], specs, entries).points
+
+ assert point.platform == {}
+
+
+def test_a_window_whose_environment_lacks_a_platform_fact_is_left_out(machine, tmp_path: Path, entries, specs) -> None:
+ machine(None, "linux")
+ complete = _export(tmp_path / "complete.json", RTX_4090, [_window(1, _decode(1024), 4 * GIB)])
+ without_os = _export(tmp_path / "old.json", RTX_4090, [_window(2, _decode(512), GIB)], os_fact=False)
+
+ build = build_points([complete, without_os], specs, entries)
+
+ assert [p.features["height"] for p in build.points] == [1024]
+ assert build.skipped == {"no platform facts": 1}
+
+
+ "window, message",
+ [
+ pytest.param(_window(1, _decode(1024), 4 * GIB, version=1), "version 1, the registered estimator is version 2",
+ id="stale-version"),
+ pytest.param(_window(1, {"operation": "decode", "height": 1024}, 4 * GIB), "cannot evaluate its features",
+ id="features-the-terms-cannot-read"),
+ ],
+) # fmt: skip
+def test_an_export_the_estimator_cannot_price_is_refused(
+ window, message, machine, tmp_path: Path, entries, specs
+) -> None:
+ machine(None, "linux")
+ export = _export(tmp_path / "export.json", RTX_4090, [window])
+
+ with pytest.raises(BuildError, match=message):
+ build_points([export], specs, entries)
+
+
+def test_a_directory_stands_for_its_exports_in_lifetime_order(tmp_path: Path) -> None:
+ for name in ("run-10-0123456789abcdef.json", "run-2-0123456789abcdef.json", "run-2-status.json", "notes.json"):
+ (tmp_path / name).write_text("{}", encoding="utf-8")
+
+ assert [p.name for p in export_paths([tmp_path])] == ["run-2-0123456789abcdef.json", "run-10-0123456789abcdef.json"]
+
+
+def _probe_point(measured_bytes: int) -> MeasuredPoint:
+ return MeasuredPoint(
+ estimator="vae.flux2",
+ version=2,
+ platform=CUDNN_NATIVE,
+ features=_decode(1024),
+ measured_bytes=measured_bytes,
+ method="probe_demand",
+ device="NVIDIA GeForce RTX 4090",
+ provenance="-",
+ )
+
+
+ "shipped, new, kept", [(5 * GIB, 4 * GIB, 5 * GIB), (4 * GIB, 5 * GIB, 5 * GIB)], ids=["lower", "higher"]
+)
+def test_a_remeasured_point_keeps_the_larger_demand(shipped: int, new: int, kept: int) -> None:
+ data = coefficients.shipped_data()["vae.json"]
+ with_point = {"vae.json": data.model_copy(update={"points": [*data.points, _probe_point(shipped)]})}
+
+ merged = merge_points(with_point, [_probe_point(new)])["vae.json"]
+
+ same = [p for p in merged.points if p.method == "probe_demand"]
+ assert [p.measured_bytes for p in same] == [kept]
+ assert len(merged.points) == len(with_point["vae.json"].points)
+
+
+def shipped_checks(monkeypatch: pytest.MonkeyPatch) -> Iterator[Callable[[Path], None]]:
+ """`check(data_dir)` runs the data test's checks on `data_dir` instead of the shipped files."""
+
+ def check(data_dir: Path) -> None:
+ data = load_data(data_dir)
+ monkeypatch.setattr(coefficients, "shipped_data", lambda: data)
+ coefficients.shipped_coefficients.cache_clear()
+ path = Path(__file__).parent / "backend" / "working_memory" / "test_shipped_coefficients.py"
+ spec = spec_from_file_location("shipped_checks_on_built_data", path)
+ assert spec is not None and spec.loader is not None
+ checks = module_from_spec(spec)
+ spec.loader.exec_module(checks)
+ built = [point for file in data.values() for point in file.points]
+ assert sorted(map(repr, checks.ALL_POINTS)) == sorted(map(repr, built)), "the checks read the built data"
+ checks.test_every_data_file_parses_and_declares_coefficients()
+ checks.test_every_coefficient_entry_resolves_for_its_spec_on_a_measured_platform()
+ checks.test_every_fitted_value_is_decided_by_an_in_fit_point()
+ checks.test_every_fitted_value_is_the_shipped_fit_of_its_points()
+ checks.test_a_stand_in_is_a_whole_line_its_fresh_process_points_cannot_fit()
+ checks.test_the_out_of_fit_points_are_the_listed_ones()
+ checks.test_every_listed_upper_bound_exception_is_a_shipped_point_that_needs_it()
+ checks.test_a_point_bound_is_never_looser_than_the_default()
+ for estimator in checks.SPECS.values():
+ checks.test_every_estimator_has_coefficients_on_every_measured_platform(estimator)
+ checks.test_the_os_only_matters_where_an_entry_names_it(estimator)
+ checks.test_an_unmeasured_platform_is_priced_as_the_measured_one_at_least_and_says_so(estimator)
+ for point in checks.ALL_POINTS:
+ checks.test_every_measured_point_is_bounded_by_its_estimate(point)
+
+ try:
+ yield check
+ finally:
+ # Resolved from the built data; the next caller must resolve from the shipped files again.
+ coefficients.shipped_coefficients.cache_clear()
+
+
+MIB = 2**20
+CUDNN_NATIVE = {"conv_backend": "cudnn", "allocator": "native"}
+MIOPEN_EXPANDABLE_WINDOWS = {"conv_backend": "miopen", "allocator": "expandable", "os": "windows"}
+
+
+def _carried(data_dir: Path, estimator: str, platform: dict[str, str]) -> dict[str, float]:
+ [entry] = [
+ e for e in load_data(data_dir)["vae.json"].coefficients if e.estimator == estimator and e.platform == platform
+ ]
+ assert entry.values is not None
+ return dict(entry.values)
+
+
+def _data_copy(tmp_path: Path) -> tuple[Path, dict[str, bytes]]:
+ data_dir = tmp_path / "data"
+ shutil.copytree(DATA_DIR, data_dir)
+ return data_dir, {path.name: path.read_bytes() for path in data_dir.iterdir()}
+
+
+def _files(data_dir: Path) -> dict[str, bytes]:
+ return {path.name: path.read_bytes() for path in data_dir.iterdir()}
+
+
+def test_written_data_holds_the_points_and_passes_the_shipped_data_checks(
+ exports, tmp_path: Path, shipped_checks, capsys
+) -> None:
+ data_dir, before = _data_copy(tmp_path)
+
+ assert main([*map(str, exports), "--data-dir", str(data_dir)]) == 0
+ assert _files(data_dir) == before, "nothing written without --write"
+ preview = capsys.readouterr().out
+ # The 4.7 GB decode lies above the cuDNN line all FLUX.2 points share with vae.sd3: it is refitted.
+ shipped_k = _carried(DATA_DIR, "vae.sd3", CUDNN_NATIVE)["k_decode_bf16"]
+ assert f"vae.sd3 {CUDNN_NATIVE} k_decode_bf16 {shipped_k:.0f} ->" in preview
+
+ # A run's calibration/ directory stands for its exports.
+ assert main([str(exports[0].parent), "--data-dir", str(data_dir), "--write"]) == 0
+ assert capsys.readouterr().out.splitlines()[1:] == preview.splitlines()[1:] + [f"wrote {data_dir / 'vae.json'}"]
+ built = load_data(data_dir)["vae.json"]
+ probe_points = [p for p in built.points if p.method == "probe_demand"]
+ assert sorted(p.measured_bytes for p in probe_points) == [1_150_000_000, 4_700_000_000, 10_900_000_000]
+ assert _carried(data_dir, "vae.sd3", CUDNN_NATIVE)["k_decode_bf16"] > shipped_k
+ shipped_checks(data_dir)
+
+ # Built again from the same exports, the data does not change.
+ written = _files(data_dir)
+ assert main([*map(str, exports), "--data-dir", str(data_dir), "--write"]) == 0
+ assert "no changes" in capsys.readouterr().out
+ assert _files(data_dir) == written
+
+
+def _sd_decode(px: int, dtype: str) -> dict[str, object]:
+ """An SD1/SDXL decode as the RX 9060 XT recorded it: the ROCm SDPA guard chunks the mid-block scores."""
+ return {"operation": "decode", "height": px, "width": px, "tile": None, "dtype": dtype, "upcast_weight_bytes": 0,
+ "score_matrix_bytes": 285212672 if px == 512 else GIB, "vae_class": "AutoencoderKL"} # fmt: skip
+
+
+def _amd_export(tmp_path: Path, machine, windows: list[dict]) -> Path:
+ machine("7.14.0", "windows", "expandable_segments:True")
+ return _export(tmp_path / f"20261017-160953-box-1-{RX_9060_XT.id}.json", RX_9060_XT, windows)
+
+
+def test_new_readings_below_the_shipped_ones_add_points_without_moving_their_line(
+ tmp_path: Path, machine, capsys
+) -> None:
+ """The RX 9060 XT's fp16 SDXL probe decodes, all below the shipped expandable-segments fp16 points (460 MiB under
+ 940 MiB at 512px): lower bounds only, they neither choose the line nor are capped by it."""
+ windows = [
+ _window(item, _sd_decode(px, "fp16"), mib * MIB, estimator="vae.sd")
+ for item, (px, mib) in enumerate([(512, 460), (768, 1120), (1024, 1960), (1280, 2880)], start=1)
+ ]
+ export = _amd_export(tmp_path, machine, windows)
+ data_dir, _ = _data_copy(tmp_path)
+ shipped = _carried(DATA_DIR, "vae.sd3", MIOPEN_EXPANDABLE_WINDOWS)
+
+ assert main([str(export), "--data-dir", str(data_dir), "--write"]) == 0
+
+ captured = capsys.readouterr()
+ assert "line " not in captured.out
+ assert "not written" not in captured.err
+ assert _carried(data_dir, "vae.sd3", MIOPEN_EXPANDABLE_WINDOWS) == shipped
+ written = [p for p in load_data(data_dir)["vae.json"].points if p.method == "probe_demand"]
+ assert sorted(p.measured_bytes // MIB for p in written) == [460, 1120, 1960, 2880]
+
+
+MIOPEN_NATIVE = {"conv_backend": "miopen", "allocator": "native"}
+
+
+ "per_pixel, shipped_k", [(2000, 7200), (8000, 8400)], ids=["below-the-stand-in", "above-the-stand-in"]
+)
+def test_probe_points_on_a_stand_in_line_raise_it_but_never_lower_it(
+ per_pixel: int, shipped_k: int, tmp_path: Path, machine, shipped_checks
+) -> None:
+ """fp16 SDXL probe decodes on Linux with MIOpen's native allocator, a line no fresh-process point measures: its
+ stand-in of 7200 bytes per pixel stays the floor until one does. Warm windows below it would fit 2100."""
+ machine("7.14.0", "linux")
+ windows = [
+ _window(item, _sd_decode(px, "fp16"), per_pixel * px * px, estimator="vae.sd")
+ for item, px in enumerate([512, 1024], start=1)
+ ]
+ export = _export(tmp_path / f"20261017-160953-box-1-{RX_9060_XT.id}.json", RX_9060_XT, windows)
+ data_dir, _ = _data_copy(tmp_path)
+ shipped = _carried(DATA_DIR, "vae.sd3", MIOPEN_NATIVE)
+ assert (shipped["k_decode_fp16"], shipped["b_decode_fp16"]) == (7200, 0)
+
+ assert main([str(export), "--data-dir", str(data_dir), "--write"]) == 0
+
+ carried = _carried(data_dir, "vae.sd3", MIOPEN_NATIVE)
+ assert (carried["k_decode_fp16"], carried["b_decode_fp16"]) == (shipped_k, 0)
+ assert carried == shipped | {"k_decode_fp16": shipped_k}
+ [entry] = [
+ e
+ for e in load_data(data_dir)["vae.json"].coefficients
+ if e.estimator == "vae.sd3" and e.platform == MIOPEN_NATIVE
+ ]
+ assert {"k_decode_fp16", "b_decode_fp16"} <= set(entry.stand_ins)
+ assert (RAISE_NOTE in entry.provenance) == (shipped_k > 7200)
+ shipped_checks(data_dir)
+
+
+def _miopen_native_point(
+ estimator: str, features: dict[str, object], measured_bytes: int, method: str
+) -> MeasuredPoint:
+ return MeasuredPoint(
+ estimator=estimator,
+ version=2,
+ platform=MIOPEN_NATIVE,
+ features=features,
+ measured_bytes=measured_bytes,
+ method=method,
+ device="AMD Radeon RX 9060 XT",
+ provenance="-",
+ )
+
+
+def _refit_shipped(points: list[MeasuredPoint], specs, carrier: str) -> CoefficientEntry:
+ """The shipped data with `points` merged and refitted, checked against every point's bounds; returns `carrier`'s
+ entry for MIOpen's native allocator off Windows."""
+ after = refit(merge_points(coefficients.shipped_data(), points))
+ assert bound_violations(after, specs) == []
+ [entry] = [
+ entry
+ for file in after.values()
+ for entry in file.coefficients
+ if entry.estimator == carrier and entry.platform == MIOPEN_NATIVE
+ ]
+ return entry
+
+
+def test_a_stand_in_stays_until_its_fresh_process_points_span_the_sizes_of_a_fit(specs) -> None:
+ """One fresh-process fp16 decode at 1024px and a warm probe at 512px: together they span 4x, but the fresh size
+ alone pins nothing at 512px, where a cold run's base can lie far above the warm window. The fit through them
+ (7010 bytes per pixel) would undercut the 7200 stand-in."""
+ fresh = _miopen_native_point("vae.sd", _sd_decode(1024, "fp16"), 7_000_000_000, "demand_peak")
+ probe = _miopen_native_point("vae.sd", _sd_decode(512, "fp16"), 1_000_000_000, "probe_demand")
+
+ entry = _refit_shipped([fresh, probe], specs, "vae.sd3")
+
+ assert entry.values is not None
+ assert (entry.values["k_decode_fp16"], entry.values["b_decode_fp16"]) == (7200, 0)
+ assert {"k_decode_fp16", "b_decode_fp16"} <= set(entry.stand_ins)
+
+
+def test_a_raised_stand_in_takes_the_larger_base_too(specs) -> None:
+ """CogView4's bf16 decode stand-in off Windows: 13720 bytes per pixel and a 14 MiB base. Probe decodes with a
+ 1 GiB base and 10000 bytes per pixel fit 10500 and 1076 MiB: the slope stays, the base rises."""
+ probes = [
+ _miopen_native_point("vae.cogview4", _sd_decode(px, "bf16"), GIB + 10_000 * px * px, "probe_demand")
+ for px in (512, 1024)
+ ]
+
+ entry = _refit_shipped(probes, specs, "vae.cogview4")
+
+ assert entry.values is not None
+ assert (entry.values["k_decode_bf16"], entry.values["b_decode_bf16"]) == (13720, 1076 * MIB)
+ assert {"k_decode_bf16", "b_decode_bf16"} <= set(entry.stand_ins)
+ assert RAISE_NOTE in entry.provenance
+
+
+def _fp32_1280(first_mib: int, largest_mib: int) -> list[dict]:
+ """Two fp32 SDXL decodes at 1280px in one long-running server, allocated flat at the first one's bytes."""
+ return [
+ _window(1, _sd_decode(1280, "fp32"), first_mib * MIB, estimator="vae.sd", allocated=first_mib * MIB),
+ _window(2, _sd_decode(1280, "fp32"), largest_mib * MIB, estimator="vae.sd", allocated=first_mib * MIB),
+ ]
+
+
+def test_a_raise_that_pushes_fresh_process_points_over_their_bound_is_refused_even_with_consent(
+ tmp_path: Path, machine, capsys
+) -> None:
+ """The RX 9060 XT's fp32 SDXL decode at 1280px: allocated stays at 8020 MiB while reserved grows to 13000 MiB. The
+ line that covers it over-reserves the fresh-process points of the same line beyond 1.3x."""
+ export = _amd_export(tmp_path, machine, _fp32_1280(8020, 13000))
+ data_dir, before = _data_copy(tmp_path)
+
+ for consent in ([], ["--accept-fragmentation"]):
+ assert main([str(export), "--data-dir", str(data_dir), "--write", *consent]) == 1
+ captured = capsys.readouterr()
+ assert "[2 windows, MiB 8020, 13000; max/first 1.62]" in captured.out
+ assert "reserved MiB 8020, 13000 while allocated MiB 8020, 8020" in captured.out
+ assert "decode_fp32: k 5988 -> " in captured.out and "1 flagged as fragmentation" in captured.out
+ assert "the bounds of these points reject the result" in captured.err
+ violation = "vae.sd-miopen,expandable,windows-decode-fp32-1280x1280-scores-RX9060XT-demand_peak: reserves"
+ assert violation in captured.err
+ assert _files(data_dir) == before
+
+
+def test_two_owners_attempts_with_one_id_are_measured_apart(tmp_path: Path, machine, entries, specs) -> None:
+ """The two fp32 1280px decodes of `_fp32_1280`, each another owner's attempt "1": reserved grew from one to the
+ other around flat allocations, which within one attempt is fragmentation. Across two it is not."""
+ windows = [
+ {**window, "run_id": run_id} for window, run_id in zip(_fp32_1280(8020, 9300), ("run-a", "run-b"), strict=True)
+ ]
+ export = _amd_export(tmp_path, machine, windows)
+ store = json.loads(export.read_text(encoding="utf-8"))
+ [run] = store["runs"]
+ store["runs"] = [
+ {**run, "run_id": run_id, "user_id": owner, "attempt_id": "1", "attempt_steps": 1}
+ for run_id, owner in (("run-a", "admin-a"), ("run-b", "admin-b"))
+ ]
+ export.write_text(json.dumps(store), encoding="utf-8")
+
+ build = build_points([export], specs, entries)
+
+ assert [spread.fragmented for spread in build.spreads.values()] == [False]
+
+
+def test_a_raise_on_a_fragmentation_flagged_point_needs_consent(
+ tmp_path: Path, machine, shipped_checks, capsys
+) -> None:
+ """A smaller growth (8020 to 9300 MiB reserved at flat allocated bytes) that raises the line within the bounds."""
+ export = _amd_export(tmp_path, machine, _fp32_1280(8020, 9300))
+ data_dir, before = _data_copy(tmp_path)
+ shipped_k = _carried(DATA_DIR, "vae.sd3", MIOPEN_EXPANDABLE_WINDOWS)["k_decode_fp32"]
+
+ assert main([str(export), "--data-dir", str(data_dir), "--write"]) == 1
+ captured = capsys.readouterr()
+ assert "warning: fragmentation?" in captured.out and "1 flagged as fragmentation" in captured.out
+ assert "--accept-fragmentation" in captured.err
+ assert _files(data_dir) == before
+
+ assert main([str(export), "--data-dir", str(data_dir), "--write", "--accept-fragmentation"]) == 0
+ assert _carried(data_dir, "vae.sd3", MIOPEN_EXPANDABLE_WINDOWS)["k_decode_fp32"] > shipped_k
+ shipped_checks(data_dir)
+
+
+RTX_4060_TI_16GB = DeviceClass(
+ vendor="nvidia", name="NVIDIA GeForce RTX 4060 Ti", total_mib=16380, backend="cuda", arch="sm_89"
+)
+RTX_4060_TI_8GB = DeviceClass(
+ vendor="nvidia", name="NVIDIA GeForce RTX 4060 Ti", total_mib=8188, backend="cuda", arch="sm_89"
+)
+
+
+def test_cards_of_one_name_are_separate_points_and_spreads(
+ tmp_path: Path, machine, entries, specs, shipped_checks, capsys
+) -> None:
+ """The 16 GB and the 8 GB RTX 4060 Ti report one name. A FLUX.2 decode at 1024px on each allocates 4.2 GB and
+ reserves 4.2 GB on the one card, 4.7 GB on the other: two cards' readings, not a server's cache growing around the
+ same tensors. The 4.7 GB raises the cuDNN line, and nothing flags it as fragmentation."""
+ machine(None, "linux")
+ sixteen = _export(
+ tmp_path / f"20261017-120000-box-1-{RTX_4060_TI_16GB.id}.json",
+ RTX_4060_TI_16GB,
+ [_window(1, _decode(1024), 4_200_000_000, allocated=4_200_000_000)],
+ )
+ eight = _export(
+ tmp_path / f"20261018-120000-box-1-{RTX_4060_TI_8GB.id}.json",
+ RTX_4060_TI_8GB,
+ [_window(1, _decode(1024), 4_700_000_000, allocated=4_200_000_000)],
+ )
+ data_dir, _ = _data_copy(tmp_path)
+
+ assert main([str(sixteen), str(eight), "--data-dir", str(data_dir), "--write"]) == 0
+
+ captured = capsys.readouterr()
+ assert "fragmentation" not in captured.out + captured.err
+ assert "raised, 2 new points on it" in captured.out
+ expected = [
+ (f"NVIDIA GeForce RTX 4060 Ti ({RTX_4060_TI_16GB.id})", 4_200_000_000),
+ (f"NVIDIA GeForce RTX 4060 Ti ({RTX_4060_TI_8GB.id})", 4_700_000_000),
+ ]
+ written = load_data(data_dir)["vae.json"].points
+ assert sorted((p.device, p.measured_bytes) for p in written if p.method == "probe_demand") == sorted(expected)
+ shipped_checks(data_dir)
+ build = build_points([sixteen, eight], specs, entries)
+ assert sorted((p.device, p.measured_bytes) for p in build.points) == sorted(expected)
+ assert sorted(spread.demand for spread in build.spreads.values()) == [(4_200_000_000,), (4_700_000_000,)]
+
+
+ "reserved, allocated, fragmented",
+ [
+ pytest.param((8020, 13000), (8020, 8020), True, id="reserved-grows-allocated-flat"),
+ # The RTX 4090's first fp16 512px decode: allocated grows with reserved, a first-run effect.
+ pytest.param((576, 736, 736), (450, 609, 609), False, id="both-grow"),
+ pytest.param((1120, 1020, 1020), (864, 864, 864), False, id="the-first-is-the-largest"),
+ pytest.param((2887, 3160, 3160), (2887, 2887, 2887), False, id="growth-below-ten-percent"),
+ ],
+)
+def test_a_measurement_is_flagged_as_fragmentation_only_when_reserved_grows_around_flat_allocations(
+ reserved, allocated, fragmented
+) -> None:
+ measurement = Measurement(
+ line="decode_fp32", pixels=1280**2, demand=reserved, reserved=reserved, allocated=allocated
+ )
+ assert fragmentation.fragmented([measurement]) == [fragmented]
+
+
+def test_a_size_whose_one_window_stands_out_from_the_smaller_sizes_is_flagged_without_any_growth(
+ tmp_path: Path, machine, entries, specs, capsys
+) -> None:
+ """The RX 9060 XT's fp32 SDXL decodes of one attempt (real reserved and allocated bytes): 576px and 832px reserve
+ 1.11 and 1.10 times what they allocate, the one fully resident 1216px window 1.47 times, 1.33 times their median.
+ It has no repetition to grow over, so only the ratio rule can flag it -- as the user fit does."""
+ windows = [
+ _window(item, _sd_decode(px, "fp32"), reserved, estimator="vae.sd", allocated=allocated)
+ for item, (px, reserved, allocated) in enumerate(
+ [
+ (576, 1887436800, 1702840320),
+ (576, 1887436800, 1702840320),
+ (832, 3900702720, 3552839680),
+ (832, 3900702720, 3552839680),
+ (1216, 11135877120, 7589201920),
+ ],
+ start=1,
+ )
+ ]
+ export = _amd_export(tmp_path, machine, windows)
+
+ build = build_points([export], specs, entries)
+
+ flagged = {point.features["width"] for point in build.points if build.spreads[point_identity(point)].fragmented}
+ assert flagged == {1216}
+ main([str(export), "--data-dir", str(DATA_DIR)])
+ assert "warning: fragmentation? vae.sd" in capsys.readouterr().out