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(working-memory): reserve Z-Image denoise working memory from measured lines (#9919)

Alexander Eichhorn4ef128bf4413
diff --git a/docs/src/content/docs/contributing/new-model-integration.mdx b/docs/src/content/docs/contributing/new-model-integration.mdx
index a9a85fe520..68ec7136e8 100644
--- a/docs/src/content/docs/contributing/new-model-integration.mdx
+++ b/docs/src/content/docs/contributing/new-model-integration.mdx
@@ -605,7 +605,7 @@ Packages are discovered automatically. A directory of node modules without an `_
...
```
- Report progress with `context.util.sd_step_callback(state, BaseModelType.NewModel)`; it renders previews through the architecture's `LatentSpaceFacet`. The denoise node is also where these are checked: interrupts (`context.util.is_canceled()`), inpainting, img2img through `denoising_start`, and a working-memory estimate passed to `model_on_device(working_mem_bytes=<int>)`, or `working_memory=` for an estimator that declares an `EstimatorSpec`, as MOSS-Image's (`invokeai/backend/moss_image/working_memory.py`) does; see the VAE step below and the [model manager](/development/architecture/model-manager/).
+ Report progress with `context.util.sd_step_callback(state, BaseModelType.NewModel)`; it renders previews through the architecture's `LatentSpaceFacet`. The denoise node is also where these are checked: interrupts (`context.util.is_canceled()`), inpainting, img2img through `denoising_start`, and a working-memory estimate passed to `model_on_device()`: `working_memory=` from an estimator that declares an `EstimatorSpec`, so that calibration runs measure the forward (the Z-Image denoise's is in `invokeai/backend/z_image/denoise_working_memory.py`, MOSS-Image's in `invokeai/backend/moss_image/working_memory.py`), or `working_mem_bytes=<int>` for a plain reservation. A model locked while the transformer is, such as a ControlNet adapter, reserves the estimate's `reservation_bytes` with `working_mem_bytes=`. See the VAE step below and the [model manager](/development/architecture/model-manager/).
4. **VAE encode and decode** (`vae/new_model_image_to_latents.py`, `vae/new_model_latents_to_image.py`)
diff --git a/docs/src/content/docs/development/Architecture/model-manager.mdx b/docs/src/content/docs/development/Architecture/model-manager.mdx
index 23cf30de8f..1918e791a6 100644
--- a/docs/src/content/docs/development/Architecture/model-manager.mdx
+++ b/docs/src/content/docs/development/Architecture/model-manager.mdx
@@ -1053,25 +1053,32 @@ with vae_info.model_on_device(working_memory=estimate) as (_, vae):
An estimator that declares an `EstimatorSpec` returns a `WorkingMemoryEstimate` (`invokeai/backend/working_memory/estimate.py`): the reservation, the terms it adds up to, the features it was evaluated from, and the source of its coefficients, which `model_on_device()` logs at debug level. A plain byte count goes in as `working_mem_bytes=<int>` instead; never both. The cache never reserves less than `device_working_mem_gb`.
-To write such an estimator (`invokeai/backend/util/vae_working_memory.py` has five for the VAEs, `invokeai/backend/moss_image/working_memory.py` one for a transformer forward):
+To write such an estimator (`invokeai/backend/util/vae_working_memory.py` has five for the VAEs, `invokeai/backend/z_image/denoise_working_memory.py` and `invokeai/backend/moss_image/working_memory.py` one each for a transformer forward, the Z-Image and the MOSS-Image denoise's):
- Register an `EstimatorSpec` at module import, and list the module in `ESTIMATOR_MODULES` (`working_memory/spec.py`); the data test fails on a module that declares a spec without being listed.
-- Split the estimator in two. The impure part reads the model and the device and records every runtime decision (tile, the dtype the operation runs in, score-matrix bytes) as a feature, and refuses a dtype the spec has no line for with a `ValueError` naming the estimator, dtype and platform. The pure `terms(features, values)` turns features and coefficient values into terms, building fitted terms with `WorkingMemoryTerm.fitted(...)`. The public function returns `SPEC.estimate(features, device)`.
+- Split the estimator in two. The impure part reads the model and the device and records every runtime decision (tile, the dtype the operation runs in, score-matrix bytes, a quantized model's dequantization transient) as a feature, and refuses a dtype the spec has no line for with a `ValueError` naming the estimator, dtype and platform. The pure `terms(features, values)` turns features and coefficient values into terms, building fitted terms with `WorkingMemoryTerm.fitted(...)`. The public function returns `SPEC.estimate(features, device)`.
- 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.
+- Declare the line the fitted terms price on with `line=` (a function returning a `fit.Line`): the suffix that names the line's coefficients, the operation's size on its x-axis, whether a measurement of these features fits the line, and how point ids label them. Every estimator declares it and nothing defaults it, so a new estimator cannot inherit another's line, and with it which of its measurements fit. The VAE estimators declare the AutoencoderKL convolution line in output pixels (`fit.convolution_line`), the Z-Image denoise one in attended tokens. The fit subtracts nothing from a point's demand, so a line admits only measurements whose demand is the line's alone: an operation with a term of its own on top of the line (a tile, an in-place upcast, a ControlNet's hints, regional prompting's bias, LoRAs, a dequantization or fp8 cast transient, a materialized score matrix the estimate adds rather than takes the larger of) bounds its estimate but fits nothing.
+- Opt in with `user_calibrated=True` where a user's calibration may move the estimator: the five VAE estimators do. An estimator that does not is shipped-fit only; a calibration run still records its windows. The calibration summary and plan are built on pixel lines (they key sizes by `width` and `height`), so an estimator on another line, such as the Z-Image denoise's in tokens, must not opt in until they key sizes by `Line.size`.
- 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`. `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.
+ - `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 for the VAE lines, the legacy constants for the Z-Image denoise's. A fit describes the card it was measured on, not the platforms it stands in for.
- 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. 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, 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.
+- 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, takes fresh-process points from the point files a calibration script writes (`--points`), 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 values, never hand-tune them. Fitted terms price a line per operation and dtype: `k_<suffix>` bytes per unit of the line's size plus a base of `b_<suffix>` bytes. The AutoencoderKL estimators price their convolutions on lines in output pixels (`k_<operation>_<dtype>`), the Z-Image denoise its forward on lines in attended tokens (`k_denoise_<dtype>`).
+ - `working_memory/fit.py` fits each line on the in-fit points its estimators' `line` admits, of every estimator that resolves to the entry: for the convolution lines the untiled single-sample points, leaving out those 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. The shipped values add a 5% margin and round up: the slope to a whole byte per unit of size, the base to a whole MiB.
+ - A point whose demand is not its line's alone sets `in_fit: false`: it fits nothing and gets only the lower bound. That is a point measured in a regime its platform does not run (CUDA with the math attention kernel forced), and a fit-grid forward whose features its estimator's `line` does not admit, such as one whose build materializes the score matrix. The test lists every such point.
- 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.
+ - A value on no line its entry carries is hand-set, and only a spec keyed by no platform trait may carry one (`hand_set_values` in `fit.py`): a keyed spec prices lines whose every value is half of one, so its value off one fails the data test. MOSS-Image's `k_token` is one, bytes per attended token (the image's tokens at 1/16 of each side plus the prompt's), whose entry ships no base for its `token` line. Its points still decide it and bound it from both sides; only the fit check leaves it out.
+ - Every value an entry carries is a stand-in, a `legacy` constant, 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.
+ - An entry marked `legacy` carries hand-set constants rather than a fit: no point decides them and `fit.py` does not reproduce them, though its estimator's points still bound its estimates. `LEGACY_ENTRIES` in the data test lists the entries, by estimator and platform, allowed to be legacy, so a fit has to remove its entry there too. The builder replaces an entry's legacy values with the fit of its points once they fit every line it carries and each line has a point that holds the upper bound, a fresh-process one: probe windows alone never replace hand-set values. An entry whose platform they do not measure stays legacy.
+- The Z-Image denoise (`denoise.z_image`, `data/denoise.json`) prices its activations as `k_denoise_<dtype>` bytes per attended token plus a base of `b_denoise_<dtype>`. The lines are fitted on fresh-process points of `scripts/calibrate_z_image_working_memory.py` (a random-init transformer of the real geometry with 2 main blocks, bf16, fp16 and fp32 from 512 to 2048 px): an RTX 4090 with the native allocator and with `cudaMallocAsync`, and an RX 9060 XT under ROCm 10 with AOTriton's fused kernels, with expandable segments and with the native allocator on Windows (an entry of its own). In a running server the real 30-block Z-Image Turbo measured below its estimate on the RTX 4090 under the native allocator and `cudaMallocAsync` (bf16) and on the RX 9060 XT with expandable segments (an int8 build). ROCm with the native allocator off Windows has no points and keeps the legacy constants, 0.25 MiB per token and a 1 GiB base for every dtype; they cover bf16 and fp16 but not fp32 from 1440 px up, whose measured lines are steeper. Every other unmeasured platform (XPU, MPS, CPU, cuDNN with expandable segments, MIOpen under `hipMallocAsync`) is priced as a measured one, and the entries it borrows floor every value at the same legacy constants there (`unmeasured_floor`), so no unmeasured platform reserves less than the legacy formula.
+ - The line admits only the plain forward, measured with a fused attention kernel: every analytic term zero and no attention mask, read off the estimator's terms, so a term added later takes the forwards it prices out of the fit. A point whose score matrix is materialized fits nothing, because the score term is an upper bound, and fitting the demand less the term would leave the line low by the term's slack, short for a build of the same platform keys that runs a fused kernel. A ControlNet's hints (n + 4 hint-sized tensors) and a forced math kernel's score matrix are checked against measurements of their own in `tests/app/invocations/test_z_image_denoise_working_memory.py`.
+ - An fp8-stored transformer reserves the per-forward cast of its weights as a term of its own (`util/fp8.py`, `peak_fp8_cast_transient_bytes`): the largest layer's float8 weights at the compute dtype, twice for a scaled checkpoint weight. The legacy base covers that cast too, so wherever the legacy constants price, such a model reserves it twice.
+ - Denoise lines are shipped-fit only: `denoise.z_image` is not `user_calibrated`.
#### Measuring estimates: the probe
@@ -1161,15 +1168,16 @@ The reset, export and summary routes act on the current device class unless `dev
`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.
+- Only the estimators that opt in (`EstimatorSpec.user_calibrated`, the five VAE estimators) take part. The windows of any other, a Z-Image denoise's say, stay in the store and count among the windows that fit no line, but no user line is fitted on them, none moves their estimates, the summary lists none of their lines, and they size no plan: denoise lines are shipped-fit only.
+- 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 its estimator's `line` admits it (for the convolution lines: 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`.
+- `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 its size there (output pixels) as `EstimatorSpec.line` places it. 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.
+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`), over the windows of the estimators a user calibration moves only, 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 4d830c4e55..412c8d0e1b 100644
--- a/docs/src/content/docs/development/Guides/family-e2e.mdx
+++ b/docs/src/content/docs/development/Guides/family-e2e.mdx
@@ -100,17 +100,19 @@ On a machine the tool does not run on, an administrator takes the export of a se
### 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]
+uv run --no-sync python -m scripts.working_memory.build_shipped <data_dir>/runs/<run_id>/calibration [more exports or directories] [--points FILE ...] [--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`.
+`scripts/working_memory/build_shipped.py` reads the exports, and the point files `--points` names, 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`.
+- **Point files.** A calibration script such as `scripts/calibrate_z_image_working_memory.py` writes one JSON object per line: a `MeasuredPoint`'s fields (`estimator`, `version`, `platform`, `features`, `measured_bytes`, `method`, `device`, `provenance`) and whatever else it keeps, such as raw readings, which the builder ignores. These are fresh-process measurements, so they cap a line as well as raise it; a `probe_demand` record is refused. A check's record (a forced math kernel, a ControlNet, more blocks) says `in_fit: false`, and so does a fit-grid forward whose features its estimator's `line` does not admit (a score matrix the build's SDPA kernel materializes): it tests an analytic term or an assumption rather than the line, so it ships as an out-of-fit point that bounds its estimate from below only, and the data test's `OUT_OF_FIT` has to list it. It stays beside a fit point with the same features rather than replacing it, since being in the fit is part of what makes two points one measurement. A record's platform may name the OS anywhere and keeps it only where an entry names it. A measurement given twice keeps its larger reading.
- **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:
+- **Merge and fit.** A point joins the data file that declares the estimator's coefficients; where a point of the same measurement (card, platform, method, features and whether it is in the fit) is there, the larger of the two stays, and a remeasurement below the shipped point prints `kept shipped <bytes> over remeasured <bytes>`. 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.
+- **Legacy entries.** A `legacy` entry (hand-set values, such as the Z-Image denoise's) is replaced by its fit once the points fit every line it carries and each line has a fresh-process point, which holds the upper bound: its flag cleared, its provenance replaced by one that says it is the fit of the platform's points, its `unmeasured_floor` kept. Probe windows alone never replace hand-set values, since a warm window can read below the cold first run. The data test's `LEGACY_ENTRIES`, which lists the legacy entries by estimator and platform, then needs that entry removed. An entry the points do not fully measure keeps its values, with a `note:` line saying which lines lack a fit or a fresh-process point; its new points still have to pass their bounds against the hand-set values, which a fresh-process point well below them does not.
+- **Refusals.** An export or point of another estimator version than the registered one, features the estimator cannot evaluate, a platform `MEASURED` does not list, and a line whose points span less than twice its sizes: 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.
diff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.py
index cab698269d..1188ac8f4c 100644
--- a/invokeai/app/invocations/z_image/z_image_denoise.py
+++ b/invokeai/app/invocations/z_image/z_image_denoise.py
@@ -36,15 +36,15 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.z_image_lora_constants import Z_IMAGE_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
-from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
+from invokeai.backend.quantization.dequantizing_linear import requires_sidecar_patching
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.rectified_flow.schedule_shift import ShiftFit, time_shift
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ZImageConditioningInfo
-from invokeai.backend.util.attention import sdpa_score_matrix_bytes
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.fp8 import get_model_compute_dtype
from invokeai.backend.util.sage_attention import sage_attention_scope
+from invokeai.backend.z_image.denoise_working_memory import estimate_z_image_denoise_working_memory
from invokeai.backend.z_image.extensions.regional_prompting_extension import ZImageRegionalPromptingExtension
from invokeai.backend.z_image.text_conditioning import ZImageTextConditioning
from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
@@ -52,21 +52,8 @@ from invokeai.backend.z_image.z_image_controlnet_extension import (
ZImageControlNetExtension,
z_image_forward_with_control,
)
-from invokeai.backend.z_image.z_image_patchify_utils import SEQ_MULTI_OF
from invokeai.backend.z_image.z_image_transformer_patch import patch_transformer_for_regional_prompting
-# The transformer's width and head count, which its ControlNet adapters share: 30 heads of 128.
-Z_IMAGE_HIDDEN_SIZE = 3840
-Z_IMAGE_ATTENTION_HEADS = 30
-# Peak reserved activation bytes per attended token on a fused SDPA kernel; see `_estimate_working_memory`.
-Z_IMAGE_BYTES_PER_TOKEN = int(0.25 * 1024**2)
-
-
-def _padded(tokens: int) -> int:
- """The transformer pads the image and the caption token runs to a multiple of `SEQ_MULTI_OF` each."""
- return tokens + (-tokens) % SEQ_MULTI_OF
-
-
# The shift fit of diffusers' ZImagePipeline. 4096 image tokens is a 1024x1024 frame -- one megapixel, and where the
# reference fit ends. Extrapolated past it the shift runs away fast -- 25 at 2048px, 810 at 3072px and 103_777 at
# 4096px -- and `_get_sigmas` flattens with it. Because `denoising_start` is clipped by *index* here, the step count
@@ -268,76 +255,6 @@ class ZImageDenoiseInvocation(BaseInvocation):
sigmas.append(1.0 if t >= 1 else 0.0 if t <= 0 else time_shift(shift, t))
return sigmas
- @staticmethod
- def _estimate_working_memory(
- image_seq_len: int,
- text_seq_len: int,
- num_loras: int,
- num_control_blocks: int = 0,
- regional_attention_bias_bytes: int = 0,
- has_attention_mask: bool = False,
- device: torch.device | None = None,
- dtype: torch.dtype = torch.bfloat16,
- ) -> int:
- """Estimate peak transformer working memory (bytes) so the model cache keeps that much VRAM free.
-
- The transformer attends over one unified sequence of image and caption tokens, each run padded to a
- multiple of ``SEQ_MULTI_OF``. On a fused SDPA kernel its activations scale linearly with that sequence.
- Measured as peak reserved memory in bf16 on CUDA with a 512-token caption, by
- `scripts/calibrate_z_image_working_memory.py`: 0.99 GiB at 1024px (4608 tokens), 1.96 GiB at 1440px (8640)
- and 3.85 GiB at 2048px (16896) -- 0.22 to 0.23 MB per token, unchanged between 2 and 4 blocks, because a
- no-grad forward frees each block's intermediates. 0.25 MB per token bounds every point on its own, with
- room for the ~5% more ROCm needed on FLUX.2. The fixed base covers what does not scale with the sequence
- -- fp8 weights cast per forward, and allocator slack across steps; the caller adds the dequantization copy
- of an int8, nvfp4 or GGUF build. Conditional and unconditional
- passes run one after the other, so only the longer caption counts.
-
- Where SDPA has no fused kernel for these shapes it materializes the score matrices, and those dominate:
- on ROCm under Windows, whose fused kernels are disabled, a 1024px generation spilled 7.7 GB into shared
- system memory while this node reserved only the default working memory. ``sdpa_score_matrix_bytes`` adds
- the term only where it is really built. An attention mask narrows which fused kernels a build can use, so
- the call is told whether one is passed: regional prompting's additive bias, or the padding mask the
- ControlNet forward always builds. The plain forward passes none at batch size 1.
-
- A ControlNet adapter first runs its own blocks over a sequence of the same length and keeps one hint per
- block, alive through the main layers. Measured over the plain forward at 1024px: 3.3, 5.9 and 18.9
- hint-sized tensors (sequence x width x element size) for 1, 6 and 15 blocks, so n + 4 are charged.
- """
- GB = 1024**3
- seq_len = _padded(image_seq_len) + _padded(text_seq_len)
- estimated = seq_len * Z_IMAGE_BYTES_PER_TOKEN + int(1.0 * GB)
- estimated += regional_attention_bias_bytes
- estimated += sdpa_score_matrix_bytes(
- device=device if device is not None else TorchDevice.choose_torch_device(),
- dtype=dtype,
- num_heads=Z_IMAGE_ATTENTION_HEADS,
- head_dim=Z_IMAGE_HIDDEN_SIZE // Z_IMAGE_ATTENTION_HEADS,
- seq_len=seq_len,
- has_attn_mask=has_attention_mask,
- # The attention goes through diffusers' `dispatch_attention_fn`, which can route around torch's SDPA.
- via_diffusers_dispatch=True,
- )
- if num_control_blocks:
- estimated += (num_control_blocks + 4) * seq_len * Z_IMAGE_HIDDEN_SIZE * dtype.itemsize
- estimated += int(0.5 * num_loras * GB)
- return estimated
-
- @staticmethod
- def _regional_attention_bias_bytes(
- regional_attn_mask: torch.Tensor | None, image_seq_len: int, dtype: torch.dtype
- ) -> int:
- """What `regional_forward` allocates per positive pass for regional prompting: a boolean copy of the mask,
- the additive bias over the padded unified sequence, and the image-to-image block `torch.where` fills it
- from. The mask itself is already on the device when the estimate is taken. Measured at 1024px on CUDA: 68 MiB
- over the plain forward, against 93 MiB charged."""
- if regional_attn_mask is None:
- return 0
- mask_side = regional_attn_mask.shape[0]
- unified_seq_len = _padded(image_seq_len) + _padded(mask_side - image_seq_len)
- return (
- mask_side * mask_side + (unified_seq_len * unified_seq_len + image_seq_len * image_seq_len) * dtype.itemsize
- )
-
def _run_diffusion(self, context: InvocationContext) -> torch.Tensor:
device = TorchDevice.choose_torch_device()
inference_dtype = TorchDevice.choose_bfloat16_safe_dtype(device)
@@ -520,28 +437,23 @@ class ZImageDenoiseInvocation(BaseInvocation):
# transformer as that takes. Without it the cache reserves only `device_working_mem_gb`, which a
# build that materializes the score matrices (ROCm on Windows, MPS) overruns several times at 1024px.
regional_attn_mask = regional_extension.regional_attn_mask
- working_mem_bytes = self._estimate_working_memory(
+ working_memory = estimate_z_image_denoise_working_memory(
+ transformer_info.model,
image_seq_len=img_seq_len,
text_seq_len=max(
pos_prompt_embeds.shape[0], neg_prompt_embeds.shape[0] if neg_prompt_embeds is not None else 0
),
- num_loras=len(self.transformer.loras),
- num_control_blocks=num_control_blocks,
- regional_attention_bias_bytes=self._regional_attention_bias_bytes(
- regional_attn_mask, img_seq_len, inference_dtype
- ),
+ lora_count=len(self.transformer.loras),
+ control_blocks=num_control_blocks,
+ regional_attn_mask=regional_attn_mask,
has_attention_mask=regional_attn_mask is not None or control_model_info is not None,
device=device,
dtype=inference_dtype,
)
- # An int8_tensorwise, nvfp4 or GGUF build materializes each quantized linear's weight per forward, alive
- # alongside the activations above and invisible to them. Read from the unlocked model; zero for
- # every other build.
- working_mem_bytes += peak_dequant_transient_bytes(transformer_info.model, inference_dtype)
# Load transformer - always use base transformer, control is handled via extension
(cached_weights, transformer) = exit_stack.enter_context(
- transformer_info.model_on_device(working_mem_bytes=working_mem_bytes)
+ transformer_info.model_on_device(working_memory=working_memory)
)
# Whether LoRA has to go on as a sidecar. Asked of the loaded module tree, not the
@@ -557,9 +469,11 @@ class ZImageDenoiseInvocation(BaseInvocation):
if self.control is not None:
assert control_model_info is not None
# Locked with the same working memory: the transformer can no longer be offloaded, so an
- # adapter placed with only the default reservation would fill the room kept for the forward.
+ # adapter placed with only the default reservation would fill the room kept for the forward. A
+ # plain reservation, not a second estimate: inside the transformer's calibration window this lock
+ # is a co-lock, whose weights go into the window's offset rather than its demand.
(_, control_adapter) = exit_stack.enter_context(
- control_model_info.model_on_device(working_mem_bytes=working_mem_bytes)
+ control_model_info.model_on_device(working_mem_bytes=working_memory.reservation_bytes)
)
assert isinstance(control_adapter, ZImageControlAdapter)
diff --git a/invokeai/app/run_app.py b/invokeai/app/run_app.py
index d12fced8b3..dc39ef9aae 100644
--- a/invokeai/app/run_app.py
+++ b/invokeai/app/run_app.py
@@ -1,5 +1,9 @@
+import logging
import os
-from typing import Any
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from invokeai.app.services.config.config_default import InvokeAIAppConfig
# Suppress the HuggingFace tokenizers fork-after-parallelism warning. The Rust
# ``tokenizers`` library warms a thread pool the first time a tokenizer is used
@@ -17,20 +21,82 @@ from typing import Any
# keeps their value.
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
-# ROCm: run MIOpen's convolution-kernel search in FAST mode. The default mode benchmarks
-# every candidate kernel the first time a convolution shape is seen, which on a VAE-shaped
-# workload (many layers x spatial tiles x temporal chunks, separately per dtype) costs minutes
-# of "warm-up" per new shape set, and torch's MIOpen ``chooseAlgorithm`` falls back to a
-# *global* ``emptyCache`` whenever a candidate's workspace allocation fails - on multi-GPU
-# installs that convoys the peer device mid-step (see ``install_peer_aware_empty_cache``).
-# FAST looks the shape up in MIOpen's find-db and takes the first viable kernel otherwise;
-# with a warmed find-db the difference in kernel quality is negligible. MIOpen reads the
-# variable when it is first used, so, like the tokenizer flag, it is set at module level -
-# before torch is even imported - rather than inside ``run_app()``, so no early import can run
-# a convolution ahead of it. On
-# CUDA/CPU/MPS builds MIOpen is absent and the variable is inert. ``setdefault`` keeps an
-# explicitly exported value (e.g. ``MIOPEN_FIND_MODE=NORMAL`` to re-tune the find-db).
-os.environ.setdefault("MIOPEN_FIND_MODE", "FAST")
+
+def _default_miopen_find_mode() -> None:
+ """ROCm: run MIOpen's convolution-kernel search in FAST mode.
+
+ The default mode benchmarks every candidate kernel the first time a convolution shape is seen, which on a VAE-shaped
+ workload (many layers x spatial tiles x temporal chunks, separately per dtype) costs minutes of "warm-up" per new
+ shape set, and torch's MIOpen ``chooseAlgorithm`` falls back to a *global* ``emptyCache`` whenever a candidate's
+ workspace allocation fails - on multi-GPU installs that convoys the peer device mid-step (see
+ ``install_peer_aware_empty_cache``). FAST looks the shape up in MIOpen's find-db and takes the first viable kernel
+ otherwise; with a warmed find-db the difference in kernel quality is negligible. On CUDA/CPU/MPS builds MIOpen is
+ absent and the variable is inert. ``setdefault`` keeps an explicitly exported value (e.g.
+ ``MIOPEN_FIND_MODE=NORMAL`` to re-tune the find-db).
+ """
+ os.environ.setdefault("MIOPEN_FIND_MODE", "FAST")
+
+
+# MIOpen reads the variable when it is first used, so, like the tokenizer flag, it is set at module level - before torch
+# is even imported - rather than inside ``run_app()``, so no early import can run a convolution ahead of it.
+# `apply_server_runtime` repeats it as its first step, so that function states the whole runtime; ``setdefault`` makes
+# the repeat a no-op.
+_default_miopen_find_mode()
+
+
+def _configure_torch_environment(config: "InvokeAIAppConfig", logger: logging.Logger) -> None:
+ """What torch, HIP and MIOpen read once, when they initialize, as `config` sets it: the first part of the server's
+ runtime (`apply_server_runtime`). Must run before torch is imported, which its last step does."""
+ from invokeai.app.util.rocm_integrated_gpu import hide_integrated_gpus_on_rocm_windows
+ from invokeai.app.util.torch_cuda_allocator import (
+ apply_rocm_windows_allocator_default,
+ configure_torch_cuda_allocator,
+ )
+
+ _default_miopen_find_mode()
+
+ # Before torch is imported anywhere: HIP reads its device list once, when torch initializes it, and an explicit
+ # allocator configuration below imports torch. Runs a short child process on Windows ROCm.
+ hide_integrated_gpus_on_rocm_windows(logger)
+
+ # Configure the torch CUDA memory allocator.
+ # NOTE: It is important that this happens before torch is imported.
+ if config.pytorch_cuda_alloc_conf:
+ configure_torch_cuda_allocator(config.pytorch_cuda_alloc_conf, logger)
+ else:
+ apply_rocm_windows_allocator_default(logger)
+
+ # Decide on AOTriton's experimental attention kernels before anything can run attention: torch reads the switch
+ # once, at its first fused-kernel check, and the server already runs attention while starting up. This imports
+ # torch, so it comes after the allocator configuration.
+ from invokeai.app.util.rocm_aotriton import apply_rocm_aotriton_setting
+
+ apply_rocm_aotriton_setting(config.rocm_aotriton_experimental, config.generation_devices, logger)
+
+
+def apply_server_runtime(config: "InvokeAIAppConfig", logger: logging.Logger) -> None:
+ """Give this process the server's kernels and allocation, for a process that measures what the server runs (the
+ working-memory calibration scripts). Must run before torch is imported.
+
+ The steps, in the server's order (`run_app`), with `config`'s settings:
+
+ 1. ``MIOPEN_FIND_MODE`` defaults to FAST.
+ 2. On ROCm under Windows, integrated GPUs are hidden from HIP.
+ 3. The allocator: ``pytorch_cuda_alloc_conf``, or without one the platform's default (expandable segments for ROCm
+ on Windows).
+ 4. AOTriton's experimental attention kernels, as ``rocm_aotriton_experimental`` decides.
+ 5. The monkeypatches, the ROCm SDPA guard among them, with ``attention_backend`` (`apply_monkeypatches`).
+
+ Between 4 and 5 the server imports its invocations, logs its device and finds its port. The invocations' modules bind
+ library functions there, before the monkeypatches: one that binds a patched function by name at import keeps the
+ unpatched one in the server (PiD's ``scaled_dot_product_attention``), where a module imported after this function
+ binds the patched one.
+ """
+ _configure_torch_environment(config, logger)
+
+ from invokeai.app.util.startup_utils import apply_monkeypatches
+
+ apply_monkeypatches(config.attention_backend)
def get_app():
@@ -58,10 +124,6 @@ def run_app() -> None:
import uvicorn
from invokeai.app.services.config.config_default import get_config
- from invokeai.app.util.torch_cuda_allocator import (
- apply_rocm_windows_allocator_default,
- configure_torch_cuda_allocator,
- )
from invokeai.backend.util.logging import InvokeAILogger
# Load config.
@@ -69,27 +131,11 @@ def run_app() -> None:
logger = InvokeAILogger.get_logger(config=app_config)
- # Before torch is imported anywhere: HIP reads its device list once, when torch initializes it, and an explicit
- # allocator configuration below imports torch. Runs a short child process on Windows ROCm.
- from invokeai.app.util.rocm_integrated_gpu import hide_integrated_gpus_on_rocm_windows
-
- hide_integrated_gpus_on_rocm_windows(logger)
-
- # Configure the torch CUDA memory allocator.
- # NOTE: It is important that this happens before torch is imported.
- if app_config.pytorch_cuda_alloc_conf:
- configure_torch_cuda_allocator(app_config.pytorch_cuda_alloc_conf, logger)
- else:
- apply_rocm_windows_allocator_default(logger)
+ # The server's runtime (`apply_server_runtime`) in its two parts, around the startup steps below that need torch:
+ # first what torch, HIP and MIOpen read when they initialize, before torch is imported anywhere.
+ _configure_torch_environment(app_config, logger)
- # Decide on AOTriton's experimental attention kernels before anything can run attention: torch reads the switch
- # once, at its first fused-kernel check, and the server already runs attention while starting up. This imports
- # torch, so it comes after the allocator configuration.
- from invokeai.app.util.rocm_aotriton import apply_rocm_aotriton_setting
-
- apply_rocm_aotriton_setting(app_config.rocm_aotriton_experimental, app_config.generation_devices, logger)
-
- # This import must happen after configure_torch_cuda_allocator() is called, because the module imports torch.
+ # This import must happen after the allocator is configured, because the module imports torch.
from invokeai.app.invocations.baseinvocation import InvocationRegistry
from invokeai.app.invocations.load_custom_nodes import load_custom_nodes
from invokeai.backend.util.devices import TorchDevice
@@ -97,7 +143,7 @@ def run_app() -> None:
torch_device_name = TorchDevice.get_generation_devices_summary(app_config.generation_devices)
logger.info(f"Using torch device: {torch_device_name}")
- # Import from startup_utils here to avoid importing torch before configure_torch_cuda_allocator() is called.
+ # Import from startup_utils here to avoid importing torch before the allocator is configured.
from invokeai.app.util.startup_utils import (
apply_monkeypatches,
check_cuda_build_compatibility,
@@ -118,8 +164,10 @@ def run_app() -> None:
app_config.port = first_open_port
logger.warning(f"Port {orig_config_port} is already in use. Using port {app_config.port}.")
- # Miscellaneous startup tasks.
+ # The runtime's second part: the monkeypatches, once the invocations are imported.
apply_monkeypatches(app_config.attention_backend)
+
+ # Miscellaneous startup tasks.
register_mime_types()
check_cudnn(logger)
check_cuda_build_compatibility(logger)
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 4e3532d887..cee7d02cc0 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
@@ -740,8 +740,10 @@ class WorkingMemoryCalibrationModelSummary(BaseModel):
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"
+ "attempt, tiled, batched, upcast, a VAE outside the AutoencoderKL family, no demand, or of an estimator a user "
+ "calibration does not move, such as the Z-Image denoise. Of these, only the not fit-eligible, the fragmented "
+ "and the aborted attempt's windows show among a line's sizes, as a size that is not counted where no counted "
+ "window measured it"
)
runs: list[WorkingMemoryCalibrationModelRun]
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 a4e6779e62..e67acf6666 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
@@ -1555,7 +1555,11 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
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
+ fit = (
+ user_fit_of(file, env.id, platform, import_estimator_modules(), 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
)
@@ -1729,6 +1733,7 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
assert device is not None
return self._untiled_decode_reservation(estimator, height, width, dtype, device)
+ specs = import_estimator_modules()
return build_plan(
target,
store.all_models(),
@@ -1738,8 +1743,8 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
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,
+ specs=specs,
+ capacity_bytes=self._decode_capacity(device, specs) 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,
)
@@ -1757,21 +1762,22 @@ class WorkingMemoryCalibrationService(WorkingMemoryCalibrationServiceBase):
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:
+ def _decode_capacity(self, device: torch.device, specs: Mapping[str, EstimatorSpec]) -> 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."""
+ window of this environment found it at (`recorded_outside_torch_bytes`, over the windows of the estimators a
+ user calibration moves): 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)
+ recorded = recorded_outside_torch_bytes(known.file, known.env_id, specs)
if recorded is not None:
capacity -= max(0, recorded - (memory.outside_torch_bytes or 0))
return capacity
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
index b6a4062608..6862193bce 100644
--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.py
+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.py
@@ -3,7 +3,9 @@ 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`).
+fragmented (`exclusions`), of the estimators a user calibration moves (`EstimatorSpec.user_calibrated`). The windows of
+any other estimator, a Z-Image denoise's say, are kept in the store but measure no line here and size no plan
+(`recorded_outside_torch_bytes`).
"""
import json
@@ -30,7 +32,7 @@ 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.fit import EntryKey, Line
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
@@ -40,16 +42,16 @@ 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 _measured_line(point: CalibrationPoint, specs: Mapping[str, EstimatorSpec]) -> Optional[Line]:
+ """The line a window measured: valid, a positive demand, and an estimator of `specs` that is `user_calibrated`
+ and whose line admits its features. None for every other window."""
+ if not point.valid or point.demand_bytes is None or point.demand_bytes <= 0:
+ return None
+ spec = specs.get(point.estimator)
+ if spec is None or not spec.user_calibrated:
+ return None
+ found = spec.line(point.features)
+ return found if found is not None and found.fits else None
def _attempts(file: CalibrationStoreFile) -> dict[str, str]:
@@ -69,10 +71,10 @@ _NONE_HELD_BACK: Final[HeldBack] = MappingProxyType({})
def exclusions(
- file: CalibrationStoreFile, held_back: HeldBack = _NONE_HELD_BACK
+ file: CalibrationStoreFile, specs: Mapping[str, EstimatorSpec], 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.
+ """Why each window that measured a line (`specs` registers the estimators) 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.
@@ -89,8 +91,10 @@ def exclusions(
attempt_of = _attempts(file)
excluded: dict[int, CalibrationSizeExclusion] = {}
groups: dict[tuple[str, str, int, str, str], list[int]] = {}
+ lines: dict[int, Line] = {}
for index, point in enumerate(points):
- if not _measures_a_line(point):
+ line = _measured_line(point, specs)
+ if line is None:
continue
if held_back.get(point.run_id) == "aborted_attempt":
excluded[index] = "aborted_attempt"
@@ -98,6 +102,7 @@ def exclusions(
if not point.fit_eligible:
excluded[index] = "partial_residency"
continue
+ lines[index] = line
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)
@@ -106,10 +111,12 @@ def exclusions(
measurements = []
for (env_id, estimator, version, _, _), indices in groups.items():
windows = [points[index] for index in indices]
+ # The windows of a measurement share their features, so they place it on one line at one size.
+ line = lines[indices[0]]
measurements.append(
fragmentation.Measurement(
- line=(env_id, estimator, version, _suffix(windows[0])),
- pixels=_pixels(windows[0]),
+ line=(env_id, estimator, version, line.suffix),
+ size=line.size,
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],
@@ -122,33 +129,47 @@ def exclusions(
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]:
+def counted_windows(
+ file: CalibrationStoreFile, specs: Mapping[str, EstimatorSpec], 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]
+ excluded = exclusions(file, specs, held_back)
+ return [
+ point
+ for index, point in enumerate(file.points)
+ if index not in excluded and _measured_line(point, specs) is not None
+ ]
-def recorded_outside_torch_bytes(file: CalibrationStoreFile, env_id: str) -> Optional[int]:
+def recorded_outside_torch_bytes(
+ file: CalibrationStoreFile, env_id: str, specs: Mapping[str, EstimatorSpec]
+) -> 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)."""
+ opened, of an estimator a user calibration moves (`EstimatorSpec.user_calibrated`, as `specs` registers it): 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). The windows of any
+ other estimator, a Z-Image denoise's say, size no calibration plan."""
+ calibrated = {estimator for estimator, spec in specs.items() if spec.user_calibrated}
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
+ if point.env_id == env_id
+ and point.valid
+ and point.estimator in calibrated
+ 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
+ file: CalibrationStoreFile,
+ env_id: str,
+ platform: Platform,
+ specs: Mapping[str, EstimatorSpec],
+ *,
+ 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
@@ -156,10 +177,10 @@ def user_fit_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)
+ for point in counted_windows(file, specs, 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)
+ lines, problems = user_fit.fit_user_lines(points, platform, specs)
if not lines:
return None, problems
return UserFit(label=fit_label(file.device_class.id, env_id), platform=platform, lines=lines), problems
@@ -195,7 +216,7 @@ class _EnvFit:
LineId = tuple[str, str, int, str]
-"""A summary line: environment id, estimator, version and ``<operation>_<dtype>``."""
+"""A summary line: environment id, estimator, version and ``<operation>_<dtype>`` (`fit.Line.suffix`)."""
def model_lines(
@@ -213,9 +234,11 @@ def model_lines(
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.
+ measured, of the estimators of `specs` a user calibration moves (`EstimatorSpec.user_calibrated`). 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. A window of any other estimator measured no line here, and
+ counts among the model's windows that fit none.
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
@@ -231,24 +254,25 @@ def model_lines(
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)
+ reasons = exclusions(file, specs, 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]] = {}
+ # Per environment, each window that measured a line, with that line's suffix.
+ measured_by_env: dict[str, list[tuple[CalibrationPoint, str]]] = {}
for point in file.points:
- measured = _measures_a_line(point)
- if measured:
- measured_by_env.setdefault(point.env_id, []).append(point)
+ measured = _measured_line(point, specs)
+ if measured is not None:
+ measured_by_env.setdefault(point.env_id, []).append((point, measured.suffix))
if model_key not in measured_models(point, models):
continue
- if not measured or id(point) in reason_of:
+ if measured is None or id(point) in reason_of:
excluded += 1
- if measured:
- own.setdefault((point.env_id, point.estimator, point.version, _suffix(point)), []).append(point)
+ if measured is not None:
+ own.setdefault((point.env_id, point.estimator, point.version, measured.suffix), []).append(point)
def counts(point: CalibrationPoint) -> bool:
return id(point) not in reason_of
@@ -260,7 +284,7 @@ def model_lines(
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, {})
+ user_fit_of(file, env_id, platform, specs, 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]
@@ -279,8 +303,8 @@ def model_lines(
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:
+ for point, measured in measured_by_env.get(env_id, []):
+ if measured != suffix:
continue
if carrier is None:
same = (point.estimator, point.version) == (estimator, version)
@@ -294,7 +318,7 @@ def model_lines(
if current_env is not None:
for estimator, suffix in priced_on:
spec = specs.get(estimator)
- if spec is not None:
+ if spec is not None and spec.user_calibrated:
line_ids.add((current_env.id, estimator, spec.version, suffix))
names: dict[str, Optional[str]] = {}
diff --git a/invokeai/backend/moss_image/working_memory.py b/invokeai/backend/moss_image/working_memory.py
index d0dce9be56..756eb3d83d 100644
--- a/invokeai/backend/moss_image/working_memory.py
+++ b/invokeai/backend/moss_image/working_memory.py
@@ -6,7 +6,7 @@ the image's (one per 16x16 pixels) and the prompt's. The coefficient and the poi
"""
from collections.abc import Mapping
-from typing import cast
+from typing import Optional, cast
import torch
@@ -14,17 +14,36 @@ from invokeai.backend.moss_image.pipeline_moss_image import MOSSImageTransformer
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.util.attention import sdpa_score_matrix_bytes
from invokeai.backend.working_memory.estimate import FeatureValue, WorkingMemoryEstimate, WorkingMemoryTerm
+from invokeai.backend.working_memory.fit import Line
from invokeai.backend.working_memory.spec import EstimatorSpec, register
# One transformer token per 2x2 patch of the FLUX.2 VAE's 8x latent.
MOSS_IMAGE_TOKEN_SCALE = 16
-def _denoise_terms(features: Mapping[str, FeatureValue], values: Mapping[str, float]) -> tuple[WorkingMemoryTerm, ...]:
+def _tokens(features: Mapping[str, FeatureValue]) -> int:
image_tokens = (cast(int, features["height"]) // MOSS_IMAGE_TOKEN_SCALE) * (
cast(int, features["width"]) // MOSS_IMAGE_TOKEN_SCALE
)
- tokens = image_tokens + cast(int, features["text_tokens"])
+ return image_tokens + cast(int, features["text_tokens"])
+
+
+def _line(features: Mapping[str, FeatureValue]) -> Optional[Line]:
+ """The forward's line, `token` over the attended tokens. Only the plain forward fits it: a fused SDPA kernel and a
+ dense build, every analytic term zero. The label names the size, the prompt's tokens and each analytic term that
+ is not zero, in bytes.
+
+ The shipped entry carries the slope alone (`k_token`), no base, so the line is not one it carries and the shipped
+ fit leaves it out (`fit.hand_set_values`): the slope is hand-set until a fitted base ships with it."""
+ if not all(isinstance(features.get(name), int) for name in ("height", "width", "text_tokens")):
+ return None
+ on_top = [f"{name}={features[name]}" for name in ("score_matrix_bytes", "dequant_bytes") if features.get(name)]
+ shape = f"{features['height']}x{features['width']}-text{features['text_tokens']}"
+ return Line("token", _tokens(features), not on_top, "-".join((shape, *on_top)))
+
+
+def _denoise_terms(features: Mapping[str, FeatureValue], values: Mapping[str, float]) -> tuple[WorkingMemoryTerm, ...]:
+ tokens = _tokens(features)
return (
WorkingMemoryTerm.fitted("activations", "k_token", tokens, values),
# Analytic: zero on a fused SDPA kernel, the materialized score matrices where the build has none.
@@ -44,6 +63,7 @@ MOSS_IMAGE_DENOISE_SPEC = register(
# shapes is what does, and the analytic score-matrix term prices that.
platform_keys=(),
terms=_denoise_terms,
+ line=_line,
)
)
diff --git a/invokeai/backend/util/fp8.py b/invokeai/backend/util/fp8.py
index ce4d5b7a75..17e8ffc943 100644
--- a/invokeai/backend/util/fp8.py
+++ b/invokeai/backend/util/fp8.py
@@ -9,6 +9,9 @@ parameter — reports `float8_e4m3fn`. That is a *storage* dtype: torch has no C
arithmetic on it (`"pow_cuda" not implemented for 'Float8_e4m3fn'`). So any code that reads a
model's dtype in order to build or cast *tensors* (latents, noise, conditioning, control images,
LoRA patch weights) must use `get_model_compute_dtype()` instead of `model.dtype`.
+
+The widened weights are memory one forward needs beyond the model's resident size, which a
+working-memory estimate prices with `peak_fp8_cast_transient_bytes()`.
"""
import torch
@@ -72,3 +75,42 @@ def get_model_compute_dtype(model: torch.nn.Module) -> torch.dtype:
"expect a dtype mismatch during the forward pass."
)
return fallback
+
+
+def peak_fp8_cast_transient_bytes(model: torch.nn.Module, compute_dtype: torch.dtype) -> int:
+ """Peak bytes one forward transiently needs to run this model's float8-stored weights in `compute_dtype`.
+
+ Two paths keep weights in float8 and widen them per forward, and both leave the stored tensors resident:
+
+ - FP8 Storage (`ModelLoader._wrap_forward_with_fp8_cast`): a layer's hooks widen its params to the compute
+ dtype when its forward starts and put the stored ones back when it ends, so the widened copies die with the
+ layer's forward.
+ - float8 weights a checkpoint ships and the loader keeps packed (`fp8_scaled.should_keep_fp8_weights`, or FP8
+ Storage on a scaled-fp8 checkpoint): `CustomLinear` dequantizes them per forward with `dequantize_weight`,
+ which holds the widened weight and its product with the `weight_scale` at once, two compute-dtype copies.
+
+ The hooked layers are leaf modules and run one after another, each freeing its copies before the next widens, so
+ the peak is the largest single layer's: its float8 params at the compute dtype, twice for one with a
+ `weight_scale`. Zero for a model that holds no float8 parameter. A quantized payload in a tensor subclass (SDNQ,
+ GGUF) is its scheme's to dequantize, not one of these casts, and is not counted.
+
+ Assumes the layers widen to `compute_dtype`, the dtype the forward runs in, as the loaders record it
+ (`get_model_compute_dtype`); a model widened to another dtype would be cast again per layer, which this does not
+ count. Counts every kept checkpoint weight, also where `torch._scaled_mm` multiplies it in float8 without widening
+ it: whether it does is decided per forward (the fp8 matmul setting, the device, alignment, a producer's
+ full-precision hint, the weight's device under partial loading), and the miss over-reserves one layer. Does not
+ count the host-to-device copy of a layer that partial loading left on the CPU, which every partially loaded weight
+ costs, whatever its dtype.
+ """
+ peak = 0
+ for module in model.modules():
+ stored = sum(
+ param.numel()
+ for param in module.parameters(recurse=False)
+ if type(param.data) is torch.Tensor and param.dtype in FP8_STORAGE_DTYPES
+ )
+ if not stored:
+ continue
+ copies = 2 if getattr(module, "weight_scale", None) is not None else 1
+ peak = max(peak, copies * stored * compute_dtype.itemsize)
+ return peak
diff --git a/invokeai/backend/util/vae_working_memory.py b/invokeai/backend/util/vae_working_memory.py
index 788fbaa39a..3a71d2974b 100644
--- a/invokeai/backend/util/vae_working_memory.py
+++ b/invokeai/backend/util/vae_working_memory.py
@@ -16,6 +16,7 @@ from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
from invokeai.backend.util.vae_tiling_scope import resolve_tile_size
from invokeai.backend.working_memory.estimate import FeatureValue, WorkingMemoryEstimate, WorkingMemoryTerm
+from invokeai.backend.working_memory.fit import convolution_line
from invokeai.backend.working_memory.platform import platform_for
from invokeai.backend.working_memory.spec import EstimatorSpec, register
@@ -120,7 +121,8 @@ def _vae_mid_block_score_matrix_bytes(
# bytes per pixel plus `b_<operation>_<dtype>` bytes the process pays whatever the size, shipped per convolution
# backend and allocator (`platform_for`). The values ship in `backend/working_memory/data/vae.json` with the points
# they are fitted on (`backend/working_memory/fit.py`); `scripts/calibrate_flux2_working_memory.py --only vae`
-# measures a build against them.
+# measures a build against them. Every spec here declares that line (`fit.convolution_line`) and opts in to user
+# calibration (`user_calibrated`), so a calibration run's decode windows refit these lines per device.
#
# None of the three scales out of the line. The demand does not follow the element size: on MIOpen fp16 needs about a
# third of what bf16 does, and on both backends fp32 needs less per value byte than bf16. The allocator matters as
@@ -266,6 +268,8 @@ VAE_SD_SPEC = register(
coefficients=_convolution_coefficients("fp16", "fp32"),
platform_keys=_PLATFORM_KEYS,
terms=_sd_terms,
+ line=convolution_line,
+ user_calibrated=True,
)
)
@@ -375,6 +379,8 @@ VAE_COGVIEW4_SPEC = register(
coefficients=_convolution_coefficients("bf16"),
platform_keys=_PLATFORM_KEYS,
terms=_cogview4_terms,
+ line=convolution_line,
+ user_calibrated=True,
)
)
@@ -492,6 +498,8 @@ VAE_FLUX_SPEC = register(
coefficients=_convolution_coefficients("fp16", "bf16", "fp32"),
platform_keys=_PLATFORM_KEYS,
terms=_flux_terms,
+ line=convolution_line,
+ user_calibrated=True,
)
)
@@ -590,6 +598,8 @@ VAE_FLUX2_SPEC = register(
coefficients=_convolution_coefficients("bf16", "fp32"),
platform_keys=_PLATFORM_KEYS,
terms=_flux2_terms,
+ line=convolution_line,
+ user_calibrated=True,
)
)
@@ -1184,6 +1194,8 @@ VAE_SD3_SPEC = register(
coefficients=_convolution_coefficients("fp16", "bf16", "fp32"),
platform_keys=_PLATFORM_KEYS,
terms=_single_pass_terms,
+ line=convolution_line,
+ user_calibrated=True,
)
)
diff --git a/invokeai/backend/working_memory/bounds.py b/invokeai/backend/working_memory/bounds.py
index 48f1975167..b7126b2c46 100644
--- a/invokeai/backend/working_memory/bounds.py
+++ b/invokeai/backend/working_memory/bounds.py
@@ -11,6 +11,7 @@ data to it, and by `scripts/working_memory/build_shipped.py`, which refuses to w
weights evicted for nothing.
"""
+import json
from collections.abc import Iterable, Mapping
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, Optional
@@ -46,23 +47,18 @@ spikes at small sizes and a second run reserving up to 1.6x the first at large o
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
+def point_id(point: MeasuredPoint, spec: "EstimatorSpec") -> str:
+ """A readable id of a point: estimator, platform, its features as its estimator's line labels them (`fit.Line`:
+ operation, dtype, size, tile, batch and a materialized score matrix of a VAE operation; size and prompt tokens of a
+ MOSS-Image denoise), card and method. Features that name no line show as they are. An estimator keyed by no
+ platform trait records none."""
+ found = spec.line(point.features)
+ label = found.label if found is not None else json.dumps(point.features, sort_keys=True, separators=(",", ":"))
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}"
+ head = f"{point.estimator}-{platform}" if platform else point.estimator
+ return f"{head}-{label}{out_of_fit}-{card}-{point.method}"
_ANY_PLATFORM: Final = Platform("cudnn", "native", "linux")
@@ -89,15 +85,15 @@ 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."""
+def bound_violation(point: MeasuredPoint, spec: "EstimatorSpec", estimate: WorkingMemoryEstimate) -> Optional[str]:
+ """Why `estimate`, the estimate `spec` gives `point`'s features, 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)
+ default = UPPER_BOUND_EXCEPTIONS.get(point_id(point, spec), 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:
diff --git a/invokeai/backend/working_memory/coefficients.py b/invokeai/backend/working_memory/coefficients.py
index 0321702dbc..5f325198a0 100644
--- a/invokeai/backend/working_memory/coefficients.py
+++ b/invokeai/backend/working_memory/coefficients.py
@@ -3,9 +3,10 @@
Both ship as JSON under `data/`, read through `importlib.resources` so a wheel install finds them. A coefficient entry
belongs to one estimator version on one measured platform, and either carries its values or borrows another entry's
(`values_from`); a point records the features of an operation that was measured and its measured peak. A carried value
-is the fit of the points it is resolved for (`fit.py`) or a declared stand-in (`stand_ins`).
-`tests/backend/working_memory/test_shipped_coefficients.py` resolves every entry against its `EstimatorSpec`, holds
-every point to the estimate the shipped coefficients give it, and every fitted value to the fit of its points.
+is the fit of the points it is resolved for (`fit.py`), a declared stand-in (`stand_ins`), or a hand-set constant of an
+entry marked `legacy`. `tests/backend/working_memory/test_shipped_coefficients.py` resolves every entry against its
+`EstimatorSpec`, holds every point to the estimate the shipped coefficients give it, and every fitted value to the fit
+of its points.
"""
import functools
@@ -50,11 +51,17 @@ class CoefficientEntry(_DataModel):
its own values."""
stand_ins: list[str] = []
"""Carried values that are declared conservative stand-ins rather than fits: what this platform prices a line no
- in-fit point measures at. `provenance` says what they stand for; every other carried value is a fit."""
+ in-fit point measures at. `provenance` says what they stand for; every other carried value is a fit, unless the
+ entry is `legacy`."""
unmeasured_floor: dict[str, float] = {}
"""Declared lower bounds, not fits: what carried values are raised to where this entry prices a platform nothing
is measured on (see `priced_as`). A fit describes the platform its points were measured on, not the one it stands
in for. `provenance` says where the floors come from."""
+ legacy: bool = False
+ """True for an entry whose carried values are hand-set constants, not a fit of measured points: no point decides
+ them and `fit.py` does not reproduce them, though the points of its estimator still bound its estimates. The data
+ test lists the entries that may ship such values; `scripts/working_memory/build_shipped.py` replaces them with the
+ fit of measured points once those fit every line and a fresh-process point measures each."""
provenance: str
"""Card, torch build, method and script the values come from, and which points they were fitted on."""
@@ -107,9 +114,10 @@ class MeasuredPoint(_DataModel):
"""A tighter upper bound than the default 1.3, as a multiple of `measured_bytes`, for a point the estimate has to
stay closer to. It applies whichever term decides the estimate."""
in_fit: bool = True
- """False for a point measured in a regime its platform does not run, kept to check another term: CUDA with the
- 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."""
+ """False for a point whose demand is not its line's alone, kept to check another term: one measured in a regime its
+ platform does not run (CUDA with the math attention kernel forced, whose score matrix shares the forward with the
+ convolutions), or one whose features carry a term on top of the line (`fit.Line.fits`), such as the score matrix a
+ build's own SDPA kernel materializes. 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:
diff --git a/invokeai/backend/working_memory/data/denoise.json b/invokeai/backend/working_memory/data/denoise.json
new file mode 100644
index 0000000000..cc2c2a064b
--- /dev/null
+++ b/invokeai/backend/working_memory/data/denoise.json
@@ -0,0 +1,2253 @@
+{
+ "schema_version": 1,
+ "coefficients": [
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "values": {
+ "k_denoise_bf16": 266684,
+ "b_denoise_bf16": 0,
+ "k_denoise_fp16": 266684,
+ "b_denoise_fp16": 0,
+ "k_denoise_fp32": 459628,
+ "b_denoise_fp32": 0
+ },
+ "unmeasured_floor": {
+ "k_denoise_bf16": 262144,
+ "b_denoise_bf16": 1073741824,
+ "k_denoise_fp16": 262144,
+ "b_denoise_fp16": 1073741824,
+ "k_denoise_fp32": 262144,
+ "b_denoise_fp32": 1073741824
+ },
+ "provenance": "The Z-Image transformer forward's lines, bytes per attended token plus a base, per dtype. RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA. Measured by scripts/calibrate_z_image_working_memory.py on 2026-10-18: bf16, fp16 and fp32 at 512, 768, 1024, 1440 and 2048px with a 512-token caption, and at 1024 and 1440px with a 77-token one, 21 plain forwards on a random-init transformer of the real geometry (memory does not depend on weight values) with 2 main blocks and one refiner block each, one fresh process per point with the server's runtime, demand_peak (the largest of the driver, reserved and allocated peak) of the larger of a cold and a warm forward. Fitted by scripts/working_memory/build_shipped.py: working_memory/fit.py's upper envelope of the points below, plus 5%. 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB, cudaMallocAsync). bf16 and fp16 measured identical; fp32 needs about 1.7 times as much per token. Every line runs through the origin: no point needs a base. Where this entry prices a platform nothing is measured on (MPS, XPU, the CPU, or cuDNN with expandable segments), each value is floored at the legacy constants the node reserved by hand, 0.25 MiB per attended token and a 1 GiB base for every dtype: the fit describes the card its points were measured on, not the platforms it stands in for."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "values": {
+ "k_denoise_bf16": 189236,
+ "b_denoise_bf16": 9437184,
+ "k_denoise_fp16": 189236,
+ "b_denoise_fp16": 9437184,
+ "k_denoise_fp32": 341719,
+ "b_denoise_fp32": 0
+ },
+ "provenance": "The Z-Image transformer forward's lines, bytes per attended token plus a base, per dtype. RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync, fused SDPA. Measured by scripts/calibrate_z_image_working_memory.py on 2026-10-18: bf16, fp16 and fp32 at 512, 768, 1024, 1440 and 2048px with a 512-token caption, and at 1024 and 1440px with a 77-token one, 21 plain forwards on a random-init transformer of the real geometry (memory does not depend on weight values) with 2 main blocks and one refiner block each, one fresh process per point with the server's runtime, demand_peak (the largest of the driver, reserved and allocated peak) of the larger of a cold and a warm forward. Fitted by scripts/working_memory/build_shipped.py: working_memory/fit.py's upper envelope of the points below, plus 5%. 4 main blocks measured no more at 1024px bf16 (768 MiB against 800 MiB). The real 30-block Z-Image Turbo in a running server measured below this line: 2176 MiB of demand at 15424 tokens in bf16, which it prices at 2793 MiB (calibration probe windows, kept as evidence and not shipped)."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native"
+ },
+ "values": {
+ "k_denoise_bf16": 262144,
+ "b_denoise_bf16": 1073741824,
+ "k_denoise_fp16": 262144,
+ "b_denoise_fp16": 1073741824,
+ "k_denoise_fp32": 262144,
+ "b_denoise_fp32": 1073741824
+ },
+ "legacy": true,
+ "provenance": "Legacy, not a fit, for every OS but Windows, which has its own entry: Linux ROCm with the native allocator is not measured. The constants the Z-Image denoise node reserved by hand, 0.25 MiB per attended token and a 1 GiB base, the same for every dtype, derived from peak reserved memory in bf16 on an RTX 4090 with a 512-token caption (scripts/calibrate_z_image_working_memory.py): 0.99 GiB at 1024px, 1.96 GiB at 1440px and 3.85 GiB at 2048px, 0.22 to 0.23 MB per token. They cover bf16 and fp16 on every platform measured since, but not fp32 from 1440px up: every measured fp32 line is steeper (the RX 9060 XT with the native allocator on Windows measured 6.9 GiB at 2048px, which these constants price at 5.1 GiB)."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "values": {
+ "k_denoise_bf16": 267790,
+ "b_denoise_bf16": 233832448,
+ "k_denoise_fp16": 267790,
+ "b_denoise_fp16": 271581184,
+ "k_denoise_fp32": 495266,
+ "b_denoise_fp32": 42991616
+ },
+ "unmeasured_floor": {
+ "k_denoise_bf16": 262144,
+ "b_denoise_bf16": 1073741824,
+ "k_denoise_fp16": 262144,
+ "b_denoise_fp16": 1073741824,
+ "k_denoise_fp32": 262144,
+ "b_denoise_fp32": 1073741824
+ },
+ "provenance": "Windows only; every other OS keeps its own entry. The Z-Image transformer forward's lines, bytes per attended token plus a base, per dtype. RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Measured by scripts/calibrate_z_image_working_memory.py on 2026-10-18: bf16, fp16 and fp32 at 512, 768, 1024, 1440 and 2048px with a 512-token caption, and at 1024 and 1440px with a 77-token one, 21 plain forwards on a random-init transformer of the real geometry (memory does not depend on weight values) with 2 main blocks and one refiner block each, one fresh process per point with the server's runtime, demand_peak (the largest of the driver, reserved and allocated peak) of the larger of a cold and a warm forward. Fitted by scripts/working_memory/build_shipped.py: working_memory/fit.py's upper envelope of the points below, plus 5%. 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, expandable segments). The base carries the ~250 MiB a process's first forward maps beyond its second (585 against 334 MiB at 512px bf16). Where this entry prices a platform nothing is measured on (MIOpen under hipMallocAsync on Windows), each value is floored at the legacy constants the node reserved by hand, 0.25 MiB per attended token and a 1 GiB base for every dtype: the fit describes the card its points were measured on, not the platform it stands in for."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "values": {
+ "k_denoise_bf16": 167383,
+ "b_denoise_bf16": 269484032,
+ "k_denoise_fp16": 167383,
+ "b_denoise_fp16": 306184192,
+ "k_denoise_fp32": 318260,
+ "b_denoise_fp32": 134217728
+ },
+ "provenance": "Windows only, where expandable segments are Invoke's ROCm default. The Z-Image transformer forward's lines, bytes per attended token plus a base, per dtype. RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True, MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Measured by scripts/calibrate_z_image_working_memory.py on 2026-10-18: bf16, fp16 and fp32 at 512, 768, 1024, 1440 and 2048px with a 512-token caption, and at 1024 and 1440px with a 77-token one, 21 plain forwards on a random-init transformer of the real geometry (memory does not depend on weight values) with 2 main blocks and one refiner block each, one fresh process per point with the server's runtime, demand_peak (the largest of the driver, reserved and allocated peak) of the larger of a cold and a warm forward. Fitted by scripts/working_memory/build_shipped.py: working_memory/fit.py's upper envelope of the points below, plus 5%. 4 main blocks measured the same at 1024px bf16 (937 MiB). The base carries the ~255 MiB a process's first forward maps beyond its second (477 against 222 MiB at 512px bf16). The real 30-block Z-Image Turbo in a running server measured below this line: 686 MiB of demand at 4128 tokens in bf16, which it prices at 1066 MiB (calibration probe windows, kept as evidence and not shipped)."
+ }
+ ],
+ "points": [
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 367001600,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 645922816,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1077936128,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2118123520,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 4148166656,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1050673152,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2088763392,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 367001600,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 645922816,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1077936128,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2118123520,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 4148166656,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1050673152,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2088763392,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 624951296,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1101004800,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1881145344,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 3667918848,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 7266631680,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1835008000,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "native"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 3579838464,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, no allocator configuration (the native allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 285212672,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 452984832,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 838860800,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1426063360,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2969567232,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 754974720,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1409286144,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 285212672,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 452984832,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 838860800,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1426063360,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2785017856,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 754974720,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1459617792,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 446693376,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 916455424,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1352663040,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2627731456,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 5077204992,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1319108608,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "cudnn",
+ "allocator": "cudaMallocAsync"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2550136832,
+ "method": "demand_peak",
+ "device": "RTX 4090",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RTX 4090, torch 2.13.0+cu130, Windows, PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync (the cudaMallocAsync allocator), fused SDPA; MIOPEN_FIND_MODE, AOTriton and the ROCm SDPA guard are ROCm's and do not apply. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured no more at 1024px bf16 on this card (768 MiB against 800 MiB with 2, under cudaMallocAsync). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 500629504,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 689373184,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 982974464,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1633091584,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2618753024,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 857145344,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1507262464,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 536346624,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 725090304,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1018691584,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1668808704,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2654470144,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 892862464,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1542979584,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 593362944,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 949878784,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1432223744,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2627600384,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 5249040384,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1355415552,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "expandable",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2257190912,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True (expandable segments), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 613875712,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 892796928,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1324810240,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2341928960,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 4501995520,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1291255808,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "bf16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2308374528,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 649592832,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 928514048,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1360527360,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2377646080,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 4537712640,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1326972928,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "fp16",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2344091648,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 1024,
+ "text_tokens": 512,
+ "tokens": 1536,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 765329408,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 2304,
+ "text_tokens": 512,
+ "tokens": 2816,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 1258160128,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 512,
+ "tokens": 4608,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2036203520,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 512,
+ "tokens": 8640,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 3802005504,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 16384,
+ "text_tokens": 512,
+ "tokens": 16896,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 7383941120,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 4096,
+ "text_tokens": 96,
+ "tokens": 4192,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 2018115584,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ },
+ {
+ "estimator": "denoise.z_image",
+ "version": 1,
+ "platform": {
+ "conv_backend": "miopen",
+ "allocator": "native",
+ "os": "windows"
+ },
+ "features": {
+ "image_tokens": 8128,
+ "text_tokens": 96,
+ "tokens": 8224,
+ "dtype": "fp32",
+ "control_blocks": 0,
+ "has_attention_mask": false,
+ "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0,
+ "lora_count": 0,
+ "dequant_transient_bytes": 0,
+ "fp8_cast_transient_bytes": 0
+ },
+ "measured_bytes": 3721003008,
+ "method": "demand_peak",
+ "device": "RX 9060 XT (gfx1200)",
+ "provenance": "scripts/calibrate_z_image_working_memory.py, 2026-10-18: RX 9060 XT (gfx1200), torch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Windows, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:False (the native allocator), MIOPEN_FIND_MODE=FAST, TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 (fused SDPA), ROCm SDPA guard installed. Random-init Z-Image transformer with the real geometry (memory does not depend on weight values), 2 main blocks and one refiner block each; 4 main blocks measured the same at 1024px bf16 on this card (937 MiB, under expandable segments). demand_peak: the largest of the driver, reserved and allocated peak over the baseline, the larger of a cold and a warm forward, one fresh process per point with the server's runtime; no failed allocation, allocator retry or spill."
+ }
+ ]
+}
diff --git a/invokeai/backend/working_memory/fit.py b/invokeai/backend/working_memory/fit.py
index b1fd34a038..92b3b299fc 100644
--- a/invokeai/backend/working_memory/fit.py
+++ b/invokeai/backend/working_memory/fit.py
@@ -1,34 +1,44 @@
"""The shipped fit: the values under `data/` reproduced from their measured points.
-The AutoencoderKL estimators price their convolutions as a line in the output's pixel count, one per operation and
-dtype: `k_<operation>_<dtype>` bytes per pixel plus `b_<operation>_<dtype>` bytes, the base a process pays whatever the
-size. Each carried pair is the upper envelope of the points it is resolved for (see `upper_envelope`), plus
-`SHIPPED_MARGIN`. A point joins the fit of the entry its estimator resolves to on its platform -- the lender's, where
-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. A point that bounds its estimate from below only
+An estimator's fitted terms price a line per operation and dtype: `k_<suffix>` bytes per unit of the line's size plus
+`b_<suffix>` bytes, the base a process pays whatever the size. Its `EstimatorSpec.line` says which line an operation's
+features price on, their size on it, and whether a measurement of them can join its fit (`Line`). The AutoencoderKL
+estimators price their convolutions on a line in the output's pixels (`convolution_line`); the Z-Image denoise prices
+its forward on one in attended tokens. Each carried pair is the upper envelope of the points it is
+resolved for (see `upper_envelope`), plus `SHIPPED_MARGIN`. A point joins the fit of the entry its estimator resolves
+to on its platform -- the lender's, where the estimator borrows -- when it is `in_fit` (not measured out of regime) and
+its line admits it.
+
+A line is fitted on its points' demand as measured; no term is subtracted from it. So a line admits only measurements
+whose demand is the line's alone. Where an estimate adds a term of its own on top of the line, a measurement of it
+fits nothing: a tiled VAE operation (the tile term reuses the untiled pair), a VAE an in-place cast grew
+(`upcast_weight_bytes`), and every denoise forward with an analytic term. The VAE mid-block score matrix is not such a
+term: an estimate reserves the larger of it and the convolutions, which peak apart, and on the builds that materialize
+it the convolutions stay the larger over the measured sizes (`vae_working_memory._peak_of_two_phases`); the CUDA points
+that force a math kernel are out of fit. 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.
+`tests/backend/working_memory/test_shipped_coefficients.py` holds every carried value 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
+`legacy` entry's hand-set values are neither fitted nor held to a fit. A value on no line its entry carries is hand-set
+too, 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, whose entry ships no base for its line. Its points still decide and bound it
+there.
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.
+`USER_MARGIN`, the same margin, for the estimators that opt in (`EstimatorSpec.user_calibrated`).
"""
import math
-from collections.abc import Iterable, Mapping, Sequence
+from collections.abc import Callable, Iterable, Mapping, Sequence
from fractions import Fraction
from typing import TYPE_CHECKING, Final, NamedTuple, Optional
from invokeai.backend.working_memory.coefficients import CoefficientEntry, MeasuredPoint, WorkingMemoryData, find_entry
+from invokeai.backend.working_memory.estimate import FeatureValue
if TYPE_CHECKING:
from invokeai.backend.working_memory.spec import EstimatorSpec
@@ -42,8 +52,8 @@ USER_MARGIN: Final = SHIPPED_MARGIN
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."""
+"""How far apart the sizes a line is fitted on must lie, as a ratio of its sizes (pixel or token counts): closer points
+pin the intercept no better than their noise."""
_MIB: Final = 2**20
@@ -51,19 +61,66 @@ EntryKey = tuple[str, int, tuple[tuple[str, str], ...]]
"""An entry's estimator id, version and platform keys: what a point is resolved by."""
+class Line(NamedTuple):
+ """Where an operation's features place it on the line its estimator's fitted terms price it on."""
+
+ suffix: str
+ """``<operation>_<dtype>``, naming the line's coefficients ``k_<suffix>`` and ``b_<suffix>``."""
+ size: int
+ """The operation's size on the line, in the unit its slope is per: output pixels, attended tokens."""
+ fits: bool
+ """Whether a measurement of these features can join the line's fit: its demand is the line's alone."""
+ label: str
+ """How a point of these features reads in its id (`bounds.point_id`), e.g. ``decode-bf16-1024x1024-tile512``, with
+ ``-scores`` where a VAE operation's build materializes the mid-block score matrix."""
+
+
+LineFunction = Callable[[Mapping[str, FeatureValue]], Optional[Line]]
+"""What an `EstimatorSpec` declares about its fitted line: the `Line` an operation's features place it on, or None for
+features that name no line."""
+
+
+def convolution_line(features: Mapping[str, FeatureValue]) -> Optional[Line]:
+ """The AutoencoderKL convolution line ``<operation>_<dtype>``, in output pixels: every VAE estimator's.
+
+ An untiled single-sample operation of an AutoencoderKL whose VAE no in-place cast grew fits it. Tiled operations
+ 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.
+ """
+ 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
+ tile, batch = features.get("tile"), features.get("batch_size", 1)
+ fits = (
+ tile is None
+ and batch == 1
+ and not features.get("upcast_weight_bytes", 0)
+ and features.get("vae_class", "AutoencoderKL") == "AutoencoderKL"
+ )
+ tiled = f"-tile{tile}" if tile is not None else ""
+ batched = f"-b{batch}" if batch != 1 else ""
+ scored = "-scores" if features.get("score_matrix_bytes") else ""
+ label = f"{operation}-{dtype}-{height}x{width}{tiled}{batched}{scored}"
+ return Line(f"{operation}_{dtype}", height * width, fits, label)
+
+
def entry_key(entry: CoefficientEntry | MeasuredPoint) -> EntryKey:
return (entry.estimator, entry.version, tuple(sorted(entry.platform.items())))
class FitPoint(NamedTuple):
- pixels: int
+ size: 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."""
+ """Whether the sizes 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]
@@ -86,7 +143,7 @@ def upper_envelope(
sizes = sorted({x for x, _ in points})
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"
+ f"an envelope needs two sizes at least {MIN_AREA_RATIO}x apart, got {sizes}; measure more sizes"
)
highest = {x: max(y for px, y in points if px == x) for x in sizes}
@@ -118,7 +175,7 @@ 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."""
+ a whole byte per unit of size and the intercept to a whole MiB."""
k, b = upper_envelope(points, capping)
margin = 1 + SHIPPED_MARGIN
return math.ceil(k * margin), math.ceil(b * margin / _MIB) * _MIB
@@ -126,7 +183,7 @@ def shipped_pair(
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.
+ rounded up to a whole byte per unit of size 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`
@@ -136,67 +193,46 @@ def user_pair(points: Sequence[tuple[int, int]]) -> tuple[int, int]:
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."""
+def carried_lines(entry: CoefficientEntry) -> set[str]:
+ """The suffixes an entry carries both halves of a line for."""
names = set(entry.values or {})
return {name[2:] for name in names if name.startswith("k_") and f"b_{name[2:]}" in names}
def hand_set_values(entry: CoefficientEntry, spec: "EstimatorSpec") -> set[str]:
- """The values `entry` may carry that no fit reproduces: those on no pixel line, for a `spec` keyed by no platform
- trait. Any other spec prices convolutions, whose every value is half of a line, so a value off one there is a typo
- or a term the fit never checks, and none is exempt."""
+ """The values `entry` may carry that no fit reproduces: those on no line it carries (`carried_lines`), for a `spec`
+ keyed by no platform trait. The MOSS-Image denoise declares its line in attended tokens, but its entry carries the
+ slope alone; shipping a fitted base (`b_token`) with it makes that a carried line, and its exemption goes. Any
+ other spec prices lines whose every value is half of one, so a value off one there is a typo or a term the fit
+ never checks, and none is exempt."""
if spec.platform_keys:
return set()
- lines = {f"{part}_{suffix}" for suffix in _pairs(entry) for part in ("k", "b")}
+ lines = {f"{part}_{suffix}" for suffix in carried_lines(entry) for part in ("k", "b")}
return set(entry.values or {}) - lines
-def fit_points(data: Iterable[WorkingMemoryData]) -> Mapping[tuple[EntryKey, str], list[FitPoint]]:
+def fit_points(
+ data: Iterable[WorkingMemoryData], specs: Mapping[str, "EstimatorSpec"]
+) -> 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.
+ the line its estimator's `EstimatorSpec.line` places its features on, where that admits them. `specs` holds the
+ spec of every estimator a point names. 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[FitPoint]] = {}
for point in (point for file in files for point in file.points):
- found = line_of(point.features)
- if not point.in_fit or found is None or not fits_a_line(point.features):
+ if not point.in_fit:
+ continue
+ line = specs[point.estimator].line(point.features)
+ if line is None or not line.fits:
continue
owner = carrier_of(entries, point)
- suffix, pixels = found
- if suffix in _pairs(owner):
- line = groups.setdefault((entry_key(owner), suffix), [])
- line.append(FitPoint(pixels, point.measured_bytes, point.holds_upper_bound))
+ if line.suffix in carried_lines(owner):
+ fitted_on = groups.setdefault((entry_key(owner), line.suffix), [])
+ fitted_on.append(FitPoint(line.size, point.measured_bytes, point.holds_upper_bound))
return groups
@@ -210,31 +246,57 @@ def carrier_of(entries: Sequence[CoefficientEntry], point: MeasuredPoint) -> Coe
return find_entry(entries, entry.values_from.estimator, entry.values_from.version, point.platform, where)
-def fitted_values(data: Iterable[WorkingMemoryData]) -> Mapping[EntryKey, Mapping[str, int]]:
- """Per entry that carries values, what `fitted_pair` gives each line it does not declare a stand-in.
+def entry_fit(
+ entry: CoefficientEntry, groups: Mapping[tuple[EntryKey, str], Sequence[FitPoint]]
+) -> tuple[dict[str, int], dict[str, str]]:
+ """What `fitted_pair` gives each line `entry` carries and does not declare a stand-in, from `groups`
+ (`fit_points`); and, per such line its points cannot fit, why."""
+ key = entry_key(entry)
+ values: dict[str, int] = {}
+ problems: dict[str, str] = {}
+ for suffix in sorted(carried_lines(entry)):
+ if {f"k_{suffix}", f"b_{suffix}"} <= set(entry.stand_ins):
+ continue
+ line = groups.get((key, suffix), [])
+ if not line:
+ problems[suffix] = "no in-fit point measures it"
+ continue
+ try:
+ k, b = fitted_pair(line)
+ except ValueError as e:
+ problems[suffix] = str(e)
+ continue
+ values |= {f"k_{suffix}": k, f"b_{suffix}": b}
+ return values, problems
+
+
+def fitted_values(
+ data: Iterable[WorkingMemoryData], specs: Mapping[str, "EstimatorSpec"]
+) -> Mapping[EntryKey, Mapping[str, int]]:
+ """Per entry that carries values and is not `legacy`, what `fitted_pair` gives each line it does not declare a
+ stand-in (`entry_fit`).
Raises, naming the entry and line, where the points cannot fit that line.
"""
files = list(data)
- groups = fit_points(files)
+ groups = fit_points(files, specs)
fitted: dict[EntryKey, dict[str, int]] = {}
- for entry in (entry for file in files for entry in file.coefficients if entry.values is not None):
- key = entry_key(entry)
- for suffix in sorted(_pairs(entry)):
- if {f"k_{suffix}", f"b_{suffix}"} <= set(entry.stand_ins):
- continue
- try:
- 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})
+ for entry in (entry for file in files for entry in file.coefficients):
+ if entry.values is None or entry.legacy:
+ continue
+ values, problems = entry_fit(entry, groups)
+ if problems:
+ suffix, problem = next(iter(problems.items()))
+ raise ValueError(f"{entry.estimator} on {entry.platform}, {suffix}: {problem}")
+ if values:
+ fitted[entry_key(entry)] = values
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)
+ return spans(point.size for point in line if point.caps)
def fitted_pair(line: Sequence[FitPoint]) -> tuple[int, int]:
@@ -243,12 +305,12 @@ def fitted_pair(line: Sequence[FitPoint]) -> tuple[int, int]:
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]
+ capping = [(p.size, 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"its fresh-process points measure sizes {sorted({x for x, _ in capping})}, not two 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_all, b_all = shipped_pair([(p.size, 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
index c9a4b20dc0..c45d4c5ec3 100644
--- a/invokeai/backend/working_memory/fragmentation.py
+++ b/invokeai/backend/working_memory/fragmentation.py
@@ -41,9 +41,10 @@ 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
+ """What its sizes are compared within: one line (`fit.Line.suffix`) of one estimator version on one card and
platform or environment."""
- pixels: int
+ size: int
+ """The operation's size on that line (`fit.Line.size`)."""
demand: Sequence[int]
reserved: Sequence[Optional[int]]
"""Each window's reserved delta."""
@@ -66,14 +67,14 @@ def fragmented(measurements: Sequence[Measurement]) -> list[bool]:
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):
+ for index in sorted(members, key=lambda index: measurements[index].size):
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]):
+ if ratio_outlier(ratio, [kept_ratio for size, kept_ratio in kept if size < measurement.size]):
flags[index] = True
elif ratio is not None and measurement.reference:
- kept.append((measurement.pixels, ratio))
+ kept.append((measurement.size, ratio))
return flags
diff --git a/invokeai/backend/working_memory/measurement.py b/invokeai/backend/working_memory/measurement.py
new file mode 100644
index 0000000000..cdf4a85692
--- /dev/null
+++ b/invokeai/backend/working_memory/measurement.py
@@ -0,0 +1,183 @@
+"""An operation's working memory, from this process's counter readings at the two ends of a window.
+
+A window spans one operation on a compute device with its weights and inputs in place. It opens with a synchronize, a
+release of the allocator's cached blocks, the baseline reading and a reset of the peaks: with nothing cached, whatever
+the operation takes shows as growth. It closes with a synchronize and a reading. Per counter (the driver's figure,
+torch's reserved and allocated bytes; see `counters`) the window takes its peak's growth over the baseline, and the
+operation's *demand* is the largest growth of the counters that could be read: no counter alone covers every platform
+(`counters` has the measurements).
+
+A window is invalid when its readings show that
+
+- an allocation failed (``oom``), or only succeeded after the allocator released its cache and retried
+ (``alloc_retry``). A retry squeezes the peak: an untiled 3072px FLUX VAE decode on an RTX 4090 read 22.5 GiB at the
+ card's limit, ~1280 bytes per pixel instead of ~2150;
+- Windows still keeps more than `SPILL_TOLERANCE_BYTES` of the process in shared memory `SPILL_SETTLE_S` after the close
+ (``spill``). Right after a decode the counter spikes transiently, 589 MiB, and is back at 9 MiB at the next read;
+- a device-wide counter (XPU) grew by more than this process's own reserved bytes: another process's load
+ (``foreign_device_load``);
+- no counter could be read (``counters_unavailable``).
+
+Two kinds of window take these definitions. The in-server probe's (`probe`) follow an operation through co-locks, nested
+windows and releases, in segments, and have reasons of their own. A *fresh window* (`measure`) is one operation alone:
+the calibration scripts measure their points that way, each in a fresh process with the server's runtime
+(`invokeai.app.run_app.apply_server_runtime`).
+"""
+
+import time
+from collections.abc import Callable, Iterable
+from dataclasses import dataclass
+from typing import Final, Literal, Optional
+
+import torch
+
+from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.working_memory import counters
+from invokeai.backend.working_memory.counters import CounterReading, Method
+
+MIB = 2**20
+
+SPILL_TOLERANCE_BYTES: Final = 256 * MIB
+"""Shared-memory bytes above the window's baseline that count as spill once they persist."""
+SPILL_SETTLE_S: float = 0.5
+"""How long a close waits before re-reading a raised shared-memory counter. Module-level so tests can shorten it."""
+FOREIGN_DEVICE_TOLERANCE_BYTES: Final = 256 * MIB
+"""Growth of a device-wide counter (XPU) beyond this process's own reserved growth that marks another process's load."""
+
+CounterName = Literal["driver", "reserved", "allocated"]
+COUNTERS: Final[tuple[CounterName, ...]] = ("driver", "reserved", "allocated")
+
+ReadingReason = Literal["oom", "alloc_retry", "spill", "foreign_device_load", "counters_unavailable"]
+"""Why a window's readings void it. The probe has reasons of its own on top (`probe.Reason`)."""
+
+
+def counter_value(reading: CounterReading, name: CounterName) -> Optional[int]:
+ """`name`'s value in `reading`, as a baseline takes it."""
+ return reading.driver if name == "driver" else reading.reserved if name == "reserved" else reading.allocated
+
+
+def counter_peak(reading: CounterReading, name: CounterName) -> Optional[int]:
+ """`name`'s peak since the last reset in `reading`. The driver keeps none outside a sampler (MPS): its value then."""
+ if name == "driver":
+ return reading.peak_driver if reading.peak_driver is not None else reading.driver
+ return reading.peak_reserved if name == "reserved" else reading.peak_allocated
+
+
+def demand(deltas: Iterable[Optional[int]]) -> Optional[int]:
+ """The demand of an operation whose counters grew by `deltas`: the largest that could be read, None if none could."""
+ readable = [delta for delta in deltas if delta is not None]
+ return max(readable) if readable else None
+
+
+def window_method(first: CounterReading, driver_readable: bool) -> Method:
+ """Where a window's driver figure came from: the method of its baseline `first`, unless a driver figure read there
+ dropped out later (`driver_readable` False), which leaves the window to torch's counters."""
+ return "torch-only" if first.driver is not None and not driver_readable else first.method
+
+
+def _rose(before: Optional[int], after: Optional[int]) -> bool:
+ return before is not None and after is not None and after > before
+
+
+def reading_reasons(first: CounterReading, final: CounterReading) -> list[ReadingReason]:
+ """Why the readings at a window's open (`first`) and close (`final`) void it, spill and unreadable counters aside."""
+ reasons: list[ReadingReason] = []
+ if _rose(first.num_ooms, final.num_ooms):
+ reasons.append("oom")
+ if _rose(first.num_alloc_retries, final.num_alloc_retries):
+ reasons.append("alloc_retry")
+ if (
+ first.device_used is not None
+ and final.device_used is not None
+ and first.reserved is not None
+ and final.reserved is not None
+ and (final.device_used - first.device_used) - (final.reserved - first.reserved) > FOREIGN_DEVICE_TOLERANCE_BYTES
+ ):
+ reasons.append("foreign_device_load")
+ return reasons
+
+
+def spilled(first: CounterReading, final: CounterReading, read: Callable[[], CounterReading]) -> bool:
+ """Whether the process stays paged into shared memory after a window: `final` holds more than
+ `SPILL_TOLERANCE_BYTES` above `first`, and so does a `read` `SPILL_SETTLE_S` later."""
+ baseline = first.paged
+ if baseline is None or final.paged is None or final.paged - baseline <= SPILL_TOLERANCE_BYTES:
+ return False
+ time.sleep(SPILL_SETTLE_S)
+ settled = read().paged
+ return settled is None or settled - baseline > SPILL_TOLERANCE_BYTES
+
+
+@dataclass(frozen=True)
+class FreshWindow:
+ """One operation measured as a window of its own: per counter its peak's growth over the baseline, None where it
+ could not be read."""
+
+ driver: Optional[int]
+ reserved: Optional[int]
+ allocated: Optional[int]
+ paged: Optional[int]
+ """How many more of the process's bytes Windows kept in shared memory at the close than at the baseline. A record:
+ `spilled` judges spill after the settle time."""
+ demand: Optional[int]
+ counter_method: Method
+ """Where the driver figure came from (`window_method`)."""
+ reasons: tuple[ReadingReason, ...]
+ """Why the window is invalid; none for a valid one."""
+
+
+def fresh_window(first: CounterReading, final: CounterReading, *, oom: bool, spill: bool) -> FreshWindow:
+ """The fresh window of an operation between `first`, read after the release before it, and `final`, read after it.
+
+ `oom` says the operation ran out of memory, `spill` that the process stayed paged (`spilled`).
+ """
+ deltas: dict[CounterName, Optional[int]] = {}
+ for name in COUNTERS:
+ base, top = counter_value(first, name), counter_peak(final, name)
+ deltas[name] = None if base is None or top is None else top - base
+ reasons: list[ReadingReason] = ["oom"] if oom else []
+ reasons += [reason for reason in reading_reasons(first, final) if reason not in reasons]
+ if spill:
+ reasons.append("spill")
+ operation_demand = demand(deltas.values())
+ if operation_demand is None:
+ reasons.append("counters_unavailable")
+ return FreshWindow(
+ driver=deltas["driver"],
+ reserved=deltas["reserved"],
+ allocated=deltas["allocated"],
+ paged=None if first.paged is None or final.paged is None else final.paged - first.paged,
+ demand=operation_demand,
+ counter_method=window_method(first, driver_readable=deltas["driver"] is not None),
+ reasons=tuple(reasons),
+ )
+
+
+def measure(device: torch.device, operation: Callable[[], object]) -> FreshWindow:
+ """Run `operation` on `device` as a fresh window: synchronize, release the allocator's cached blocks, read the
+ baseline and reset the peaks; run it; synchronize and read.
+
+ An operation that runs out of memory gives an invalid window (``oom``); its other errors propagate, and so does a
+ synchronization or a peak reset that fails (`counters`): no reading after it could be trusted, so there is no
+ window. Its output is released after the closing reading.
+ """
+ device_counters = counters.DeviceCounters(device)
+ try:
+ device_counters.synchronize()
+ TorchDevice.empty_cache(force=True)
+ first = device_counters.read()
+ device_counters.reset_peaks()
+ output, oom = None, False
+ try:
+ output = operation()
+ except RuntimeError as e: # torch.OutOfMemoryError among them
+ if "out of memory" not in str(e).lower():
+ raise
+ oom = True
+ device_counters.synchronize()
+ final = device_counters.read()
+ spill = spilled(first, final, device_counters.read)
+ del output
+ return fresh_window(first, final, oom=oom, spill=spill)
+ finally:
+ device_counters.close()
diff --git a/invokeai/backend/working_memory/probe.py b/invokeai/backend/working_memory/probe.py
index a17be614fc..55cff8d483 100644
--- a/invokeai/backend/working_memory/probe.py
+++ b/invokeai/backend/working_memory/probe.py
@@ -26,20 +26,18 @@ What a window measures, per counter (driver, torch reserved, torch allocated; se
5. Close: synchronize and read the final segment. Per counter, the delta is the largest segment peak less the
baseline and that segment's offset; `demand_bytes` is the largest delta of the counters that could be read.
-A window is invalid (`valid=False`, with its reasons) when another thread locked a model on the same device's cache
-while it was open, held one when it opened or was still locking one then (Expand Prompt and Image to Prompt run next to
-sessions; see `locking`), when weights left the device other than through one of the window's co-locks (`weights_left`:
-an offload by another thread or by this one outside a lock, or the weights of a model the cache dropped dying; see
-`offloading` and `dropped`), when an allocation failed or only succeeded after the allocator released its cache (a retry
-squeezes the peak: an untiled 3072px FLUX VAE decode on an RTX 4090 read 22.5 GiB at the card's limit, ~1280 bytes per
-pixel instead of ~2150), when Windows still keeps more than `SPILL_TOLERANCE_BYTES` of the process in shared memory
-`SPILL_SETTLE_S` after close (right after a decode the counter spikes transiently, 589 MiB, and is back at 9 MiB at the
-next read), when the operation raised or was canceled, or its node failed or was canceled after the window closed
-(`ProbeScope.invalidate`), when the Krea-2 SDPA benchmark (which resets the peaks itself) is active, when XPU's
-device-wide usage grew beyond this process's own, when a probe step failed (`probe_error`: a reading, a release, a peak
-reset or a synchronization, at the window's open as much as later; a failed lock hook also voids the scope's later
-windows, since its lock bookkeeping is suspect), and when no counter could be read. A model less than fully resident at
-open keeps the window valid but not `fit_eligible`: streamed weights are working memory the estimate does not price.
+The baseline, the demand, the counters' method and the reasons the readings give are `measurement`'s, which the
+calibration scripts' fresh windows share. A window is invalid (`valid=False`, with its reasons) for any reason its
+readings give (a failed or retried allocation, spill, another process's load on an XPU, no readable counter), and when
+another thread locked a model on the same device's cache while it was open, held one when it opened or was still
+locking one then (Expand Prompt and Image to Prompt run next to sessions; see `locking`), when weights left the device
+other than through one of the window's co-locks (`weights_left`: an offload by another thread or by this one outside a
+lock, or the weights of a model the cache dropped dying; see `offloading` and `dropped`), when the operation raised or
+was canceled, or its node failed or was canceled after the window closed (`ProbeScope.invalidate`), when the Krea-2
+SDPA benchmark (which resets the peaks itself) is active, and when a probe step failed (`probe_error`: a reading, a
+release, a peak reset or a synchronization, at the window's open as much as later; a failed lock hook also voids the
+scope's later windows, since its lock bookkeeping is suspect). A model less than fully resident at open keeps the
+window valid but not `fit_eligible`: streamed weights are working memory the estimate does not price.
`weights_left` covers what the model cache moves off the device while a scope is armed, and the weights of records it
drops, whenever they were dropped. Two things it does not cover or covers coarsely: device tensors something else still
@@ -78,6 +76,16 @@ from invokeai.backend.working_memory.counters import (
backend_for,
)
from invokeai.backend.working_memory.estimate import FeatureValue, WorkingMemoryEstimate, WorkingMemoryTerm
+from invokeai.backend.working_memory.measurement import (
+ COUNTERS,
+ CounterName,
+ counter_peak,
+ counter_value,
+ demand,
+ reading_reasons,
+ spilled,
+ window_method,
+)
if TYPE_CHECKING:
from invokeai.backend.model_manager.load.model_cache.cache_record import CacheRecord
@@ -88,13 +96,6 @@ MIB = 2**20
CALIBRATION_HEADROOM_MIN_BYTES: Final = 1 * GIB
CALIBRATION_HEADROOM_FRACTION: Final = 0.5
-SPILL_TOLERANCE_BYTES: Final = 256 * MIB
-"""Shared-memory bytes above the window's baseline that count as spill once they persist."""
-SPILL_SETTLE_S: float = 0.5
-"""How long a close waits before re-reading a raised shared-memory counter. Module-level so tests can shorten it."""
-FOREIGN_DEVICE_TOLERANCE_BYTES: Final = 256 * MIB
-"""Growth of a device-wide counter (XPU) beyond this process's own reserved growth that marks another process's load."""
-
Reason = Literal[
"foreign_lock",
"weights_left",
@@ -120,10 +121,6 @@ def _validity(reasons: list[Reason]) -> tuple[bool, bool]:
return valid, valid and "partial_residency" not in reasons
-CounterName = Literal["driver", "reserved", "allocated"]
-_COUNTERS: Final[tuple[CounterName, ...]] = ("driver", "reserved", "allocated")
-
-
class _Record(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")
@@ -240,20 +237,6 @@ def _release() -> None:
_boundary.active = False
-def _value(reading: CounterReading, name: CounterName) -> Optional[int]:
- return reading.driver if name == "driver" else reading.reserved if name == "reserved" else reading.allocated
-
-
-def _peak(reading: CounterReading, name: CounterName) -> Optional[int]:
- if name == "driver":
- return reading.peak_driver if reading.peak_driver is not None else reading.driver
- return reading.peak_reserved if name == "reserved" else reading.peak_allocated
-
-
-def _rose(before: Optional[int], after: Optional[int]) -> bool:
- return before is not None and after is not None and after > before
-
-
def _krea2_sdpa_benchmark_active() -> bool:
# Imported here: the Krea-2 attention module pulls in diffusers, which a lock must not.
from invokeai.backend.krea2.attention import KREA2_SDPA_BACKEND_ENV_VAR
@@ -294,7 +277,7 @@ class _Window:
self.state: Literal["measuring", "co_lock", "suspended"] = "measuring"
self.first: Optional[CounterReading] = None
self.baseline: dict[CounterName, Optional[int]] = {}
- self.offset: dict[CounterName, int] = dict.fromkeys(_COUNTERS, 0)
+ self.offset: dict[CounterName, int] = dict.fromkeys(COUNTERS, 0)
self.peak: dict[CounterName, int] = {}
self.delta: dict[CounterName, int] = {}
self.unavailable: set[CounterName] = set()
@@ -326,17 +309,17 @@ class _Window:
def start(self, reading: CounterReading) -> None:
self.first = reading
self.opened_at = time.perf_counter()
- for name in _COUNTERS:
- self.baseline[name] = _value(reading, name)
+ for name in COUNTERS:
+ self.baseline[name] = counter_value(reading, name)
if self.baseline[name] is None:
self.unavailable.add(name)
def fold(self, reading: CounterReading, ends_segment: bool = True) -> None:
"""Take `reading` as the end of the current segment, or with `ends_segment=False` as a sample within it."""
- for name in _COUNTERS:
+ for name in COUNTERS:
if name in self.unavailable:
continue
- value, base = _peak(reading, name), self.baseline[name]
+ value, base = counter_peak(reading, name), self.baseline[name]
if value is None or base is None:
self.unavailable.add(name)
continue
@@ -360,8 +343,8 @@ class _Window:
self.counters.synchronize()
_release()
settled = self.counters.read()
- for name in _COUNTERS:
- before, after = _value(self.co_lock_start, name), _value(settled, name)
+ for name in COUNTERS:
+ before, after = counter_value(self.co_lock_start, name), counter_value(settled, name)
if before is None or after is None:
self.unavailable.add(name)
else:
@@ -381,15 +364,12 @@ class _Window:
def method(self) -> Method:
if self.first is None:
return "torch-only"
- # A driver figure that dropped out mid-window leaves the window to torch's counters.
- if self.first.driver is not None and "driver" in self.unavailable:
- return "torch-only"
- return self.first.method
+ return window_method(self.first, driver_readable="driver" not in self.unavailable)
def measured(self, duration_s: float) -> MeasuredWindow:
- counter_deltas = {name: self.counter(name) for name in _COUNTERS}
- deltas = [delta.delta for delta in counter_deltas.values() if delta is not None]
- if not deltas:
+ counter_deltas = {name: self.counter(name) for name in COUNTERS}
+ demand_bytes = demand(None if delta is None else delta.delta for delta in counter_deltas.values())
+ if demand_bytes is None:
self.add_reason("counters_unavailable")
valid, fit_eligible = _validity(self.reasons)
method = self.method()
@@ -412,7 +392,7 @@ class _Window:
driver=counter_deltas["driver"],
reserved=counter_deltas["reserved"],
allocated=counter_deltas["allocated"],
- demand_bytes=max(deltas) if deltas else None,
+ demand_bytes=demand_bytes,
method=method,
verified=backend is not None and (method, backend) in VERIFIED_METHODS,
resident_fraction=self.resident_fraction,
@@ -469,20 +449,8 @@ class _Window:
self.counters.synchronize()
final = self.counters.read()
self.fold(final)
- first = self.first
- if _rose(first.num_ooms, final.num_ooms):
- self.add_reason("oom")
- if _rose(first.num_alloc_retries, final.num_alloc_retries):
- self.add_reason("alloc_retry")
- if (
- first.device_used is not None
- and final.device_used is not None
- and first.reserved is not None
- and final.reserved is not None
- and (final.device_used - first.device_used) - (final.reserved - first.reserved)
- > FOREIGN_DEVICE_TOLERANCE_BYTES
- ):
- self.add_reason("foreign_device_load")
+ for reason in reading_reasons(self.first, final):
+ self.add_reason(reason)
if any(cache_id == id(self.cache) for cache_id in _freed_weights[self.freed_seen :]):
self.add_reason("weights_left")
_deregister(self)
@@ -490,18 +458,10 @@ class _Window:
self.scope._stack.remove(self)
duration_s = time.perf_counter() - self.opened_at
+ # Outside the lock: it may wait out the settle time.
if final is not None and self.first is not None and self.counters is not None:
- baseline_paged = self.first.paged
- if (
- baseline_paged is not None
- and final.paged is not None
- and final.paged - baseline_paged > SPILL_TOLERANCE_BYTES
- ):
- # Shared usage spikes for a moment after large transfers; only what is still there later is spill.
- time.sleep(SPILL_SETTLE_S)
- settled = self.counters.read().paged
- if settled is None or settled - baseline_paged > SPILL_TOLERANCE_BYTES:
- self.add_reason("spill")
+ if spilled(self.first, final, self.counters.read):
+ self.add_reason("spill")
with _state_lock:
parent = self.parent
diff --git a/invokeai/backend/working_memory/spec.py b/invokeai/backend/working_memory/spec.py
index 715332c09a..273088237f 100644
--- a/invokeai/backend/working_memory/spec.py
+++ b/invokeai/backend/working_memory/spec.py
@@ -9,12 +9,17 @@ 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.fit import LineFunction
from invokeai.backend.working_memory.platform import platform_for
TermsFunction = Callable[[Mapping[str, FeatureValue], Mapping[str, float]], tuple[WorkingMemoryTerm, ...]]
"""An estimator's pure part: its features and its coefficient values in, its terms out."""
-ESTIMATOR_MODULES: Final = ("invokeai.backend.moss_image.working_memory", "invokeai.backend.util.vae_working_memory")
+ESTIMATOR_MODULES: Final = (
+ "invokeai.backend.moss_image.working_memory",
+ "invokeai.backend.util.vae_working_memory",
+ "invokeai.backend.z_image.denoise_working_memory",
+)
"""Every module that registers an `EstimatorSpec`. The registry holds only the specs of modules imported so far, so a
caller that needs all of them imports these (`import_estimator_modules`); `tests/backend/working_memory/` fails on a
module that declares a spec without being listed here."""
@@ -22,12 +27,14 @@ module that declares a spec without being listed here."""
@dataclass(frozen=True)
class EstimatorSpec:
- """What a working-memory estimator declares: its id and version, the coefficients its fitted terms read, and the
- platform keys those coefficients are shipped per.
+ """What a working-memory estimator declares: its id and version, the coefficients its fitted terms read, the
+ platform keys those coefficients are shipped per, and how its features map to the line those terms price on.
Registered at import of the module that defines the estimator. `terms` is that estimator's pure part, so an
estimate can be evaluated again from recorded features alone -- which is how the measured points under `data/` are
- checked. It is behaviour rather than declaration and stays out of equality and hashing.
+ checked. `line` places features on the estimator's fitted line for the shipped fit (`fit.py`), the ids of measured
+ points (`bounds.point_id`) and a user calibration. Both are behaviour rather than declaration and stay out of
+ equality and hashing.
"""
id: str
@@ -36,10 +43,25 @@ class EstimatorSpec:
coefficients: frozenset[str]
platform_keys: tuple[str, ...]
terms: TermsFunction = field(compare=False, repr=False)
+ line: LineFunction = field(compare=False, repr=False)
+ """The line an operation's features price on, their size on it, and whether a measurement of them fits it: the
+ AutoencoderKL convolution line in output pixels for every VAE estimator (`fit.convolution_line`), one in attended
+ tokens for the Z-Image denoise. Declared by every estimator, so a new one cannot inherit another's line, and with it
+ which of its measurements join a fit."""
+ user_calibrated: bool = False
+ """Whether a user's calibration moves this estimator: its windows fit user lines, its estimates read them, the
+ calibration summary shows its lines, and what its windows found held outside torch sizes the calibration plan
+ (`recorded_outside_torch_bytes`). Without it, its lines are the shipped fit's alone: a calibration run still records
+ its windows, and the summary counts them among the windows that fit no line.
+
+ The summary and the calibration plan are built on pixel lines: the summary keys a line's sizes by its windows'
+ `width` and `height`, and the plan sizes square decodes. A spec whose line is another, such as the Z-Image
+ denoise's in tokens, must not opt in until they key sizes by `fit.Line.size`."""
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,
- and with the user's own line where a calibration of this device measured it (`user_fit.resolve`)."""
+ and, for a `user_calibrated` estimator, 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)
diff --git a/invokeai/backend/working_memory/user_fit.py b/invokeai/backend/working_memory/user_fit.py
index 83e2107a53..0bd46adb43 100644
--- a/invokeai/backend/working_memory/user_fit.py
+++ b/invokeai/backend/working_memory/user_fit.py
@@ -3,7 +3,9 @@
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.
+values -- so a calibration of one model's decode moves every estimator that prices with the same line. Only the
+estimators that opt in (`EstimatorSpec.user_calibrated`) take part: the others' windows fit no user line, and no user
+line moves their estimates.
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
@@ -24,14 +26,14 @@ 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.fit import EntryKey, carried_lines, entry_key, 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."""
+"""A line: the entry that carries its values, and its suffix (`fit.Line.suffix`)."""
@dataclass(frozen=True)
@@ -49,13 +51,13 @@ 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."""
+ """Bytes per unit of the line's size (`fit.Line.size`)."""
b: int
"""Bytes whatever the size."""
x_min: int
- """The smallest size measured, in output pixels."""
+ """The smallest size measured."""
x_max: int
- """The largest size measured, in output pixels."""
+ """The largest size measured."""
points: int
@@ -102,30 +104,32 @@ 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(carried_lines(entry))
return frozenset()
def fit_user_lines(
- points: Iterable[UserPoint], platform: Platform
+ points: Iterable[UserPoint], platform: Platform, specs: Mapping[str, "EstimatorSpec"]
) -> 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.
+ A point joins a line where its estimator, as `specs` registers it, is `user_calibrated` and its `line` admits the
+ point's 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):
+ spec = specs.get(point.estimator)
+ if spec is None or not spec.user_calibrated or point.demand_bytes <= 0:
+ continue
+ found = spec.line(point.features)
+ if found is None or not found.fits:
continue
carrier = carrier_key(point.estimator, point.version, platform)
- suffix, pixels = found
- if carrier is None or suffix not in _carried_lines(carrier):
+ if carrier is None or found.suffix not in _carried_lines(carrier):
continue
- groups.setdefault((carrier, suffix), []).append((pixels, point.demand_bytes))
+ groups.setdefault((carrier, found.suffix), []).append((found.size, point.demand_bytes))
lines: dict[LineKey, UserLine] = {}
problems: dict[LineKey, str] = {}
@@ -135,7 +139,7 @@ def fit_user_lines(
except ValueError as e:
problems[key] = str(e)
continue
- sizes = [pixels for pixels, _ in measured]
+ sizes = [size for size, _ 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)
@@ -146,20 +150,21 @@ def resolve(
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 estimate for `features` with `fit`'s line in place of the shipped one, where `fit` has the line and `spec`
+ is `user_calibrated`.
- 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.
+ The line and its size are read as `fit.py` reads a point's (`EstimatorSpec.line`): for the convolution lines 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
+ found = spec.line(features) if spec.user_calibrated else None
+ line = fit.lines_for(spec).get(found.suffix) if found is not None else None
if found is None or line is None:
return spec.evaluate(features, shipped)
- suffix, pixels = found
+ suffix = found.suffix
values = MappingProxyType({**shipped.values, f"k_{suffix}": line.k, f"b_{suffix}": line.b})
- within = pixels <= line.x_max
+ within = found.size <= 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}")
diff --git a/invokeai/backend/z_image/denoise_working_memory.py b/invokeai/backend/z_image/denoise_working_memory.py
new file mode 100644
index 0000000000..e51e4006dd
--- /dev/null
+++ b/invokeai/backend/z_image/denoise_working_memory.py
@@ -0,0 +1,210 @@
+"""The working memory of one Z-Image transformer forward, as the denoise node reserves it.
+
+The transformer attends over one unified sequence of image and caption tokens, each run padded to a multiple of
+``SEQ_MULTI_OF``. On a fused SDPA kernel its activations scale linearly with that sequence: `k_denoise_<dtype>` bytes
+per attended token plus a base of `b_denoise_<dtype>` bytes, shipped per platform in
+`backend/working_memory/data/denoise.json`. Conditional and unconditional passes run one after the other, so only the
+longer caption counts. The platform keys are those of the VAE estimators; for a transformer, `conv_backend` just names
+the CUDA (`cudnn`) or ROCm (`miopen`) stack it runs on.
+
+That line is `denoise_<dtype>` over the attended tokens (`_line`), and only the plain forward fits it: every analytic
+term below comes to zero, and no attention mask is passed, which narrows the kernels SDPA can pick. `_line` reads that
+off the terms themselves, so a term added here takes the forwards it prices out of the fit. The fit takes a point's
+demand as measured, so a forward with an analytic term bounds its estimate but fits nothing. A materialized score
+matrix is no exception, although its term could be subtracted from the demand instead: the term is an upper bound
+(`SDPA_MATH_BYTES_PER_SCORE_ELEMENT` against the 9.6 to 16.4 bytes per score measured, and a whole chunk under the ROCm
+guard), so the line would come out low by its slack, and as the platform keys do not tell a build that materializes
+from one with a fused kernel, that low line would price the fused build short. The line is the shipped fit's alone:
+the spec does not opt in to user calibration (`EstimatorSpec.user_calibrated`), so a calibration run records the
+forward's windows but no user line moves the estimate.
+
+The lines are fitted per platform and dtype on fresh-process points of `scripts/calibrate_z_image_working_memory.py`
+(their provenance is in the data): an RTX 4090 with the native allocator and with `cudaMallocAsync`, and an RX 9060 XT
+under ROCm 10 with AOTriton's fused kernels, with expandable segments and with the native allocator on Windows. bf16,
+fp16 and fp32 run at 512 to 2048px with a 512-token caption, and at 1024 and 1440px with a 77-token one, on a
+random-init transformer of the real geometry with 2 main blocks: a no-grad forward frees each block's intermediates, so
+4 blocks measured no more. bf16 and fp16 take the same per token, fp32 1.7 to 1.9 times that; on ROCm a process's first
+forward maps ~250 MiB more than its second, which the base carries. In a running server, the real 30-block Z-Image
+Turbo measured below its estimate on the RTX 4090 under the native allocator and under `cudaMallocAsync` in bf16, and
+on the RX 9060 XT with expandable segments as an int8 build, whose dequantization transient sits on top.
+
+ROCm with the native allocator on every OS but Windows is not measured, and keeps the `legacy` constants the node
+reserved by hand: 0.25 MiB per attended token and a 1 GiB base, the same for every dtype, from peak reserved memory in
+bf16 on the RTX 4090. They cover bf16 and fp16 everywhere measured since, but not fp32 from 1440px up, whose measured
+lines are steeper. Their base also covers the fp8 weights cast per forward, which an fp8-stored model reserves as a
+term of its own as well, so it pays that cast twice wherever they price.
+
+Every other platform nothing measures is priced as a measured one (`priced_as`): XPU, MPS, the CPU and cuDNN with
+expandable segments as cuDNN with the native allocator, MIOpen under `hipMallocAsync` (and with expandable segments off
+Windows) as MIOpen with the native allocator on its OS. A fit describes the card it was measured on, so the two fitted
+entries they borrow, the RTX 4090's and the RX 9060 XT's on Windows with the native allocator, floor every value at
+the legacy constants there (`unmeasured_floor`): no unmeasured platform reserves less than the node did by hand.
+
+The analytic terms:
+
+- Where SDPA has no fused kernel for these shapes it materializes the score matrices, and those dominate: on ROCm
+ under Windows, whose fused kernels are disabled, a 1024px generation spilled 7.7 GB into shared system memory while
+ the node reserved only the default working memory. `sdpa_score_matrix_bytes` prices the term only where it is really
+ built. An attention mask narrows which fused kernels a build can use, so the call is told whether one is passed:
+ regional prompting's additive bias, or the padding mask the ControlNet forward always builds. The plain forward
+ passes none at batch size 1.
+- Regional prompting's attention bias (`_regional_attention_bias_bytes`).
+- A ControlNet adapter first runs its own blocks over a sequence of the same length and keeps one hint per block,
+ alive through the main layers. Measured over the plain forward at 1024px: 3.3, 5.9 and 18.9 hint-sized tensors
+ (sequence x width x element size) for 1, 6 and 15 blocks in the script's first runs, and at 15 blocks 19.5 on the
+ RTX 4090 and 18.4 on the RX 9060 XT since. n + 4 are charged; with the line's margin that covers each of them.
+- Half a GiB per LoRA.
+- The dequantization copy an int8_tensorwise, nvfp4 or GGUF build materializes per quantized linear and forward,
+ alive alongside the activations and invisible to them (`peak_dequant_transient_bytes`); zero for every other build.
+- The compute-dtype copies of a layer's float8-stored weights that FP8 Storage, or a kept fp8 checkpoint, widens per
+ forward (`peak_fp8_cast_transient_bytes`); zero for every other build.
+"""
+
+from collections.abc import Mapping
+from types import MappingProxyType
+from typing import Final, Optional, cast
+
+import torch
+
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
+from invokeai.backend.util.attention import sdpa_score_matrix_bytes
+from invokeai.backend.util.fp8 import peak_fp8_cast_transient_bytes
+from invokeai.backend.working_memory.estimate import FeatureValue, WorkingMemoryEstimate, WorkingMemoryTerm
+from invokeai.backend.working_memory.fit import Line
+from invokeai.backend.working_memory.platform import platform_for
+from invokeai.backend.working_memory.spec import EstimatorSpec, register
+from invokeai.backend.z_image.z_image_patchify_utils import SEQ_MULTI_OF
+
+Z_IMAGE_HIDDEN_SIZE: Final = 3840
+"""The transformer's width, which its ControlNet adapters share."""
+Z_IMAGE_ATTENTION_HEADS: Final = 30
+"""Heads of 128."""
+
+_CONTROL_HINTS_BEYOND_BLOCKS: Final = 4
+_LORA_PATCH_BYTES: Final = 2**29
+_DTYPE_NAMES: Final[Mapping[torch.dtype, str]] = {torch.bfloat16: "bf16", torch.float16: "fp16", torch.float32: "fp32"}
+"""The dtypes `TorchDevice.choose_bfloat16_safe_dtype` runs the transformer in."""
+_ELEMENT_SIZES: Final[Mapping[str, int]] = {"bf16": 2, "fp16": 2, "fp32": 4}
+_COEFFICIENTS: Final = frozenset(f"{part}_denoise_{dtype}" for part in ("k", "b") for dtype in _ELEMENT_SIZES)
+_UNPRICED: Final[Mapping[str, float]] = MappingProxyType(dict.fromkeys(_COEFFICIENTS, 0.0))
+"""Coefficient values that price the fitted terms at nothing: what remains of a forward's terms is what it adds on top
+of its line."""
+
+
+def padded_tokens(tokens: int) -> int:
+ """The transformer pads the image and the caption token runs to a multiple of `SEQ_MULTI_OF` each."""
+ return tokens + (-tokens) % SEQ_MULTI_OF
+
+
+def _regional_attention_bias_bytes(
+ regional_attn_mask: Optional[torch.Tensor], image_seq_len: int, dtype: torch.dtype
+) -> int:
+ """What `regional_forward` allocates per positive pass for regional prompting: a boolean copy of the mask, the
+ additive bias over the padded unified sequence, and the image-to-image block `torch.where` fills it from. The mask
+ itself is already on the device when the estimate is taken. Measured at 1024px on CUDA: 68 MiB over the plain
+ forward, against 93 MiB charged."""
+ if regional_attn_mask is None:
+ return 0
+ mask_side = regional_attn_mask.shape[0]
+ unified_seq_len = padded_tokens(image_seq_len) + padded_tokens(mask_side - image_seq_len)
+ return mask_side * mask_side + (unified_seq_len * unified_seq_len + image_seq_len * image_seq_len) * dtype.itemsize
+
+
+def _line(features: Mapping[str, FeatureValue]) -> Optional[Line]:
+ """The forward's line, `denoise_<dtype>` over the attended tokens. Only the plain forward fits it: no attention
+ mask, and every analytic term of `_terms` zero (see the module docstring). The label names what puts a forward off
+ the line: the mask, and each analytic term that is not zero, in bytes. A dtype without a line names none."""
+ dtype, tokens = features.get("dtype"), features.get("tokens")
+ if not isinstance(dtype, str) or dtype not in _ELEMENT_SIZES or not isinstance(tokens, int):
+ return None
+ on_top = [term for term in _terms(features, _UNPRICED) if term.coefficient is None and term.bytes]
+ off_line = ["attention_mask"] if features.get("has_attention_mask") else []
+ off_line += [f"{term.name}={int(term.bytes)}" for term in on_top]
+ shape = f"{features.get('image_tokens')}+{features.get('text_tokens')}tok"
+ return Line(f"denoise_{dtype}", tokens, not off_line, "-".join(("denoise", dtype, shape, *off_line)))
+
+
+def _terms(features: Mapping[str, FeatureValue], values: Mapping[str, float]) -> tuple[WorkingMemoryTerm, ...]:
+ tokens = cast(int, features["tokens"])
+ dtype = cast(str, features["dtype"])
+ control_blocks = cast(int, features["control_blocks"])
+ hint_bytes = 0
+ if control_blocks:
+ hint_bytes = (
+ (control_blocks + _CONTROL_HINTS_BEYOND_BLOCKS) * tokens * Z_IMAGE_HIDDEN_SIZE * _ELEMENT_SIZES[dtype]
+ )
+ return (
+ WorkingMemoryTerm.fitted("activations", f"k_denoise_{dtype}", tokens, values),
+ WorkingMemoryTerm.fitted("base", f"b_denoise_{dtype}", 1, values),
+ WorkingMemoryTerm("regional_attention_bias", cast(int, features["regional_bias_bytes"]), True),
+ WorkingMemoryTerm("attention_scores", cast(int, features["score_matrix_bytes"]), True),
+ WorkingMemoryTerm("control_hints", hint_bytes, True),
+ WorkingMemoryTerm("lora_patches", cast(int, features["lora_count"]) * _LORA_PATCH_BYTES, True),
+ WorkingMemoryTerm("dequant_transient", cast(int, features["dequant_transient_bytes"]), True),
+ WorkingMemoryTerm("fp8_cast_transient", cast(int, features["fp8_cast_transient_bytes"]), True),
+ )
+
+
+Z_IMAGE_DENOISE_SPEC = register(
+ EstimatorSpec(
+ id="denoise.z_image",
+ version=1,
+ coefficients=_COEFFICIENTS,
+ platform_keys=("conv_backend", "allocator"),
+ terms=_terms,
+ line=_line,
+ )
+)
+
+
+def estimate_z_image_denoise_working_memory(
+ transformer: torch.nn.Module,
+ *,
+ image_seq_len: int,
+ text_seq_len: int,
+ lora_count: int,
+ control_blocks: int = 0,
+ regional_attn_mask: Optional[torch.Tensor] = None,
+ has_attention_mask: bool = False,
+ device: torch.device,
+ dtype: torch.dtype,
+) -> WorkingMemoryEstimate:
+ """The working memory one forward of `transformer` needs on `device` in `dtype`.
+
+ `transformer` is the model about to be locked, read unlocked for its dequantization and fp8 cast transients.
+ `image_seq_len` and `text_seq_len` are the unpadded token counts, the longer caption of a CFG pair. `control_blocks`
+ is the ControlNet adapter's block count, `regional_attn_mask` regional prompting's mask, and `has_attention_mask`
+ whether the forward passes an attention mask at all.
+ """
+ dtype_name = _DTYPE_NAMES.get(dtype)
+ if dtype_name is None:
+ raise ValueError(
+ f"Working-memory estimator '{Z_IMAGE_DENOISE_SPEC.id}' has no {dtype} line on {platform_for(device)}: the "
+ "transformer runs in a dtype it is not measured for."
+ )
+ image_tokens = padded_tokens(image_seq_len)
+ text_tokens = padded_tokens(text_seq_len)
+ tokens = image_tokens + text_tokens
+ features: dict[str, FeatureValue] = {
+ "image_tokens": image_tokens,
+ "text_tokens": text_tokens,
+ "tokens": tokens,
+ "dtype": dtype_name,
+ "control_blocks": control_blocks,
+ "has_attention_mask": has_attention_mask,
+ "regional_bias_bytes": _regional_attention_bias_bytes(regional_attn_mask, image_seq_len, dtype),
+ "score_matrix_bytes": sdpa_score_matrix_bytes(
+ device=device,
+ dtype=dtype,
+ num_heads=Z_IMAGE_ATTENTION_HEADS,
+ head_dim=Z_IMAGE_HIDDEN_SIZE // Z_IMAGE_ATTENTION_HEADS,
+ seq_len=tokens,
+ has_attn_mask=has_attention_mask,
+ # The attention goes through diffusers' `dispatch_attention_fn`, which can route around torch's SDPA.
+ via_diffusers_dispatch=True,
+ ),
+ "lora_count": lora_count,
+ "dequant_transient_bytes": peak_dequant_transient_bytes(transformer, dtype),
+ "fp8_cast_transient_bytes": peak_fp8_cast_transient_bytes(transformer, dtype),
+ }
+ return Z_IMAGE_DENOISE_SPEC.estimate(features, device)
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index fbf81a1b7f..14bc1c9781 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -121530,7 +121530,7 @@
"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"
+ "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, no demand, or of an estimator a user calibration does not move, such as the Z-Image denoise. Of these, only the not fit-eligible, the fragmented and the aborted attempt's windows show among a line's sizes, as a size that is not counted where no counted window measured it"
},
"runs": {
"items": {
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index 0e8ab0b499..6454e11cec 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -54996,7 +54996,7 @@ export type components = {
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
+ * @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, no demand, or of an estimator a user calibration does not move, such as the Z-Image denoise. Of these, only the not fit-eligible, the fragmented and the aborted attempt's windows show among a line's sizes, as a size that is not counted where no counted window measured it
*/
excluded_windows: number;
/** Runs */
diff --git a/scripts/calibrate_z_image_working_memory.py b/scripts/calibrate_z_image_working_memory.py
index 7ed5c90fb9..b4b0da6033 100644
--- a/scripts/calibrate_z_image_working_memory.py
+++ b/scripts/calibrate_z_image_working_memory.py
@@ -1,71 +1,189 @@
-"""Calibrate the Z-Image denoise working-memory estimate against measured peak CUDA/HIP memory.
-
-Background
-----------
-The Z-Image transformer attends over one unified sequence -- image tokens and caption tokens, each padded to a
-multiple of 32 -- through diffusers' `dispatch_attention_fn`. Three numbers decide how much VRAM the model cache has
-to keep free for one transformer forward (``ZImageDenoiseInvocation._estimate_working_memory``):
-
-1. the activation cost per attended token on a fused SDPA kernel, which scales linearly with the sequence;
-2. the materialized score matrix, only where SDPA has no fused kernel for these shapes -- ROCm/Windows without
- the experimental AOTriton kernels, MPS -- which `sdpa_score_matrix_bytes` charges at the shipped
- `SDPA_MATH_BYTES_PER_SCORE_ELEMENT`;
-3. with a ControlNet attached, the adapter's hints: one per control block, live next to the transformer's own
- activations.
-
-This measures all three on the real geometry (dim 3840, 30 heads of 128, caption features 2560 wide) with randomly
-initialized models and a reduced transformer block count: memory depends on shapes, not on weight values, and a
-no-grad forward frees each block's intermediates. `--extra-blocks` re-checks that on the build at hand. Every point
-runs in a fresh subprocess, so the caching allocator's history cannot contaminate the peak-reserved reading, and a
-point that runs out of memory is recorded as such rather than aborting the run.
-
-Peak *reserved*, not allocated: the estimate is compared against free memory, so it has to bound what the
-allocator actually takes off the card.
-
-Every point is priced before it runs -- the node's own estimate for it, the forced-math score matrix where that is
-the point, and the weights -- and skipped when that exceeds free device memory. An oversized allocation does not
-always fail: where the driver backs it with system RAM (NVIDIA's sysmem fallback, AMD on Windows) it pages and can
-stall the whole machine. On a build whose default kernel materializes the score matrix, that skips every size above
-1024px. `--force` runs them anyway.
+"""Measure the working memory of one Z-Image transformer forward, as shipped-data points for `denoise.z_image`.
+
+What a point measures
+---------------------
+The demand of one transformer forward, measured as a fresh window (`invokeai/backend/working_memory/measurement.py`,
+whose definitions the in-server probe's windows share). With the model and its inputs resident: synchronize, release the
+allocator's cached blocks, read the baseline and reset the peaks; run the forward; the demand is then the largest growth
+of three counters over the baseline: the driver's figure for this process, torch's reserved peak and its allocated peak.
+A forward whose allocations failed, or only succeeded after the allocator released its cache and retried (a squeezed
+peak), or after which Windows keeps more than `measurement.SPILL_TOLERANCE_BYTES` of the process in shared memory, is
+invalid: it is recorded as such, not as a point.
+
+Every point runs in a fresh process, which first applies the server's runtime (`apply_server_runtime` in
+`invokeai/app/run_app.py`): the `MIOPEN_FIND_MODE` default, the integrated-GPU check, the allocator, the AOTriton
+decision and the monkeypatches, the ROCm SDPA guard among them, in the server's order. Its settings are those of a server
+without a config file, except the allocator configuration: `--alloc-conf`, or without one the platform default the
+server uses (expandable segments for ROCm on Windows, torch's native allocator elsewhere). This script's own process runs
+the integrated-GPU check once before the first point: the measuring processes inherit the `HIP_VISIBLE_DEVICES` it sets,
+which their own check keeps, as the server keeps an exported one.
+
+The forward then runs twice. The first forward after a load is a real peak in a server (kernel modules, library
+workspaces), and so is a later one, so the point takes the larger demand. Where both forwards read the driver's figure
+the point is a `demand_peak`. Where one could not, the point falls back to torch's counters alone, as a `reserved_peak`.
+
+The transformer has the real geometry (dim 3840, 30 heads of 128, caption features 2560 wide) and random weights in the
+measured dtype, because memory depends on shapes, not on weight values. It has 2 main blocks and one refiner block each:
+a no-grad forward frees each block's intermediates, which `--extra-blocks 4` re-checks at 1024px. A point carries the
+features of `estimate_z_image_denoise_working_memory`, taken in the measuring process after the runtime setup, so its
+`score_matrix_bytes` reflects the attention kernel this build really runs.
+
+Each point is priced before it runs: the estimate for it plus its weights in its dtype. It is skipped when that exceeds
+free device memory, unless `--force`. An oversized allocation does not always fail: where the driver backs it with
+system RAM (NVIDIA's sysmem fallback, AMD on Windows) it pages, which can stall the whole machine.
+
+Modes
+-----
+- `fit` (default): the fit grid, in each of `--dtypes` (bfloat16, float16, float32). The `--sizes` (512, 768, 1024,
+ 1440, 2048 px) run with a `--text-tokens` caption (512). Those among `--short-text-sizes` (1024, 1440) also run with
+ a `--short-text-tokens` caption (77), for the text slope. `--extra-blocks N` adds one forward with N main blocks at
+ 1024px, in the first dtype.
+- `math`: SDPA forced onto the math kernel at 1024px, next to the default kernel, per dtype: what a materialized score
+ matrix costs per element, against what the estimate charges for it.
+- `control`: a `--control-blocks` ControlNet adapter (15) at 1024px, next to no control, per dtype: how many
+ hint-sized tensors it keeps, against the n + 4 the estimate charges.
+
+Only the fit grid's points are fit points (`"fit": true`). The checks' points, the extra-blocks forward included, test
+analytic terms or assumptions rather than the line: they are marked `"fit": false`, and their `in_fit` is false. A fit
+point is `in_fit` only where the estimator's line admits its features (`Line.fits`): on a build whose SDPA kernel
+materializes the score matrix, the fit grid's forwards carry a score term on top of the line, so they measure that term
+rather than the line, as a check does.
+
+Output
+------
+Every measured point is appended to `--out` as one JSON object per line, the point file
+`scripts/working_memory/build_shipped.py --points` reads. It carries the fields of a `MeasuredPoint`
+(`invokeai/backend/working_memory/coefficients.py`):
+
+- `estimator`, `version` and `features`, the estimate's own;
+- `platform`, as `platform_for` gives it, OS included; the builder names the OS only where the data needs it;
+- `measured_bytes` (the demand), `method`, `device` and `in_fit`;
+- `provenance`, which names the GPU, the torch build, the OS, the allocator configuration, on ROCm `MIOPEN_FIND_MODE`,
+ the AOTriton switch and the SDPA guard, the block count and the date.
+
+The other keys are the script's, which the builder ignores: `fit`, `point` (the grid entry) and `raw` (each forward's
+counter deltas, the prediction and the runtime facts). An invalid, skipped or failed forward is no point: it shows in
+the table on stdout, with its reasons, and stays out of the file.
Usage
-----
- python scripts/calibrate_z_image_working_memory.py
- python scripts/calibrate_z_image_working_memory.py --extra-blocks 4 --control-blocks 6
- python scripts/calibrate_z_image_working_memory.py --max-px 1024 --control-blocks 0
+RTX 4090 (CUDA): the native allocator, then `cudaMallocAsync`; the checks once.
+
+ python scripts/calibrate_z_image_working_memory.py --out 4090-native.jsonl --extra-blocks 4
+ python scripts/calibrate_z_image_working_memory.py --out 4090-async.jsonl --alloc-conf backend:cudaMallocAsync
+ python scripts/calibrate_z_image_working_memory.py --out 4090-checks.jsonl --mode math
+ python scripts/calibrate_z_image_working_memory.py --out 4090-checks.jsonl --mode control
+
+RX 9060 XT (ROCm on Windows): the server's default expandable segments, then the native allocator; the checks once.
+
+ python scripts/calibrate_z_image_working_memory.py --out 9060xt-expandable.jsonl --extra-blocks 4
+ python scripts/calibrate_z_image_working_memory.py --out 9060xt-native.jsonl --alloc-conf expandable_segments:False
+ python scripts/calibrate_z_image_working_memory.py --out 9060xt-checks.jsonl --mode math
+ python scripts/calibrate_z_image_working_memory.py --out 9060xt-checks.jsonl --mode control
+
+`--dry-run` prints the planned points without touching a device.
"""
import argparse
+import dataclasses
+import datetime
import json
+import os
import subprocess
import sys
+import traceback
+from collections.abc import Mapping, Sequence
from contextlib import nullcontext
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Literal
-import torch
-from torch.nn.attention import SDPBackend, sdpa_kernel
-
+# None of these imports torch: a measuring process has to configure the allocator before torch is imported.
from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
-from invokeai.app.invocations.z_image.z_image_denoise import (
- Z_IMAGE_ATTENTION_HEADS,
- Z_IMAGE_HIDDEN_SIZE,
- ZImageDenoiseInvocation,
- _padded,
-)
-from invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+from invokeai.app.util.rocm_aotriton import AOTRITON_EXPERIMENTAL_ENV
+from invokeai.app.util.torch_cuda_allocator import ALLOCATOR_CONF_ENV_VARS
+
+if TYPE_CHECKING:
+ import torch
-GIB = 1024**3
-MIB = 1024**2
+ from invokeai.backend.working_memory.measurement import FreshWindow
+
+GIB = 2**30
+MIB = 2**20
CAP_FEAT_DIM = 2560
PATCH_SIZE = 2
CONTROL_IN_DIM = 33 # V2.0 adapters; the channel count only sizes the patch embedder
-# One transformer block at full width: attention 4 dim^2, SwiGLU 8 dim^2, adaLN and norms, rounded up.
-BLOCK_PARAMS = 13 * Z_IMAGE_HIDDEN_SIZE**2
-
-SIZES = (1024, 1440, 2048)
-TEXT_TOKENS = 512
-
-DTYPES = {"float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32}
+CHECK_PX = 1024
+"""The size the checks and the extra-blocks forward run at."""
+
+DTYPES = ("bfloat16", "float16", "float32")
+LOGGER_NAME = "calibrate_z_image_working_memory"
+RESULT_PREFIX = "RESULT "
+POINT_TIMEOUT_S = 1800
+"""How long one measuring process may take. Generous: it only keeps a driver that hangs from stalling a whole run."""
+
+Kind = Literal["fit", "blocks", "reference", "math", "control"]
+Mode = Literal["fit", "math", "control"]
+PointMethod = Literal["demand_peak", "reserved_peak"]
+
+
+@dataclass(frozen=True)
+class Point:
+ """One transformer forward to measure, in a process of its own."""
+
+ kind: Kind
+ """`fit` for a point of the fit grid; otherwise the check it serves: another block count (`blocks`), the
+ default-kernel forward a check compares with (`reference`), the forced math kernel (`math`) or a ControlNet
+ (`control`)."""
+ px: int
+ text_tokens: int
+ """The caption's tokens, unpadded."""
+ dtype: str
+ """A torch dtype name, one of `DTYPES`."""
+ blocks: int
+ force_math: bool = False
+ control_blocks: int = 0
+
+ @property
+ def fit(self) -> bool:
+ return self.kind == "fit"
+
+
+def plan(
+ mode: Mode,
+ *,
+ sizes: Sequence[int],
+ dtypes: Sequence[str],
+ text_tokens: int,
+ short_text_tokens: int,
+ short_text_sizes: Sequence[int],
+ blocks: int,
+ extra_blocks: int,
+ control_blocks: int,
+) -> list[Point]:
+ """The forwards a run measures, in order: per dtype, the fit grid or a check's pair of forwards."""
+ points: list[Point] = []
+ for dtype in dtypes:
+ if mode == "fit":
+ points += [Point("fit", px, text_tokens, dtype, blocks) for px in sizes]
+ points += [Point("fit", px, short_text_tokens, dtype, blocks) for px in sizes if px in short_text_sizes]
+ continue
+ points.append(Point("reference", CHECK_PX, text_tokens, dtype, blocks))
+ points.append(
+ Point(
+ mode,
+ CHECK_PX,
+ text_tokens,
+ dtype,
+ blocks,
+ force_math=mode == "math",
+ control_blocks=control_blocks if mode == "control" else 0,
+ )
+ )
+ if mode == "fit" and extra_blocks:
+ points.append(Point("blocks", CHECK_PX, text_tokens, dtypes[0], extra_blocks))
+ return points
def image_tokens(px: int) -> int:
@@ -73,77 +191,144 @@ def image_tokens(px: int) -> int:
return side * side
-def unified_tokens(px: int, text_tokens: int) -> int:
- return _padded(image_tokens(px)) + _padded(text_tokens)
+def measured_bytes_and_method(windows: Sequence["FreshWindow"]) -> tuple[int, PointMethod]:
+ """A valid point's bytes and `MeasuredPoint.method`, from its forwards' windows.
+
+ `demand_peak` where every forward read the driver's figure: the largest demand. Otherwise `reserved_peak`, from
+ torch's counters alone, so that the method names what the bytes were read from.
+ """
+ if all(window.driver is not None for window in windows):
+ return max(window.demand for window in windows if window.demand is not None), "demand_peak"
+ torch_counters = [delta for window in windows for delta in (window.reserved, window.allocated) if delta is not None]
+ return max(torch_counters), "reserved_peak"
+
+
+def point_line(
+ point: Point,
+ *,
+ common: Mapping[str, Any],
+ provenance: str,
+ windows: Sequence["FreshWindow"],
+ raw: Mapping[str, Any],
+) -> dict[str, Any]:
+ """The output line of a measured point: a `point`, or `invalid` with the reasons of its forwards.
+
+ `common` holds the `MeasuredPoint` fields the measurement does not decide: estimator, version, platform, features
+ and device. `windows` are the forwards' fresh windows, cold first; `raw` the point's other facts.
+ """
+ reasons = list(dict.fromkeys(reason for window in windows for reason in window.reasons))
+ line = {"status": "invalid" if reasons else "point", "fit": point.fit, "point": dataclasses.asdict(point), **common}
+ raw = {**raw, **dict(zip(("cold", "warm"), map(dataclasses.asdict, windows), strict=False))}
+ if reasons:
+ return line | {"reasons": reasons, "raw": raw}
+ # Imports torch: a point line is taken in the measuring process, after `_apply_server_runtime`.
+ from invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_DENOISE_SPEC
+
+ measured, method = measured_bytes_and_method(windows)
+ on_line = Z_IMAGE_DENOISE_SPEC.line(common["features"])
+ return line | {
+ "measured_bytes": measured,
+ "method": method,
+ "provenance": provenance,
+ "in_fit": point.fit and on_line is not None and on_line.fits,
+ "raw": raw,
+ }
-def predicted_bytes(px: int, blocks: int, dtype: torch.dtype, force_math: bool, control_blocks: int) -> int:
- """What a point is expected to take: working memory as the node estimates it, plus the weights."""
- working = ZImageDenoiseInvocation._estimate_working_memory(
- image_seq_len=image_tokens(px),
- text_seq_len=TEXT_TOKENS,
- num_loras=0,
- num_control_blocks=control_blocks,
- has_attention_mask=control_blocks > 0,
- device=torch.device("cuda"),
- dtype=dtype,
- )
- if force_math:
- tokens = unified_tokens(px, TEXT_TOKENS)
- working += Z_IMAGE_ATTENTION_HEADS * tokens * tokens * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
- # Main blocks plus refiners and embedders; adapter blocks plus its refiners.
- modules = blocks + 4 + (control_blocks + 2 if control_blocks else 0)
- return working + modules * BLOCK_PARAMS * dtype.itemsize
-
-
-def _peak_reserved(fn) -> int | None:
- """Run ``fn`` and return the growth in peak reserved bytes, or ``None`` if it ran out of memory."""
- torch.cuda.synchronize()
- torch.cuda.empty_cache()
- torch.cuda.reset_peak_memory_stats()
- baseline = torch.cuda.memory_reserved()
- try:
- fn()
- torch.cuda.synchronize()
- except (torch.cuda.OutOfMemoryError, RuntimeError) as e:
- if "out of memory" not in str(e).lower():
- raise
- return None
- return torch.cuda.max_memory_reserved() - baseline
+def failed_line(point: Point, error: str) -> dict[str, Any]:
+ return {"status": "failed", "fit": point.fit, "point": dataclasses.asdict(point), "error": error}
-def _control_adapter(blocks: int, device: torch.device, dtype: torch.dtype) -> torch.nn.Module:
- """A randomly initialized adapter, allocated directly in ``dtype`` on the device: 15 blocks are ~3B parameters,
- which would otherwise pass through the host in float32 first."""
- from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
+def file_record(line: Mapping[str, Any]) -> dict[str, Any] | None:
+ """What `--out` receives of a line: a measured point, without the status only the table reads. None for a forward
+ that is no point: the data builder refuses a point file record that is no `MeasuredPoint`."""
+ if line["status"] != "point":
+ return None
+ return {key: value for key, value in line.items() if key != "status"}
+
+
+def _alloc_conf(facts: Mapping[str, Any]) -> str:
+ return ", ".join(f"{var}={value}" for var, value in facts["alloc_conf"].items()) or "no allocator configuration"
+
+
+def provenance(point: Point, facts: Mapping[str, Any], date: str) -> str:
+ """A measured point's `provenance`: where and how it was measured."""
+ build = f"torch {facts['torch']}" + (f" (HIP {facts['hip']})" if facts["hip"] else "")
+ parts = [
+ facts["device"],
+ build,
+ facts["os"].capitalize(),
+ f"{_alloc_conf(facts)} (torch reports the {facts['allocator_backend']} allocator)",
+ ]
+ if facts["hip"]:
+ parts += [
+ f"MIOPEN_FIND_MODE={facts['miopen_find_mode'] or 'unset'}",
+ f"{AOTRITON_EXPERIMENTAL_ENV}={facts['aotriton_experimental'] or 'unset'}",
+ f"ROCm SDPA guard {'installed' if facts['rocm_sdpa_guard'] else 'not installed'}",
+ ]
+ regime = {"math": ", SDPA forced onto the math kernel", "control": f", a {point.control_blocks}-block ControlNet"}
+ blocks = f"{point.blocks} main block{'' if point.blocks == 1 else 's'}"
+ return (
+ f"scripts/calibrate_z_image_working_memory.py ({date}): {', '.join(parts)}. Random-init Z-Image transformer "
+ f"with the real geometry, {blocks} and one refiner block each{regime.get(point.kind, '')}; "
+ "memory does not depend on weight values. A fresh process with the server's runtime, the larger demand of a "
+ "cold and a warm forward; no failed allocation, allocator retry or spill."
+ )
- with torch.device("meta"):
- adapter = ZImageControlAdapter(
- num_control_blocks=blocks,
- control_in_dim=CONTROL_IN_DIM,
- dim=Z_IMAGE_HIDDEN_SIZE,
- n_heads=Z_IMAGE_ATTENTION_HEADS,
- n_kv_heads=Z_IMAGE_ATTENTION_HEADS,
- )
- adapter = adapter.to(dtype).to_empty(device=device)
- for param in adapter.parameters():
- torch.nn.init.normal_(param, std=0.02)
- return adapter.eval()
+
+# The measuring process. Everything below imports torch, so it runs only after `_apply_server_runtime`.
+
+
+def _apply_server_runtime(alloc_conf: str) -> None:
+ """Apply the server's runtime (`run_app.apply_server_runtime`) before torch is imported, with the settings of a
+ server without a config file and the allocator configuration this run measures: `alloc_conf`, or none for the
+ platform's default."""
+ from invokeai.app.run_app import apply_server_runtime
+ from invokeai.app.services.config.config_default import get_config
+ from invokeai.backend.util.logging import InvokeAILogger
+
+ config = get_config().model_copy(update={"pytorch_cuda_alloc_conf": alloc_conf or None})
+ apply_server_runtime(config, InvokeAILogger.get_logger(LOGGER_NAME, config=config))
+
+
+def _runtime_facts(device: "torch.device", os_name: str) -> dict[str, Any]:
+ """The runtime a point is measured in, as its provenance and `raw` record it."""
+ import torch
+
+ from invokeai.backend.util.attention import rocm_sdpa_chunks_math
+ from invokeai.backend.working_memory.counters import backend_for, method_verified
+ from invokeai.backend.z_image import denoise_working_memory
+
+ name = torch.cuda.get_device_name(device)
+ if torch.version.hip is not None:
+ name = f"{name} ({torch.cuda.get_device_properties(device).gcnArchName.split(':')[0]})"
+ backend = backend_for(device)
+ return {
+ "device": name,
+ "torch": torch.__version__,
+ "hip": torch.version.hip,
+ "os": os_name,
+ "allocator_backend": torch.cuda.get_allocator_backend(),
+ "alloc_conf": {var: os.environ[var] for var in ALLOCATOR_CONF_ENV_VARS if os.environ.get(var)},
+ "miopen_find_mode": os.environ.get("MIOPEN_FIND_MODE"),
+ "aotriton_experimental": os.environ.get(AOTRITON_EXPERIMENTAL_ENV),
+ "rocm_sdpa_guard": rocm_sdpa_chunks_math(device.type),
+ "driver_method_verified": backend is not None and method_verified(backend),
+ # The checkout the point was priced from. A module's file, not the package's: `invokeai` can be imported as a
+ # namespace package, whose `__file__` is None.
+ "estimator_module": str(Path(denoise_working_memory.__file__).resolve()),
+ }
-def measure(px: int, text_tokens: int, blocks: int, dtype: torch.dtype, force_math: bool, control_blocks: int) -> dict:
- """Peak reserved memory for one transformer forward at one resolution."""
+def _transformer(blocks: int) -> "torch.nn.Module":
+ """The Z-Image transformer's geometry with `blocks` main blocks and one refiner block each, on the meta device."""
+ import torch
from diffusers import ZImageTransformer2DModel
- from invokeai.backend.z_image.z_image_controlnet_extension import (
- ZImageControlNetExtension,
- z_image_forward_with_control,
- )
+ from invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_ATTENTION_HEADS, Z_IMAGE_HIDDEN_SIZE
- device = torch.device("cuda")
- model = (
- ZImageTransformer2DModel(
+ with torch.device("meta"):
+ return ZImageTransformer2DModel(
all_patch_size=(PATCH_SIZE,),
all_f_patch_size=(1,),
in_channels=16,
@@ -160,143 +345,391 @@ def measure(px: int, text_tokens: int, blocks: int, dtype: torch.dtype, force_ma
axes_dims=[32, 48, 48],
axes_lens=[1024, 512, 512],
)
- .to(device=device, dtype=dtype)
- .eval()
- )
- latent = px // LATENT_SCALE_FACTOR
- x = [torch.randn(16, 1, latent, latent, device=device, dtype=dtype)]
- t = torch.full((1,), 0.5, device=device, dtype=dtype)
- cap_feats = [torch.randn(text_tokens, CAP_FEAT_DIM, device=device, dtype=dtype)]
-
- extension = None
- if control_blocks:
- extension = ZImageControlNetExtension(
- control_adapter=_control_adapter(control_blocks, device, dtype),
- control_cond=torch.randn(CONTROL_IN_DIM, 1, latent, latent, device=device, dtype=dtype),
+
+
+def _control_adapter(blocks: int) -> "torch.nn.Module":
+ """A ControlNet adapter with `blocks` control blocks at the transformer's width, on the meta device."""
+ import torch
+
+ from invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_ATTENTION_HEADS, Z_IMAGE_HIDDEN_SIZE
+ from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
+
+ with torch.device("meta"):
+ return ZImageControlAdapter(
+ num_control_blocks=blocks,
+ control_in_dim=CONTROL_IN_DIM,
+ dim=Z_IMAGE_HIDDEN_SIZE,
+ n_heads=Z_IMAGE_ATTENTION_HEADS,
+ n_kv_heads=Z_IMAGE_ATTENTION_HEADS,
)
- def forward() -> None:
- with sdpa_kernel(SDPBackend.MATH) if force_math else nullcontext():
- if extension is None:
- model(x=x, t=t, cap_feats=cap_feats)
- else:
- z_image_forward_with_control(
- transformer=model, x=x, t=t, cap_feats=cap_feats, control_extension=extension
+
+def _materialize(module: "torch.nn.Module", device: "torch.device", dtype: "torch.dtype") -> "torch.nn.Module":
+ """A meta-device module allocated directly in `dtype` on `device`, randomly initialized: a 15-block adapter is ~3B
+ parameters, which would otherwise pass through the host in float32 first."""
+ import torch
+
+ module = module.to(dtype).to_empty(device=device)
+ for param in module.parameters():
+ torch.nn.init.normal_(param, std=0.02)
+ return module.eval()
+
+
+def _measure(point: Point, force: bool) -> dict[str, Any]:
+ """The output line of `point`, measured in this process after `_apply_server_runtime`."""
+ import torch
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ from invokeai.backend.util.devices import TorchDevice
+ from invokeai.backend.working_memory.measurement import measure
+ from invokeai.backend.working_memory.platform import platform_for
+ from invokeai.backend.z_image.denoise_working_memory import estimate_z_image_denoise_working_memory
+ from invokeai.backend.z_image.z_image_controlnet_extension import (
+ ZImageControlNetExtension,
+ z_image_forward_with_control,
+ )
+
+ # The device the node itself takes.
+ device = TorchDevice.choose_torch_device()
+ if device.type != "cuda":
+ raise SystemExit(f"Needs a CUDA or ROCm device; this process would run on {device}.")
+ dtype = getattr(torch, point.dtype)
+
+ def kernel():
+ return sdpa_kernel(SDPBackend.MATH) if point.force_math else nullcontext()
+
+ with torch.inference_mode():
+ # In the forward's kernel regime, so the score matrix is priced for the kernel that runs.
+ with kernel():
+ estimate = estimate_z_image_denoise_working_memory(
+ # The point runs a randomly initialized dense model, which dequantizes nothing per forward.
+ torch.nn.Module(),
+ image_seq_len=image_tokens(point.px),
+ text_seq_len=point.text_tokens,
+ lora_count=0,
+ control_blocks=point.control_blocks,
+ # The ControlNet forward always builds a padding mask; the plain one passes none at batch size 1.
+ has_attention_mask=point.control_blocks > 0,
+ device=device,
+ dtype=dtype,
+ )
+ platform = platform_for(device)
+ facts = _runtime_facts(device, platform.os)
+ common = {
+ "estimator": estimate.estimator,
+ "version": estimate.version,
+ "platform": dataclasses.asdict(platform),
+ "features": dict(estimate.features),
+ "device": facts["device"],
+ }
+
+ transformer = _transformer(point.blocks)
+ adapter = _control_adapter(point.control_blocks) if point.control_blocks else None
+ on_meta = [module for module in (transformer, adapter) if module is not None]
+ weight_bytes = sum(param.numel() for module in on_meta for param in module.parameters()) * dtype.itemsize
+ free, _ = TorchDevice.cuda_mem_get_info(device)
+ raw = {
+ "reservation_bytes": estimate.reservation_bytes,
+ "weight_bytes": weight_bytes,
+ "predicted_bytes": estimate.reservation_bytes + weight_bytes,
+ "free_bytes": free,
+ "runtime": facts,
+ }
+ if raw["predicted_bytes"] > free and not force:
+ return {"status": "skipped", "fit": point.fit, "point": dataclasses.asdict(point), **common, "raw": raw}
+
+ transformer = _materialize(transformer, device, dtype)
+ latent = point.px // LATENT_SCALE_FACTOR
+ x = [torch.randn(16, 1, latent, latent, device=device, dtype=dtype)]
+ t = torch.full((1,), 0.5, device=device, dtype=dtype)
+ cap_feats = [torch.randn(point.text_tokens, CAP_FEAT_DIM, device=device, dtype=dtype)]
+ extension = None
+ if adapter is not None:
+ extension = ZImageControlNetExtension(
+ control_adapter=_materialize(adapter, device, dtype),
+ control_cond=torch.randn(CONTROL_IN_DIM, 1, latent, latent, device=device, dtype=dtype),
+ )
+
+ def forward() -> object:
+ with kernel():
+ if extension is None:
+ return transformer(x=x, t=t, cap_feats=cap_feats)
+ return z_image_forward_with_control(
+ transformer=transformer, x=x, t=t, cap_feats=cap_feats, control_extension=extension
)
- row = {
- "px": px,
- "tokens": unified_tokens(px, text_tokens),
- "blocks": blocks,
- "force_math": force_math,
- "control_blocks": control_blocks,
- }
- # Warm up first: the cold call pays one-off workspace costs the per-token slope must not absorb.
- if _peak_reserved(forward) is None:
- return row | {"oom": True}
- peak = _peak_reserved(forward)
- return row | ({"oom": True} if peak is None else {"oom": False, "reserved_delta": peak})
+ windows = [measure(device, forward)]
+ if "oom" not in windows[0].reasons:
+ windows.append(measure(device, forward))
+ date = datetime.date.today().isoformat()
+ return point_line(point, common=common, provenance=provenance(point, facts, date), windows=windows, raw=raw)
+
+def _measure_in_this_process(request: str) -> None:
+ """Measure one point in this fresh process and print its line.
-def _run_point(px: int, blocks: int, dtype_name: str, force_math: bool, control_blocks: int) -> dict | None:
- args = [str(px), str(TEXT_TOKENS), str(blocks), dtype_name, "1" if force_math else "0", str(control_blocks)]
- proc = subprocess.run([sys.executable, __file__, "--single", *args], capture_output=True, text=True)
- line = proc.stdout.strip().splitlines()[-1] if proc.stdout.strip() else ""
+ Leaves without Python's shutdown, whose HIP teardown can hang on Windows while its DLLs unload (see
+ `invokeai/app/util/rocm_integrated_gpu.py`)."""
+ spec = json.loads(request)
try:
- return json.loads(line)
- except Exception:
- tail = proc.stderr.strip().splitlines()[-1:] or ["(no stderr)"]
- print(f" FAILED {' '.join(args)}: {tail[0]}")
- return None
+ _apply_server_runtime(spec["alloc_conf"])
+ line = _measure(Point(**spec["point"]), spec["force"])
+ except BaseException:
+ traceback.print_exc()
+ sys.stderr.flush()
+ os._exit(1)
+ print(RESULT_PREFIX + json.dumps(line), flush=True)
+ sys.stderr.flush()
+ os._exit(0)
+
+
+# The driving process: plans the points, measures each in a fresh process, appends the lines, prints the table.
+
+
+def _run(point: Point, alloc_conf: str, force: bool) -> dict[str, Any]:
+ request = json.dumps({"point": dataclasses.asdict(point), "alloc_conf": alloc_conf, "force": force})
+ command = [sys.executable, str(Path(__file__).resolve()), "--single", request]
+ try:
+ done = subprocess.run(command, capture_output=True, text=True, errors="replace", timeout=POINT_TIMEOUT_S)
+ except subprocess.TimeoutExpired:
+ return failed_line(point, f"no result within {POINT_TIMEOUT_S} s")
+ for output in done.stdout.splitlines():
+ if output.startswith(RESULT_PREFIX):
+ return json.loads(output[len(RESULT_PREFIX) :])
+ tail = done.stderr.strip().splitlines()[-1:] or ["no output"]
+ return failed_line(point, f"exit code {done.returncode}: {tail[0]}")
+
+
+_COLUMNS = f"{'kind':>9} {'dtype':>8} {'blocks':>6} {'control':>7} {'px':>5} {'text':>5} {'tokens':>7}"
+
+
+def _grid(point: Mapping[str, Any]) -> str:
+ return (
+ f"{point['kind']:>9} {point['dtype']:>8} {point['blocks']:>6} {point['control_blocks']:>7} "
+ f"{point['px']:>5} {point['text_tokens']:>5}"
+ )
+
+
+def _gib(value: int | None) -> str:
+ return "" if value is None else f"{value / GIB:.3f}"
+
+
+def _row(line: Mapping[str, Any]) -> str:
+ head = f"{_grid(line['point'])} {line.get('features', {}).get('tokens', ''):>7}"
+ status = line["status"]
+ raw = line.get("raw", {})
+ cold, warm = (_gib(raw[run]["demand"]) if run in raw else "" for run in ("cold", "warm"))
+ if status == "point":
+ return f"{head} {_gib(line['measured_bytes']):>10} {cold:>8} {warm:>8} {line['method']}"
+ if status == "invalid":
+ return f"{head} {'invalid':>10} {cold:>8} {warm:>8} {', '.join(line['reasons'])}"
+ if status == "skipped":
+ raw = line["raw"]
+ return (
+ f"{head} {'skipped':>10} needs ~{raw['predicted_bytes'] / GIB:.1f} GiB, {raw['free_bytes'] / GIB:.1f} GiB "
+ "free (--force runs it)"
+ )
+ return f"{head} {'FAILED':>10} {line['error']}"
+
+def _runtime_header(facts: Mapping[str, Any], platform: Mapping[str, str]) -> str:
+ rocm = ""
+ if facts["hip"]:
+ guard = "installed" if facts["rocm_sdpa_guard"] else "NOT installed"
+ rocm = f" | {AOTRITON_EXPERIMENTAL_ENV}={facts['aotriton_experimental'] or 'unset'} | SDPA guard {guard}"
+ return (
+ f"{facts['device']} | torch {facts['torch']} | {'/'.join(platform.values())} | {_alloc_conf(facts)}{rocm} | "
+ f"estimator from {facts['estimator_module']}"
+ )
-def report(
- dtype_name: str, blocks: int, extra_blocks: int | None, control_blocks: int, max_px: int, force: bool
-) -> None:
- dtype = DTYPES[dtype_name]
- sizes = [px for px in SIZES if px <= max_px]
- free, _ = torch.cuda.mem_get_info()
- print(f"{'kernel':>7} {'blocks':>6} {'control':>7} {'px':>5} {'tokens':>7} {'reserved(GiB)':>14}")
- print("-" * 52)
- def run(kernel: str, count: int, px: int, force_math: bool, control: int) -> int | None:
- need = predicted_bytes(px, count, dtype, force_math, control)
- if need > free and not force:
+def _tokens(line: Mapping[str, Any]) -> int:
+ return line["features"]["tokens"]
+
+
+def _px(line: Mapping[str, Any]) -> int:
+ return line["point"]["px"]
+
+
+def _summarize_fit(lines: Sequence[Mapping[str, Any]], text_tokens: int) -> None:
+ measured = [line for line in lines if line["status"] == "point"]
+ grid = [line for line in measured if line["fit"]]
+ # The line's slopes from the points that fit it; the extra-blocks forward compares with any grid point.
+ fit = [line for line in grid if line["in_fit"]]
+ for dtype in dict.fromkeys(line["point"]["dtype"] for line in fit):
+ of_dtype = [line for line in fit if line["point"]["dtype"] == dtype]
+ main = sorted((line for line in of_dtype if line["point"]["text_tokens"] == text_tokens), key=_tokens)
+ for line in main:
+ print(f"{dtype}, {_px(line)}px: {line['measured_bytes'] / _tokens(line) / MIB:.4f} MiB per attended token")
+ if len(main) >= 2:
+ lo, hi = main[0], main[-1]
+ slope = (hi["measured_bytes"] - lo["measured_bytes"]) / (_tokens(hi) - _tokens(lo))
+ base = lo["measured_bytes"] - slope * _tokens(lo)
+ print(f"{dtype}, {_px(lo)}-{_px(hi)}px: {slope / MIB:.4f} MiB per token, intercept {base / GIB:.3f} GiB")
+ for short in (line for line in of_dtype if line["point"]["text_tokens"] != text_tokens):
+ long = next((line for line in main if _px(line) == _px(short)), None)
+ if long is not None and _tokens(long) != _tokens(short):
+ slope = (long["measured_bytes"] - short["measured_bytes"]) / (_tokens(long) - _tokens(short))
+ print(
+ f"{dtype}, {_px(short)}px, caption of {short['point']['text_tokens']} -> {text_tokens} tokens: "
+ f"{slope / MIB:.4f} MiB per caption token"
+ )
+ for line in (line for line in measured if line["point"]["kind"] == "blocks"):
+ same = ("px", "text_tokens", "dtype")
+ base = next((ref for ref in grid if all(ref["point"][key] == line["point"][key] for key in same)), None)
+ if base is not None:
+ extra = line["measured_bytes"] - base["measured_bytes"]
print(
- f"{kernel:>7} {count:>6} {control:>7} {px:>5} {'':>7} {'skipped':>14}"
- f" needs ~{need / GIB:.1f} GiB, {free / GIB:.1f} GiB free"
+ f"{line['point']['blocks']} against {base['point']['blocks']} main blocks, {line['point']['dtype']}, "
+ f"{_px(line)}px: {extra / MIB:+.0f} MiB ({line['measured_bytes'] / base['measured_bytes']:.3f}x)"
)
- return None
- row = _run_point(px, count, dtype_name, force_math, control)
- if row is None or row.get("oom"):
- print(f"{kernel:>7} {count:>6} {control:>7} {px:>5} {'':>7} {'OOM':>14}")
- return None
- print(f"{kernel:>7} {count:>6} {control:>7} {px:>5} {row['tokens']:>7} {row['reserved_delta'] / GIB:>14.3f}")
- return row["reserved_delta"]
-
- counts = [blocks] + ([extra_blocks] if extra_blocks else [])
- fused: dict[int, dict[int, int]] = {}
- for count in counts:
- for px in sizes:
- if (peak := run("auto", count, px, False, 0)) is not None:
- fused.setdefault(count, {})[px] = peak
- math_peak = run("math", blocks, SIZES[0], True, 0)
- control_peak = run("auto", blocks, SIZES[0], False, control_blocks) if control_blocks else None
- print()
- for count, peaks in fused.items():
- for px, peak in peaks.items():
- tokens = unified_tokens(px, TEXT_TOKENS)
- print(f"auto kernel, {count} blocks, {px}px: {peak / tokens / MIB:.4f} MB per attended token")
- if len(peaks) >= 2:
- lo, hi = min(peaks), max(peaks)
- slope = (peaks[hi] - peaks[lo]) / (unified_tokens(hi, TEXT_TOKENS) - unified_tokens(lo, TEXT_TOKENS))
- base = peaks[lo] - slope * unified_tokens(lo, TEXT_TOKENS)
- print(f"auto kernel, {count} blocks: {slope / MIB:.4f} MB/token, intercept {base / GIB:.3f} GiB")
-
- tokens = unified_tokens(SIZES[0], TEXT_TOKENS)
- reference = fused.get(blocks, {}).get(SIZES[0])
- if math_peak is not None and reference is not None:
- extra = math_peak - reference
- charged = Z_IMAGE_ATTENTION_HEADS * tokens * tokens * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
- print(
- f"math kernel, {SIZES[0]}px: {extra / GIB:.3f} GiB over the auto kernel, "
- f"{extra / (Z_IMAGE_ATTENTION_HEADS * tokens * tokens):.2f} bytes/score element; shipped constant charges "
- f"{charged / GIB:.3f} GiB ({SDPA_MATH_BYTES_PER_SCORE_ELEMENT})"
- )
- if control_peak is not None and reference is not None:
- extra = control_peak - reference
- hint_bytes = tokens * Z_IMAGE_HIDDEN_SIZE * dtype.itemsize
- print(
- f"control, {control_blocks} blocks, {SIZES[0]}px: {extra / GIB:.3f} GiB over no control, "
- f"{extra / hint_bytes:.2f} hint-sized tensors; the estimate charges n + 4 = {control_blocks + 4}"
+
+def _summarize_checks(lines: Sequence[Mapping[str, Any]]) -> None:
+ from invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ from invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_ATTENTION_HEADS, Z_IMAGE_HIDDEN_SIZE
+
+ measured = [line for line in lines if line["status"] == "point"]
+ for line in (line for line in measured if line["point"]["kind"] in ("math", "control")):
+ point = line["point"]
+ reference = next(
+ (
+ ref
+ for ref in measured
+ if ref["point"]["kind"] == "reference" and ref["point"]["dtype"] == point["dtype"]
+ ),
+ None,
)
+ if reference is None:
+ print(f"{point['kind']}, {point['dtype']}: no default-kernel forward to compare with")
+ continue
+ extra = line["measured_bytes"] - reference["measured_bytes"]
+ charged = line["raw"]["reservation_bytes"] - reference["raw"]["reservation_bytes"]
+ tokens = _tokens(line)
+ if point["kind"] == "math":
+ elements = Z_IMAGE_ATTENTION_HEADS * tokens * tokens
+ print(
+ f"math kernel, {point['dtype']}, {point['px']}px: {extra / GIB:.3f} GiB over the default kernel, "
+ f"{extra / elements:.2f} bytes per score element; the estimate adds {charged / GIB:.3f} GiB "
+ f"({SDPA_MATH_BYTES_PER_SCORE_ELEMENT} bytes per element, one chunk where the ROCm guard chunks)"
+ )
+ else:
+ hint_bytes = tokens * Z_IMAGE_HIDDEN_SIZE * (4 if point["dtype"] == "float32" else 2)
+ blocks = point["control_blocks"]
+ print(
+ f"control, {blocks} blocks, {point['dtype']}, {point['px']}px: {extra / GIB:.3f} GiB over no control, "
+ f"{extra / hint_bytes:.2f} hint-sized tensors; the estimate adds {charged / GIB:.3f} GiB "
+ f"({blocks} + 4 hints, and any score matrix the mask brings)"
+ )
+
+
+def _print_plan(points: Sequence[Point]) -> None:
+ from invokeai.backend.z_image.denoise_working_memory import padded_tokens
+
+ print(_COLUMNS)
+ for point in points:
+ tokens = padded_tokens(image_tokens(point.px)) + padded_tokens(point.text_tokens)
+ print(f"{_grid(dataclasses.asdict(point))} {tokens:>7}{' forced math' if point.force_math else ''}")
+ print(f"{len(points)} forwards, one process each")
+
+
+def _sizes(text: str) -> list[int]:
+ try:
+ sizes = [int(part) for part in text.split(",") if part.strip()]
+ except ValueError:
+ raise argparse.ArgumentTypeError(f"not a comma-separated list of sizes: {text!r}")
+ multiple = LATENT_SCALE_FACTOR * PATCH_SIZE
+ if any(px <= 0 or px % multiple for px in sizes):
+ raise argparse.ArgumentTypeError(f"sizes must be positive multiples of {multiple} px, got {text!r}")
+ return sizes
+
+
+def _dtypes(text: str) -> list[str]:
+ names = [part.strip() for part in text.split(",") if part.strip()]
+ if not names or not set(names) <= set(DTYPES):
+ raise argparse.ArgumentTypeError(f"dtypes must be among {', '.join(DTYPES)}, got {text!r}")
+ return names
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--dtype", choices=list(DTYPES), default="bfloat16")
+ parser.add_argument("--mode", choices=("fit", "math", "control"), default="fit", help="Default: fit.")
+ parser.add_argument("--out", type=Path, help="The JSON-lines file the lines are appended to. Required to measure.")
+ parser.add_argument("--sizes", type=_sizes, default="512,768,1024,1440,2048", help="The fit grid's sizes, px.")
+ parser.add_argument("--dtypes", type=_dtypes, default=",".join(DTYPES), help="Default: all three.")
+ parser.add_argument("--text-tokens", type=int, default=512, help="The caption at every size. Default 512.")
+ parser.add_argument("--short-text-tokens", type=int, default=77, help="The text-slope caption. Default 77.")
+ parser.add_argument(
+ "--short-text-sizes", type=_sizes, default="1024,1440", help="Fit sizes that also run the text-slope caption."
+ )
parser.add_argument("--blocks", type=int, default=2, help="Main transformer blocks. Default 2.")
- parser.add_argument("--extra-blocks", type=int, default=None, help="Measure a second block count as well.")
- parser.add_argument("--control-blocks", type=int, default=15, help="ControlNet blocks; 0 skips. Default 15.")
- parser.add_argument("--max-px", type=int, default=SIZES[-1], help="Largest fused-kernel size to measure.")
+ parser.add_argument("--extra-blocks", type=int, default=0, help="Fit mode: this block count at 1024px as well.")
+ parser.add_argument("--control-blocks", type=int, default=15, help="The control check's adapter. Default 15.")
+ parser.add_argument(
+ "--alloc-conf",
+ default="",
+ help="The allocator configuration, as the server's pytorch_cuda_alloc_conf. Empty: the platform's default.",
+ )
parser.add_argument("--force", action="store_true", help="Run points predicted not to fit free device memory.")
- parser.add_argument("--single", nargs="*", default=None, help=argparse.SUPPRESS)
+ parser.add_argument("--dry-run", action="store_true", help="Print the planned points without touching a device.")
+ parser.add_argument("--single", help=argparse.SUPPRESS)
args = parser.parse_args()
- if not torch.cuda.is_available():
- raise SystemExit("No CUDA/HIP device available.")
- if args.single:
- px, text_tokens, blocks, dtype_name, force_math, control_blocks = args.single
- row = measure(
- int(px), int(text_tokens), int(blocks), DTYPES[dtype_name], force_math == "1", int(control_blocks)
- )
- print(json.dumps(row))
+ if args.single is not None:
+ _measure_in_this_process(args.single)
return
- print(
- f"torch {torch.__version__} | device {torch.cuda.get_device_name(0)} | hip={torch.version.hip} | {args.dtype}"
+ points = plan(
+ args.mode,
+ sizes=args.sizes,
+ dtypes=args.dtypes,
+ text_tokens=args.text_tokens,
+ short_text_tokens=args.short_text_tokens,
+ short_text_sizes=args.short_text_sizes,
+ blocks=args.blocks,
+ extra_blocks=args.extra_blocks,
+ control_blocks=args.control_blocks,
)
- report(args.dtype, args.blocks, args.extra_blocks, args.control_blocks, args.max_px, args.force)
+ if args.dry_run:
+ _print_plan(points)
+ return
+ if args.out is None:
+ parser.error("--out is required to measure")
+ exported = [var for var in ALLOCATOR_CONF_ENV_VARS if os.environ.get(var)]
+ if args.alloc_conf and exported:
+ # The server keeps an exported value and only warns; a measurement must not run another allocator than asked.
+ parser.error(f"--alloc-conf cannot apply while {', '.join(exported)} is set in the environment")
+
+ from invokeai.app.util.rocm_integrated_gpu import hide_integrated_gpus_on_rocm_windows
+ from invokeai.backend.util.logging import InvokeAILogger
+
+ # The runtime's integrated-GPU check, once for the whole run, before torch is imported anywhere: the measuring
+ # processes inherit the HIP_VISIBLE_DEVICES it sets instead of each asking HIP in a child process of its own.
+ hide_integrated_gpus_on_rocm_windows(InvokeAILogger.get_logger(LOGGER_NAME))
+
+ print(f"{len(points)} forwards, one fresh process each")
+ lines: list[dict[str, Any]] = []
+ with args.out.open("a", encoding="utf-8") as out:
+ for point in points:
+ line = _run(point, args.alloc_conf, args.force)
+ if "raw" in line and not any("raw" in earlier for earlier in lines):
+ print(_runtime_header(line["raw"]["runtime"], line["platform"]))
+ if not lines:
+ print(f"{_COLUMNS} {'demand GiB':>10} {'cold':>8} {'warm':>8}")
+ record = file_record(line)
+ if record is not None:
+ out.write(json.dumps(record) + "\n")
+ out.flush()
+ print(_row(line), flush=True)
+ lines.append(line)
+
+ print()
+ if args.mode == "fit":
+ _summarize_fit(lines, args.text_tokens)
+ else:
+ _summarize_checks(lines)
+ statuses = [line["status"] for line in lines]
+ counts = ", ".join(f"{statuses.count(status)} {status}" for status in ("point", "invalid", "skipped", "failed"))
+ print(f"{counts}; the points appended to {args.out}")
if __name__ == "__main__":
diff --git a/scripts/working_memory/build_shipped.py b/scripts/working_memory/build_shipped.py
index 9d9cf2d22b..cc7ebc8dea 100644
--- a/scripts/working_memory/build_shipped.py
+++ b/scripts/working_memory/build_shipped.py
@@ -1,19 +1,29 @@
-"""Shipped working-memory points and fitted values from calibration store exports.
+"""Shipped working-memory points and fitted values from calibration store exports and calibration point files.
- python -m scripts.working_memory.build_shipped EXPORT [EXPORT ...] [--data-dir DIR] [--write]
+ python -m scripts.working_memory.build_shipped [EXPORT ...] [--points FILE ...] [--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
+`platform_for` gives on the machine the export came from (`platform.platform_for_environment`).
+
+A point file is what a calibration script such as `scripts/calibrate_z_image_working_memory.py` writes: one JSON
+object per line, a `MeasuredPoint`'s fields and any other keys, which are ignored. Its points are fresh-process
+measurements, so they hold the upper bound as well. A point that tests an analytic term or an assumption rather than
+the line says `in_fit: false`: a check's (a forced math kernel, a ControlNet, more blocks), and a fit-grid forward whose
+features its estimator's line does not admit (`fit.Line.fits`), such as one with a materialized score matrix. It ships
+as an out-of-fit point that bounds its estimate from below only.
+
+A point joins the data file that declares its estimator's coefficients, keeping the larger of itself and a shipped
+point of the same measurement (`point_identity`), and says which it kept; 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. A `legacy` entry is replaced by its fit where the points fit every line it carries and each line has a point
+that holds the upper bound, a fresh-process one: probe windows alone never replace hand-set values. It keeps them
+otherwise.
+
+Without `--write` the changes are printed only. An export or point of another estimator version than the registered
+spec, or 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.
"""
@@ -28,7 +38,7 @@ 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 typing import Any, get_args
from pydantic import ValidationError
@@ -45,29 +55,42 @@ from invokeai.backend.working_memory.coefficients import (
WorkingMemoryData,
load_data,
)
+from invokeai.backend.working_memory.estimate import FeatureValue
from invokeai.backend.working_memory.fit import (
+ EntryKey,
+ FitPoint,
capping_spans,
+ entry_fit,
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.platform import (
+ Allocator,
+ ConvBackend,
+ OperatingSystem,
+ 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."
+REFIT_NOTE = "Refitted on its 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."
+ "fresh-process points at two sizes at least twice apart measure their line."
)
_RUNTIME_FACTS = ("cuda", "hip", "cudnn", "miopen", "xpu")
+PointIdentity = tuple[str, int, str, str, str, str, bool]
+"""What makes two points one measurement (`point_identity`)."""
+
class BuildError(ValueError):
pass
@@ -107,17 +130,19 @@ class Spread:
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`."""
+ """Windows or records left out, by reason."""
+ spreads: dict[PointIdentity, Spread] = field(default_factory=dict)
+ """By `point_identity`; the points built from export windows only."""
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."""
+def point_identity(point: MeasuredPoint) -> PointIdentity:
+ """What a newer point of the same measurement replaces: estimator, version, platform, card, method and features,
+ and whether it is in the fit. A check can share its features with a fit point, as a forward with more blocks does,
+ and must not take its place."""
return (
point.estimator,
point.version,
@@ -125,6 +150,7 @@ def point_identity(point: MeasuredPoint) -> tuple[str, int, str, str, str, str]:
point.device,
point.method,
_canonical(point.features),
+ point.in_fit,
)
@@ -145,14 +171,23 @@ def _load_export(path: Path) -> CalibrationStoreFile:
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})"
- )
+def _registered_spec(where: str, estimator: str, version: int, specs: Mapping[str, EstimatorSpec]) -> EstimatorSpec:
+ spec = specs.get(estimator)
+ if spec is None:
+ raise BuildError(f"{where}: no registered estimator is called {estimator!r}")
+ if version != spec.version:
+ raise BuildError(
+ f"{where}: {estimator} version {version}, the registered estimator is version {spec.version}; measure "
+ "again with this version"
+ )
+ return spec
+
+
+def _check_features(where: str, features: Mapping[str, FeatureValue], spec: EstimatorSpec) -> None:
try:
- spec.terms(window.features, dict.fromkeys(spec.coefficients, 1.0))
+ spec.terms(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
+ raise BuildError(f"{where}: the estimator cannot evaluate its features {dict(features)}: {e!r}") from e
def _provenance(best: _Window, count: int) -> str:
@@ -193,14 +228,7 @@ def build_points(
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"
- )
+ spec = _registered_spec(str(path), window.estimator, window.version, specs)
if not window.valid:
skipped["invalid"] += 1
continue
@@ -211,7 +239,11 @@ def build_points(
# 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)
+ where = (
+ f"{path}: {window.estimator} window of node {window.node_type} {window.node_id} "
+ f"(item {window.queue_item_id})"
+ )
+ _check_features(where, window.features, 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")
@@ -238,7 +270,7 @@ def build_points(
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)
+ flagged = _fragmented_attempts(ordered, specs)
points = []
spreads = {}
for group, windows in ordered.items():
@@ -269,7 +301,9 @@ _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]]:
+def _fragmented_attempts(
+ groups: Mapping[_Group, Sequence[_Window]], specs: Mapping[str, EstimatorSpec]
+) -> 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."""
@@ -277,10 +311,10 @@ def _fragmented_attempts(groups: Mapping[_Group, Sequence[_Window]]) -> set[tupl
measurements: list[Measurement] = []
for group, windows in groups.items():
card, estimator, version, platform, _ = group
- found = line_of(windows[0].point.features)
+ found = specs[estimator].line(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]
+ line: object = group if found is None else (card, estimator, version, platform, found.suffix)
+ size = 0 if found is None else found.size
by_attempt: dict[tuple[Path, str], list[_Window]] = {}
for window in windows:
by_attempt.setdefault((window.export, window.attempt), []).append(window)
@@ -289,7 +323,7 @@ def _fragmented_attempts(groups: Mapping[_Group, Sequence[_Window]]) -> set[tupl
measurements.append(
Measurement(
line=line,
- pixels=pixels,
+ size=size,
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],
@@ -298,6 +332,76 @@ def _fragmented_attempts(groups: Mapping[_Group, Sequence[_Window]]) -> set[tupl
return {key for key, flag in zip(keys, fragmented(measurements), strict=True) if flag}
+def _record_platform(where: str, platform: Mapping[str, str], entries: Sequence[CoefficientEntry]) -> dict[str, str]:
+ """A point file record's platform as the data names it (`point_platform`). A record names the OS where it measured
+ an OS-specific entry's platform, and may name it anywhere; one that does not measured what holds on every OS."""
+ named = {"os": "other"} | dict(platform)
+ choices = {"conv_backend": ConvBackend, "allocator": Allocator, "os": OperatingSystem}
+ problems = [f"no {key}" for key in sorted(choices.keys() - named.keys())] + [
+ f"{key}={value!r}" for key, value in named.items() if key not in choices or value not in get_args(choices[key])
+ ]
+ if problems:
+ raise BuildError(f"{where}: platform {dict(platform)} is no platform the data keys points by: {problems}")
+ measured = Platform(**named) # type: ignore[arg-type]
+ if not is_measured(measured):
+ raise BuildError(
+ f"{where}: measured on {measured}, which `platform.MEASURED` does not list; ship coefficient entries for "
+ "it first"
+ )
+ return point_platform(measured, entries)
+
+
+def read_point_files(
+ paths: Sequence[Path], specs: Mapping[str, EstimatorSpec], entries: Sequence[CoefficientEntry]
+) -> Build:
+ """The fresh-process points of calibration point files: per measurement (`point_identity`) the largest, and the
+ records left out.
+
+ A record is a JSON object on a line of its own: a `MeasuredPoint`'s fields (`estimator`, `version`, `platform`,
+ `features`, `measured_bytes`, `method`, `device`, `provenance`, optionally `in_fit` and `max_ratio`) and any other
+ keys, which are ignored. A fresh-process point holds the upper bound, so a `probe_demand` record is refused: probe
+ windows come from exports.
+ """
+ best: dict[PointIdentity, MeasuredPoint] = {}
+ skipped: Counter[str] = Counter()
+ for path in paths:
+ try:
+ lines = path.read_text(encoding="utf-8").splitlines()
+ except OSError as e:
+ raise BuildError(f"{path}: not readable: {e}") from e
+ for number, text in enumerate(lines, start=1):
+ if not text.strip():
+ continue
+ where = f"{path}:{number}"
+ try:
+ record = json.loads(text)
+ except json.JSONDecodeError as e:
+ raise BuildError(f"{where}: not a JSON object: {e}") from e
+ if not isinstance(record, dict):
+ raise BuildError(f"{where}: not a JSON object")
+ try:
+ point = MeasuredPoint.model_validate(
+ {key: value for key, value in record.items() if key in MeasuredPoint.model_fields}
+ )
+ except ValidationError as e:
+ raise BuildError(f"{where}: not a measured point: {e}") from e
+ if not point.holds_upper_bound:
+ raise BuildError(
+ f"{where}: a {point.method} point bounds its estimate from below only; a point file holds "
+ "fresh-process measurements, and probe windows come from exports"
+ )
+ spec = _registered_spec(where, point.estimator, point.version, specs)
+ _check_features(where, point.features, spec)
+ point = point.model_copy(update={"platform": _record_platform(where, point.platform, entries)})
+ identity = point_identity(point)
+ kept = best.get(identity)
+ if kept is not None:
+ skipped["remeasured, the larger kept"] += 1
+ if kept is None or point.measured_bytes > kept.measured_bytes:
+ best[identity] = point
+ return Build(points=list(best.values()), skipped=skipped)
+
+
def merge_points(
data: Mapping[str, WorkingMemoryData], points: Sequence[MeasuredPoint]
) -> dict[str, WorkingMemoryData]:
@@ -308,7 +412,7 @@ def merge_points(
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}
+ new: dict[str, dict[PointIdentity, MeasuredPoint]] = {name: {} for name in data}
for point in points:
owner = owners.get(point.estimator)
if owner is None:
@@ -325,12 +429,38 @@ def merge_points(
return merged
-def refit(data: Mapping[str, WorkingMemoryData]) -> dict[str, WorkingMemoryData]:
+FITTED_LEGACY_PROVENANCE = (
+ "The fit of this platform's in-fit points by scripts/working_memory/build_shipped.py, in place of hand-set legacy "
+ "values. Each point's provenance names what measured it."
+)
+"""The provenance of a `legacy` entry its points now fit: its hand-set provenance describes values it no longer
+carries."""
+
+
+def legacy_fit(
+ entry: CoefficientEntry, groups: Mapping[tuple[EntryKey, str], Sequence[FitPoint]]
+) -> tuple[dict[str, int], dict[str, str]]:
+ """The fit that would replace a `legacy` entry's hand-set values (`fit.entry_fit` on `groups`), and per line why
+ its points cannot: they do not fit it, as its fresh-process points do not span (`fit.capping_spans`), or none of
+ them holds the upper bound (`MeasuredPoint.holds_upper_bound`). A probe window raises a line but never caps one,
+ so probe windows alone never replace hand-set values."""
+ values, problems = entry_fit(entry, groups)
+ for suffix in problems:
+ line = groups.get((entry_key(entry), suffix), [])
+ if line and not any(point.caps for point in line):
+ problems[suffix] = f"only {METHOD} points measure it, which bound it from below only"
+ return values, dict(sorted(problems.items()))
+
+
+def refit(data: Mapping[str, WorkingMemoryData], specs: Mapping[str, EstimatorSpec]) -> 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())
+ it from below only, so they never lower it. A `legacy` entry whose points fit every line it carries, each line
+ with a point that holds the upper bound (`legacy_fit`), is fitted from then on too; one they do not keeps its
+ hand-set values."""
+ groups = fit_points(data.values(), specs)
+ replaced: set[EntryKey] = set()
def raised_stand_ins(entry: CoefficientEntry) -> dict[str, float]:
values = entry.values or {}
@@ -340,7 +470,7 @@ def refit(data: Mapping[str, WorkingMemoryData]) -> dict[str, WorkingMemoryData]
if not line:
continue
try:
- k, b = shipped_pair([(point.pixels, point.bytes) for point in line])
+ k, b = shipped_pair([(point.size, 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
@@ -348,18 +478,25 @@ def refit(data: Mapping[str, WorkingMemoryData]) -> dict[str, WorkingMemoryData]
raised[f"b_{suffix}"] = max(values[f"b_{suffix}"], b)
return raised
- def measured_lines_fitted(entry: CoefficientEntry) -> CoefficientEntry:
+ def staged(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})
+ entry = entry.model_copy(update={"stand_ins": stand_ins})
+ if not entry.legacy:
+ return entry
+ values, problems = legacy_fit(entry, groups)
+ if not values or problems:
+ return entry
+ replaced.add(entry_key(entry))
+ return entry.model_copy(update={"legacy": False, "provenance": FITTED_LEGACY_PROVENANCE})
- staged = {
- name: file.model_copy(update={"coefficients": [measured_lines_fitted(entry) for entry in file.coefficients]})
+ staged_data = {
+ name: file.model_copy(update={"coefficients": [staged(entry) for entry in file.coefficients]})
for name, file in data.items()
}
try:
- fitted = fitted_values(staged.values())
+ fitted = fitted_values(staged_data.values(), specs)
except ValueError as e:
raise BuildError(f"the points cannot fit a line: {e}") from e
@@ -379,29 +516,50 @@ def refit(data: Mapping[str, WorkingMemoryData]) -> dict[str, WorkingMemoryData]
(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:
+ if changed and note not in provenance and not (note == REFIT_NOTE and entry_key(entry) in replaced):
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()
+ for name, file in staged_data.items()
}
+def legacy_notes(
+ data: Mapping[str, WorkingMemoryData], new_points: Sequence[MeasuredPoint], specs: Mapping[str, EstimatorSpec]
+) -> list[str]:
+ """Per `legacy` entry of an estimator the new points measured, why it keeps its hand-set values: no in-fit point
+ measures its platform, or the lines its points cannot replace (`legacy_fit`)."""
+ measured = {point.estimator for point in new_points}
+ groups = fit_points(data.values(), specs)
+ notes = []
+ for entry in (entry for file in data.values() for entry in file.coefficients):
+ if not entry.legacy or entry.estimator not in measured:
+ continue
+ if not any(key == entry_key(entry) for key, _ in groups):
+ reasons = "no in-fit point measures this platform"
+ else:
+ _, problems = legacy_fit(entry, groups)
+ reasons = "; ".join(f"{suffix}: {problem}" for suffix, problem in problems.items())
+ notes.append(f"note: {entry.estimator} {entry.platform} stays legacy: {reasons}")
+ return notes
+
+
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()))
+ spec = specs[point.estimator]
+ violation = bound_violation(point, spec, evaluate_point(point, spec, data.values()))
if violation is not None:
- violations.append(f"{point_id(point)}: {violation}")
+ violations.append(f"{point_id(point, spec)}: {violation}")
return violations
@dataclass(frozen=True)
class LineChange:
- """A carried convolution line the refit moves, with the new points it is fitted on."""
+ """A carried line the refit moves, with the new points it is fitted on."""
file: str
entry: CoefficientEntry
@@ -412,24 +570,29 @@ class LineChange:
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`)."""
+ def fragmented(self, spreads: Mapping[PointIdentity, Spread]) -> list[MeasuredPoint]:
+ """The new points on a raised line whose windows are flagged as fragmentation (`Spread.fragmented`). A point
+ of a point file ran in a fresh process and has no windows to flag."""
if not self.raised:
return []
- return [point for point in self.points if spreads[point_identity(point)].fragmented]
+ flagged = (spreads.get(point_identity(point)) for point in self.points)
+ return [point for point, spread in zip(self.points, flagged, strict=True) if spread and spread.fragmented]
def review_lines(
- before: Mapping[str, WorkingMemoryData], after: Mapping[str, WorkingMemoryData], new_points: Sequence[MeasuredPoint]
+ before: Mapping[str, WorkingMemoryData],
+ after: Mapping[str, WorkingMemoryData],
+ new_points: Sequence[MeasuredPoint],
+ specs: Mapping[str, EstimatorSpec],
) -> 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]):
+ for line in fit_points([single], specs):
lines.setdefault(line, []).append(point)
- fitted_on = fit_points(after.values())
+ fitted_on = fit_points(after.values(), specs)
changes = []
for name, file in after.items():
old_entries = {entry_key(entry): entry for entry in before[name].coefficients}
@@ -441,7 +604,7 @@ def review_lines(
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), [])}
+ sizes = {p.size 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))
@@ -484,20 +647,25 @@ 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],
+ spreads: Mapping[PointIdentity, 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}
+ """One line per point added or remeasured, with the spread of its windows, carried value refitted, stand-in
+ now fitted, and legacy entry now fitted. A remeasurement below the shipped point says that the shipped one stays."""
+ new = {point_identity(point): 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))
+ remeasured = new[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 remeasured.measured_bytes < old.measured_bytes:
+ lines.append(
+ f"{where} kept shipped {old.measured_bytes} over remeasured {remeasured.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}
@@ -511,6 +679,8 @@ def describe_changes(
)
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")
+ if old_entry.legacy and not entry.legacy:
+ lines.append(f"{name}: {entry.estimator} {entry.platform} is fitted now, no longer legacy")
return lines
@@ -538,12 +708,25 @@ def export_paths(arguments: Sequence[Path]) -> list[Path]:
return paths
+def _left_out(skipped: Counter[str]) -> str:
+ return ", ".join(f"{count} {reason}" for reason, count in sorted(skipped.items())) or "none"
+
+
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/)"
+ "exports", nargs="*", type=Path, help="calibration store exports, or directories of them (a run's calibration/)"
+ )
+ parser.add_argument(
+ "--points",
+ nargs="+",
+ action="extend",
+ type=Path,
+ default=[],
+ metavar="FILE",
+ help="point files a calibration script wrote: fresh-process points, one JSON object per line",
)
parser.add_argument(
"--data-dir", type=Path, default=DATA_DIR, help=f"the working-memory data files (default {DATA_DIR})"
@@ -555,6 +738,8 @@ def main(argv: Sequence[str] | None = None) -> int:
help="let --write raise a line on points flagged as fragmentation (working_memory/fragmentation.py)",
)
args = parser.parse_args(argv)
+ if not args.exports and not args.points:
+ parser.error("name calibration store exports, --points files, or both")
try:
specs = import_estimator_modules()
@@ -565,16 +750,26 @@ def main(argv: Sequence[str] | None = None) -> int:
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))
+ fresh = read_point_files(args.points, specs, entries)
+ new_points = [*build.points, *fresh.points]
+ after = refit(merge_points(before, new_points), specs)
violations = bound_violations(after, specs)
- reviews = review_lines(before, after, build.points)
+ reviews = review_lines(before, after, new_points, specs)
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)
+ if exports:
+ print(
+ f"{len(build.points)} probe_demand points from {len(exports)} exports; windows left out: "
+ f"{_left_out(build.skipped)}"
+ )
+ if args.points:
+ print(
+ f"{len(fresh.points)} fresh-process points from {len(args.points)} point files; records left out: "
+ f"{_left_out(fresh.skipped)}"
+ )
+ changes = describe_changes(before, after, new_points, build.spreads)
print("\n".join(changes) if changes else "no changes")
for point in build.points:
spread = build.spreads[point_identity(point)]
@@ -593,6 +788,8 @@ def main(argv: Sequence[str] | None = None) -> int:
f"{'raised' if change.raised else 'lowered'}, {len(change.points)} new points on it"
+ (f", {len(flagged)} flagged as fragmentation" if flagged else "")
)
+ for note in legacy_notes(after, new_points, specs):
+ print(note)
if violations:
print(
"error: not written: the bounds of these points reject the result (working_memory/bounds.py):\n"
diff --git a/tests/app/invocations/test_denoise_noise_inputs.py b/tests/app/invocations/test_denoise_noise_inputs.py
index 10b47dea7d..f166ae9754 100644
--- a/tests/app/invocations/test_denoise_noise_inputs.py
+++ b/tests/app/invocations/test_denoise_noise_inputs.py
@@ -971,7 +971,7 @@ def test_z_image_invocation_steps_lcm_with_a_seeded_generator(seed: int, expecte
patch(f"{module}.TorchDevice.choose_bfloat16_safe_dtype", return_value=torch.bfloat16),
patch(f"{module}.ZImageRegionalPromptingExtension.from_text_conditionings", return_value=regional_extension),
patch.object(invocation, "_load_text_conditioning", return_value=[]),
- patch.object(invocation, "_estimate_working_memory", return_value=0),
+ patch(f"{module}.estimate_z_image_denoise_working_memory"),
patch.dict(ZIMAGE_SCHEDULER_MAP, {"lcm": _RecordingLCM}),
pytest.raises(_StopAtStep),
):
diff --git a/tests/app/invocations/test_z_image_denoise_schedulers.py b/tests/app/invocations/test_z_image_denoise_schedulers.py
index 3bf005be82..86f408b549 100644
--- a/tests/app/invocations/test_z_image_denoise_schedulers.py
+++ b/tests/app/invocations/test_z_image_denoise_schedulers.py
@@ -99,7 +99,7 @@ def _drive(scheduler: str, denoising_start: float = 0.0, denoising_end: float =
),
patch.object(node, "_load_text_conditioning", return_value=[]),
patch.object(node, "_prepare_noise_tensor", return_value=torch.ones(1, 16, SIZE // 8, SIZE // 8)),
- patch.object(node, "_estimate_working_memory", return_value=0),
+ patch("invokeai.app.invocations.z_image.z_image_denoise.estimate_z_image_denoise_working_memory"),
patch.object(node, "_build_step_callback", return_value=callbacks.append),
):
result = node._run_diffusion(context)
diff --git a/tests/app/invocations/test_z_image_denoise_working_memory.py b/tests/app/invocations/test_z_image_denoise_working_memory.py
index 0fe5698d0b..6237bc90f4 100644
--- a/tests/app/invocations/test_z_image_denoise_working_memory.py
+++ b/tests/app/invocations/test_z_image_denoise_working_memory.py
@@ -5,16 +5,27 @@ Until this estimate existed the node reserved only the per-forward dequant trans
generation needs several times that, and on Windows the driver pages the shortfall into shared system memory instead
of failing: 7.7 GB of it, and a 185 s denoise, on an RX 9060 XT.
-The `MEASURED_*` tables are peak *reserved* memory on CUDA (RTX 4090) in bf16 with a 512-token caption, from
-`scripts/calibrate_z_image_working_memory.py`. Every estimate must stay an upper bound on them.
+The estimate prices with the lines `backend/working_memory/data/denoise.json` ships, the fit of the plain forwards
+measured there, which `tests/backend/working_memory/` holds it to. `TestMeasuredChecks` holds it to what those points
+leave out: a ControlNet adapter's hints and a forced math kernel's score matrix, measured by
+`scripts/calibrate_z_image_working_memory.py` beside the plain forward of the same run.
+
+ROCm with the native allocator off Windows is not measured and still prices with the hand-set `legacy` constants,
+which `TestLegacyReservation` holds byte for byte to the formula the node priced with by hand, frozen below, for every
+transformer that holds no float8 weight. An fp8-stored one also reserves its cast transient, a term of its own
+(`TestEstimate`). Every other platform nothing is measured on prices with a measured one's lines, floored at those
+constants, and `TestUnmeasuredPlatforms` holds it to the formula at least.
MiniMax H3 and Krea-2 add the same dequant transient to their own estimates. Krea-2's wiring is pinned in
`tests/app/invocations/test_krea2_denoise.py` and FLUX.2's in `tests/app/invocations/test_flux2_working_memory.py`;
MiniMax H3's is not, since reaching its `model_on_device()` call needs a packed sequence.
"""
+import itertools
from contextlib import ExitStack, contextmanager, nullcontext
+from dataclasses import dataclass
from types import SimpleNamespace
+from typing import Callable, get_args
from unittest.mock import MagicMock, patch
import pytest
@@ -26,16 +37,25 @@ from invokeai.app.invocations.model import ModelIdentifierField
from invokeai.app.invocations.vae.z_image_image_to_latents import ZImageImageToLatentsInvocation
from invokeai.app.invocations.z_image.z_image_control import ZImageControlField, ZImageControlInvocation
from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
+from invokeai.backend.model_manager.load.load_default import ModelLoader
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
from invokeai.backend.util import attention
-from invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+from invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT, sdpa_score_matrix_bytes
+from invokeai.backend.working_memory import spec as spec_module
+from invokeai.backend.working_memory.coefficients import resolve_coefficients, shipped_coefficients, shipped_data
+from invokeai.backend.working_memory.estimate import WorkingMemoryEstimate, WorkingMemoryTerm
+from invokeai.backend.working_memory.platform import Allocator, ConvBackend, OperatingSystem, Platform, is_measured
+from invokeai.backend.z_image.denoise_working_memory import (
+ Z_IMAGE_DENOISE_SPEC,
+ estimate_z_image_denoise_working_memory,
+)
from invokeai.backend.z_image.extensions.regional_prompting_extension import ZImageRegionalPromptingExtension
from invokeai.backend.z_image.text_conditioning import ZImageRegionalTextConditioning
from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
MB = 1024**2
-GB = 1024**3
# Only the device's type is read: every question the estimate asks about it is answered by `_sdpa` below.
DEVICE = torch.device("cuda")
@@ -55,49 +75,79 @@ def _sdpa(materializes):
yield
-def _estimate(image_seq_len, text_seq_len=512, num_control_blocks=0, has_mask=False, materializes=lambda mask: False):
+def _dense_transformer() -> torch.nn.Module:
+ model = torch.nn.Module()
+ model.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 8)
+ return model
+
+
+def _int8_transformer(out_features: int, device: str = "cpu") -> torch.nn.Module:
+ """An int8_tensorwise build: its layer materializes two weight-sized tensors in the compute dtype per forward."""
+ model = torch.nn.Module()
+ model.proj = Int8ConvrotLinear(
+ torch.zeros(out_features, CONVROT_GROUP_SIZE, dtype=torch.int8, device=device),
+ torch.ones(out_features, 1, device=device),
+ convrot=False,
+ )
+ return model
+
+
+def _estimate(
+ image_seq_len,
+ text_seq_len=512,
+ num_control_blocks=0,
+ has_mask=False,
+ materializes=lambda mask: False,
+ transformer=None,
+ regional_mask=None,
+):
with _sdpa(materializes):
- return ZImageDenoiseInvocation._estimate_working_memory(
+ return estimate_z_image_denoise_working_memory(
+ transformer if transformer is not None else _dense_transformer(),
image_seq_len=image_seq_len,
text_seq_len=text_seq_len,
- num_loras=0,
- num_control_blocks=num_control_blocks,
+ lora_count=0,
+ control_blocks=num_control_blocks,
+ regional_attn_mask=regional_mask,
has_attention_mask=has_mask,
device=DEVICE,
- )
-
-
-def _image_tokens(px: int) -> int:
- return (px // 16) ** 2
+ dtype=torch.bfloat16,
+ ).reservation_bytes
class TestEstimate:
- # (pixels per side, ControlNet blocks, measured peak reserved MiB)
- MEASURED_FUSED = [
- (1024, 0, 1012),
- (1440, 0, 2004),
- (2048, 0, 3942),
- (1024, 1, 1122),
- (1024, 6, 1212),
- (1024, 15, 1650),
- ]
-
- @pytest.mark.parametrize("px, control_blocks, measured_mb", MEASURED_FUSED)
- def test_estimate_is_an_upper_bound_on_measured_peak(self, px, control_blocks, measured_mb):
- """The cache treats the estimate as the amount it must keep free, so under-estimating runs out of memory."""
- assert _estimate(_image_tokens(px), num_control_blocks=control_blocks) >= measured_mb * MB
-
- @pytest.mark.parametrize("px, control_blocks, measured_mb", MEASURED_FUSED)
- def test_estimate_does_not_wildly_over_reserve(self, px, control_blocks, measured_mb):
- """Every byte reserved beyond need is transformer offloaded to RAM and run over PCIe."""
- assert _estimate(_image_tokens(px), num_control_blocks=control_blocks) <= measured_mb * MB + 2 * GB
-
def test_image_and_caption_are_counted_as_the_transformer_pads_them(self):
"""Each run is padded to a multiple of 32 before the two are joined, and the padding is attended too."""
assert _estimate(4096, text_seq_len=97) == _estimate(4096, text_seq_len=128)
assert _estimate(4001, text_seq_len=128) == _estimate(4032, text_seq_len=128)
assert _estimate(4096, text_seq_len=129) > _estimate(4096, text_seq_len=128)
+ def test_a_quantized_transformer_reserves_its_dequant_transient(self):
+ """An int8 layer materializes two weight-sized bf16 tensors per forward, alive alongside the activations."""
+ quantized = _estimate(4096, transformer=_int8_transformer(1024))
+
+ assert quantized - _estimate(4096) == 2 * 1024 * CONVROT_GROUP_SIZE * torch.bfloat16.itemsize
+
+ def test_an_fp8_stored_transformer_reserves_its_largest_layer_widened(self):
+ """FP8 Storage widens a layer's weight and bias to bf16 for its forward, one layer at a time, on top of the
+ line the dense forwards were measured on."""
+ fp8_stored = _dense_transformer()
+ ModelLoader._apply_fp8_to_nn_module(fp8_stored, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
+
+ assert _estimate(4096, transformer=fp8_stored) - _estimate(4096) == (8 * CONVROT_GROUP_SIZE + 8) * 2
+
+ def test_a_dtype_without_a_line_is_refused(self):
+ """Pricing it on another dtype's line would be a guess; the estimator says what is missing instead."""
+ with pytest.raises(ValueError, match=r"'denoise\.z_image' has no torch\.float64 line on Platform\("):
+ estimate_z_image_denoise_working_memory(
+ _dense_transformer(),
+ image_seq_len=4096,
+ text_seq_len=512,
+ lora_count=0,
+ device=DEVICE,
+ dtype=torch.float64,
+ )
+
class TestMaterializedScoreMatrix:
def test_the_score_matrix_is_charged_only_where_it_is_built(self):
@@ -110,46 +160,291 @@ class TestMaterializedScoreMatrix:
assert unmasked == _estimate(4096)
assert masked - unmasked == 30 * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
- def test_estimate_bounds_the_measured_math_kernel(self):
- assert _estimate(_image_tokens(1024), materializes=lambda has_mask: True) >= 9632 * MB
+RTX_4090_NATIVE = Platform("cudnn", "native", "windows")
+RX_9060_XT_EXPANDABLE = Platform("miopen", "expandable", "windows")
-class TestRegionalAttentionBias:
- def test_no_regional_mask_costs_nothing(self):
- assert ZImageDenoiseInvocation._regional_attention_bias_bytes(None, 4096, torch.bfloat16) == 0
+# ControlNet forwards at 1024px with a 512-token caption, measured demand in bytes. 15 blocks: `--mode control`
+# (2026-10-18) beside the plain forward of the same run, 19.50 hint-sized tensors more on the RTX 4090 (19.26 in fp32)
+# and 18.37 on the RX 9060 XT, against the n + 4 = 19 charged. 1 and 6 blocks: the RTX 4090's peak reserved bytes of the
+# script's first runs, 110 and 200 MiB over its plain forward then.
+CONTROL_FORWARDS = [
+ (RTX_4090_NATIVE, "bf16", 15, 1767899136),
+ (RTX_4090_NATIVE, "fp16", 15, 1767899136),
+ (RTX_4090_NATIVE, "fp32", 15, 3244294144),
+ (RX_9060_XT_EXPANDABLE, "bf16", 15, 1633091584),
+ (RX_9060_XT_EXPANDABLE, "fp16", 15, 1668808704),
+ (RTX_4090_NATIVE, "bf16", 1, 1122 * MB),
+ (RTX_4090_NATIVE, "bf16", 6, 1212 * MB),
+]
+# The RTX 4090's forwards with SDPA forced onto the math kernel at 1024px (`--mode math`, 2026-10-18): the whole score
+# matrix materializes, which CUDA does not chunk.
+MATH_KERNEL_FORWARDS = [("bf16", 10116661248), ("fp16", 10116661248), ("fp32", 10081009664)]
+
+
+def _forward_features(dtype: str, control_blocks: int = 0, score_matrix_bytes: int = 0) -> dict:
+ """A 1024px forward with a 512-token caption as the estimator records it; a ControlNet forward passes a mask."""
+ return {"image_tokens": 4096, "text_tokens": 512, "tokens": 4608, "dtype": dtype, "control_blocks": control_blocks,
+ "has_attention_mask": control_blocks > 0, "regional_bias_bytes": 0, "score_matrix_bytes": score_matrix_bytes,
+ "lora_count": 0, "dequant_transient_bytes": 0, "fp8_cast_transient_bytes": 0} # fmt: skip
+
+
+def _shipped_reservation(features: dict, platform: Platform) -> int:
+ shipped = shipped_coefficients(Z_IMAGE_DENOISE_SPEC, platform)
+ return Z_IMAGE_DENOISE_SPEC.evaluate(features, shipped).reservation_bytes
+
+
+class TestMeasuredChecks:
+ """Forwards the shipped points leave out, because a term of their own sits on top of the line."""
+
+ @pytest.mark.parametrize("platform, dtype, control_blocks, measured", CONTROL_FORWARDS)
+ def test_a_control_forward_is_covered_by_the_line_and_its_hints(self, platform, dtype, control_blocks, measured):
+ """Within the 1.3x a shipped point holds its estimate to: every byte reserved beyond need is transformer
+ offloaded to RAM and run over PCIe."""
+ estimate = _shipped_reservation(_forward_features(dtype, control_blocks), platform)
+
+ assert measured <= estimate <= 1.3 * measured
+ @pytest.mark.parametrize("dtype, measured", MATH_KERNEL_FORWARDS)
+ def test_a_math_kernel_forward_is_covered_by_the_line_and_its_score_matrix(self, dtype, measured):
+ """A regime no server runs by default, so it bounds the estimate from below only, as the VAE's forced-math
+ points do."""
+ scores = 30 * 4608 * 4608 * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+
+ assert _shipped_reservation(_forward_features(dtype, score_matrix_bytes=scores), RTX_4090_NATIVE) >= measured
+
+
+class TestRegionalAttentionBias:
def test_bias_is_sized_on_the_padded_unified_sequence(self):
"""4096 image tokens and a 100-token caption: the boolean copy covers the 4196 real tokens, the additive bias
the 4096 + 128 padded ones, and `torch.where` fills the image block from a 4096 x 4096 scratch."""
mask = torch.empty((4196, 4196), dtype=torch.float16, device="meta")
- bias_bytes = ZImageDenoiseInvocation._regional_attention_bias_bytes(mask, 4096, torch.bfloat16)
+ bias_bytes = _estimate(4096, text_seq_len=100, regional_mask=mask) - _estimate(4096, text_seq_len=100)
assert bias_bytes == 4196**2 + 4224**2 * 2 + 4096**2 * 2
+# The reservation the node priced by hand before its estimate declared an `EstimatorSpec`, frozen verbatim with the
+# node's constants: `ZImageDenoiseInvocation._estimate_working_memory` and `_regional_attention_bias_bytes`, plus the
+# dequant transient the node added. The shipped `legacy` values reproduce it where no measured points replace them.
+_LEGACY_SEQ_MULTI_OF = 32
+_LEGACY_HIDDEN_SIZE = 3840
+_LEGACY_ATTENTION_HEADS = 30
+_LEGACY_BYTES_PER_TOKEN = int(0.25 * 1024**2)
+
+
+def _legacy_padded(tokens: int) -> int:
+ return tokens + (-tokens) % _LEGACY_SEQ_MULTI_OF
+
+
+def _legacy_estimate_working_memory(
+ image_seq_len: int,
+ text_seq_len: int,
+ num_loras: int,
+ num_control_blocks: int = 0,
+ regional_attention_bias_bytes: int = 0,
+ has_attention_mask: bool = False,
+ *,
+ device: torch.device,
+ dtype: torch.dtype = torch.bfloat16,
+) -> int:
+ GB = 1024**3
+ seq_len = _legacy_padded(image_seq_len) + _legacy_padded(text_seq_len)
+ estimated = seq_len * _LEGACY_BYTES_PER_TOKEN + int(1.0 * GB)
+ estimated += regional_attention_bias_bytes
+ estimated += sdpa_score_matrix_bytes(
+ device=device,
+ dtype=dtype,
+ num_heads=_LEGACY_ATTENTION_HEADS,
+ head_dim=_LEGACY_HIDDEN_SIZE // _LEGACY_ATTENTION_HEADS,
+ seq_len=seq_len,
+ has_attn_mask=has_attention_mask,
+ via_diffusers_dispatch=True,
+ )
+ if num_control_blocks:
+ estimated += (num_control_blocks + 4) * seq_len * _LEGACY_HIDDEN_SIZE * dtype.itemsize
+ estimated += int(0.5 * num_loras * GB)
+ return estimated
+
+
+def _legacy_regional_attention_bias_bytes(
+ regional_attn_mask: torch.Tensor | None, image_seq_len: int, dtype: torch.dtype
+) -> int:
+ if regional_attn_mask is None:
+ return 0
+ mask_side = regional_attn_mask.shape[0]
+ unified_seq_len = _legacy_padded(image_seq_len) + _legacy_padded(mask_side - image_seq_len)
+ return mask_side * mask_side + (unified_seq_len * unified_seq_len + image_seq_len * image_seq_len) * dtype.itemsize
+
+
+@dataclass(frozen=True)
+class _Attention:
+ """How a build answers the dispatch questions `sdpa_score_matrix_bytes` asks."""
+
+ device: torch.device
+ dispatch: str
+ """The diffusers attention backend's routing."""
+ chunks: bool
+ """Whether the ROCm guard computes math attention in chunks."""
+ materializes: Callable[[bool], bool]
+ """Whether torch's SDPA builds the score matrix, by whether an attention mask is passed."""
+
+ @contextmanager
+ def answers(self):
+ with (
+ patch.object(attention, "_diffusers_attention_dispatch", new=lambda: self.dispatch),
+ patch.object(attention, "rocm_sdpa_uses_math_kernel", new=lambda device_type, head_dim: False),
+ patch.object(attention, "rocm_sdpa_chunks_math", new=lambda device_type: self.chunks),
+ patch.object(attention, "_torch_sdpa_materializes_score_matrix", new=lambda *a: self.materializes(a[-1])),
+ ):
+ yield
+
+
+ATTENTION = {
+ # A fused kernel unless a mask is passed.
+ "cuda": _Attention(torch.device("cuda"), attention._DISPATCH_TORCH, False, lambda has_mask: has_mask),
+ # A fused diffusers backend (flash, sage) never asks torch, which here would materialize.
+ "cuda-fused-backend": _Attention(torch.device("cuda"), attention._DISPATCH_FUSED, False, lambda has_mask: True),
+ # Windows ROCm without fused kernels, under the guard that chunks the math kernel.
+ "hip": _Attention(torch.device("cuda"), attention._DISPATCH_TORCH, True, lambda has_mask: True),
+ "mps": _Attention(torch.device("mps"), attention._DISPATCH_TORCH, False, lambda has_mask: True),
+}
+
+# Where the shipped entry is still `legacy`: ROCm with the native allocator on every OS but Windows.
+LEGACY_PLATFORMS = [Platform("miopen", "native", "linux"), Platform("miopen", "native", "other")]
+# Height, width: odd token grids included, whose runs the transformer pads.
+SIZES = [(512, 512), (528, 528), (784, 1040), (1024, 1024), (1040, 1328), (1536, 1536), (2048, 1104), (2048, 2048)]
+CAPTIONS = [0, 77, 512, 1000]
+CONTROL_BLOCKS = [0, 1, 6, 15]
+# A transient of 123 MiB in bf16 and fp16, 246 MiB in fp32; on the meta device, so it costs no memory.
+TRANSFORMERS = [_dense_transformer(), _int8_transformer(123 * MB // (2 * CONVROT_GROUP_SIZE * 2), device="meta")]
+DTYPES = [torch.bfloat16, torch.float16, torch.float32]
+
+
+class TestLegacyReservation:
+ @pytest.mark.parametrize("attention_build", list(ATTENTION.values()), ids=list(ATTENTION))
+ def test_the_reservation_is_the_legacy_formula_byte_for_byte(self, attention_build: _Attention):
+ """On the platforms still `legacy`: estimated on such a machine, and evaluated again there from the features
+ alone. None of the transformers holds a float8 weight, the one case the reservation adds a term the formula
+ lacked."""
+ mismatches = []
+ with attention_build.answers(), patch.object(spec_module, "platform_for", return_value=LEGACY_PLATFORMS[0]):
+ grid = itertools.product(
+ SIZES, CAPTIONS, CONTROL_BLOCKS, (False, True), (False, True), (0, 2), TRANSFORMERS, DTYPES
+ )
+ for (height, width), caption, blocks, has_mask, regional, loras, transformer, dtype in grid:
+ image_seq_len = (height // 16) * (width // 16)
+ mask_side = image_seq_len + caption
+ regional_mask = torch.empty((mask_side, mask_side), device="meta") if regional else None
+ expected = _legacy_estimate_working_memory(
+ image_seq_len=image_seq_len,
+ text_seq_len=caption,
+ num_loras=loras,
+ num_control_blocks=blocks,
+ regional_attention_bias_bytes=_legacy_regional_attention_bias_bytes(
+ regional_mask, image_seq_len, dtype
+ ),
+ has_attention_mask=has_mask,
+ device=attention_build.device,
+ dtype=dtype,
+ ) + peak_dequant_transient_bytes(transformer, dtype)
+
+ estimate = estimate_z_image_denoise_working_memory(
+ transformer,
+ image_seq_len=image_seq_len,
+ text_seq_len=caption,
+ lora_count=loras,
+ control_blocks=blocks,
+ regional_attn_mask=regional_mask,
+ has_attention_mask=has_mask,
+ device=attention_build.device,
+ dtype=dtype,
+ )
+ reserved = [estimate.reservation_bytes] + [
+ Z_IMAGE_DENOISE_SPEC.evaluate(
+ estimate.features, shipped_coefficients(Z_IMAGE_DENOISE_SPEC, platform)
+ ).reservation_bytes
+ for platform in LEGACY_PLATFORMS
+ ]
+ if any(value != expected for value in reserved):
+ case = (height, width, caption, blocks, has_mask, regional, loras, dtype)
+ mismatches.append((case, expected, reserved))
+ assert not mismatches, f"{len(mismatches)} cases differ, e.g. (case, legacy, reserved): {mismatches[:3]}"
+
+
+EVERY_PLATFORM = [
+ Platform(*keys) for keys in itertools.product(get_args(ConvBackend), get_args(Allocator), get_args(OperatingSystem))
+]
+
+
+def _platform_id(platform: Platform) -> str:
+ return f"{platform.conv_backend}-{platform.allocator}-{platform.os}"
+
+
+class TestUnmeasuredPlatforms:
+ """`priced_as` prices a platform nothing is measured on -- XPU, MPS, the CPU, cuDNN with expandable segments,
+ MIOpen under `hipMallocAsync` -- with a measured platform's lines, which describe the card they were measured on.
+ The entries it borrows floor every value at the legacy constants there (`unmeasured_floor`)."""
+
+ @pytest.mark.parametrize("platform", [p for p in EVERY_PLATFORM if not is_measured(p)], ids=_platform_id)
+ def test_an_unmeasured_platform_reserves_the_legacy_formula_at_least(self, platform: Platform):
+ """The RTX 4090's native-allocator line, which XPU borrows, prices a 1024px bf16 forward at 1172 MiB; the
+ formula reserves 2176. The analytic terms are the formula's own (`TestLegacyReservation`), so plain forwards
+ compare the lines."""
+ short = []
+ with ATTENTION["cuda"].answers(), patch.object(spec_module, "platform_for", return_value=platform):
+ for (height, width), caption, dtype in itertools.product(SIZES, CAPTIONS, DTYPES):
+ image_seq_len = (height // 16) * (width // 16)
+ legacy = _legacy_estimate_working_memory(image_seq_len, caption, 0, device=DEVICE, dtype=dtype)
+ reserved = estimate_z_image_denoise_working_memory(
+ TRANSFORMERS[0],
+ image_seq_len=image_seq_len,
+ text_seq_len=caption,
+ lora_count=0,
+ device=DEVICE,
+ dtype=dtype,
+ ).reservation_bytes
+ if reserved < legacy:
+ short.append(((height, width, caption, dtype), legacy, reserved))
+ assert not short, f"{len(short)} cases below the formula, e.g. (case, legacy, reserved): {short[:3]}"
+
+ @pytest.mark.parametrize("platform", [p for p in EVERY_PLATFORM if is_measured(p)], ids=_platform_id)
+ def test_a_measured_platform_prices_with_its_own_fit_unfloored(self, platform: Platform):
+ """A platform the points were measured on is what they describe, below the formula where they measured less."""
+ unfloored = [
+ file.model_copy(
+ update={"coefficients": [e.model_copy(update={"unmeasured_floor": {}}) for e in file.coefficients]}
+ )
+ for file in shipped_data().values()
+ ]
+
+ assert shipped_coefficients(Z_IMAGE_DENOISE_SPEC, platform) == resolve_coefficients(
+ unfloored, Z_IMAGE_DENOISE_SPEC, platform, origin="shipped"
+ )
+
+
class _StopBeforeLoad(Exception):
"""Raised out of a mocked `model_on_device()` so the node stops at a reservation."""
-# Stands in for the activation estimate, which is tested above; any value the transient cannot produce.
-ACTIVATION_ESTIMATE = 3_000_000_007
+# Stands in for the estimate, which is tested above: a reservation none of its terms can produce.
+ESTIMATE = WorkingMemoryEstimate(
+ estimator=Z_IMAGE_DENOISE_SPEC.id,
+ version=Z_IMAGE_DENOISE_SPEC.version,
+ features={},
+ terms=(WorkingMemoryTerm("stand_in", 3_000_000_007, True),),
+ source="test",
+)
POSITIVE_TOKENS = 8
-def _dense_transformer() -> torch.nn.Module:
- model = torch.nn.Module()
- model.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 8)
- return model
-
-
class TestNodeReservation:
"""The wire from the node to `model_on_device()`: deleting any of these arguments leaves the estimate's own tests
green."""
def _run(
self,
- transformer=None,
*,
control_blocks=None,
control_tiling=None,
@@ -163,7 +458,7 @@ class TestNodeReservation:
ZImageConditioningInfo,
)
- transformer = transformer if transformer is not None else _dense_transformer()
+ transformer = _dense_transformer()
transformer_info = MagicMock()
transformer_info.model = transformer
@@ -237,7 +532,10 @@ class TestNodeReservation:
patch.object(ZImageDenoiseInvocation, "_get_noise", return_value=torch.zeros(1, 16, 32, 32))
)
estimate = stack.enter_context(
- patch.object(ZImageDenoiseInvocation, "_estimate_working_memory", return_value=ACTIVATION_ESTIMATE)
+ patch(
+ "invokeai.app.invocations.z_image.z_image_denoise.estimate_z_image_denoise_working_memory",
+ return_value=ESTIMATE,
+ )
)
control_encode = stack.enter_context(
patch.object(ZImageImageToLatentsInvocation, "vae_encode", side_effect=_StopBeforeLoad)
@@ -256,7 +554,9 @@ class TestNodeReservation:
invocation._run_diffusion(context)
return SimpleNamespace(
- reserved=transformer_info.model_on_device.call_args.kwargs["working_mem_bytes"],
+ transformer=transformer,
+ reserved=transformer_info.model_on_device.call_args.kwargs["working_memory"],
+ estimated_for=estimate.call_args.args,
estimate=estimate.call_args.kwargs,
adapter_reserved=(
control_info.model_on_device.call_args.kwargs.get("working_mem_bytes") if control is not None else None
@@ -264,43 +564,32 @@ class TestNodeReservation:
control_encode=control_encode.call_args.kwargs if control_encode.called else None,
)
- def test_an_unquantized_transformer_reserves_the_estimate_for_its_sequence(self):
+ def test_the_transformer_reserves_the_estimate_for_its_sequence(self):
run = self._run()
- assert run.reserved == ACTIVATION_ESTIMATE
+ assert run.reserved is ESTIMATE
+ # Priced on the model about to be locked, whose quantized layers dequantize per forward.
+ assert run.estimated_for == (run.transformer,)
# 256px is a 16x16 token grid.
assert (run.estimate["image_seq_len"], run.estimate["text_seq_len"]) == (256, POSITIVE_TOKENS)
- assert (run.estimate["num_loras"], run.estimate["num_control_blocks"]) == (0, 0)
- assert (run.estimate["regional_attention_bias_bytes"], run.estimate["has_attention_mask"]) == (0, False)
-
- def test_the_dequant_transient_is_added_to_the_estimate(self):
- """An int8 layer materializes two weight-sized bf16 tensors per forward, alive alongside the activations."""
- model = torch.nn.Module()
- model.proj = Int8ConvrotLinear(
- torch.zeros(1024, CONVROT_GROUP_SIZE, dtype=torch.int8), torch.ones(1024, 1), convrot=False
- )
-
- run = self._run(model)
-
- assert run.reserved == ACTIVATION_ESTIMATE + 2 * 1024 * CONVROT_GROUP_SIZE * torch.bfloat16.itemsize
+ assert (run.estimate["lora_count"], run.estimate["control_blocks"]) == (0, 0)
+ assert (run.estimate["regional_attn_mask"], run.estimate["has_attention_mask"]) == (None, False)
+ assert (run.estimate["device"], run.estimate["dtype"]) == (torch.device("cpu"), torch.bfloat16)
def test_a_longer_negative_caption_sizes_the_sequence(self):
"""With CFG the unconditional pass runs its own forward, so the longer of the two captions is the peak."""
assert self._run(negative_tokens=40).estimate["text_seq_len"] == 40
def test_loras_are_counted(self):
- assert self._run(loras=2).estimate["num_loras"] == 2
+ assert self._run(loras=2).estimate["lora_count"] == 2
def test_a_regional_mask_reaches_the_estimate(self):
mask = torch.zeros((256 + POSITIVE_TOKENS, 256 + POSITIVE_TOKENS), dtype=torch.float16)
run = self._run(regional_mask=mask)
- expected_bias = ZImageDenoiseInvocation._regional_attention_bias_bytes(mask, 256, torch.bfloat16)
- assert (run.estimate["regional_attention_bias_bytes"], run.estimate["has_attention_mask"]) == (
- expected_bias,
- True,
- )
+ assert run.estimate["regional_attn_mask"] is mask
+ assert run.estimate["has_attention_mask"] is True
def test_a_control_adapter_reaches_the_estimate_and_keeps_the_reservation(self):
"""The adapter's block count sizes the hints and its forward always passes a padding mask. It is locked after
@@ -308,8 +597,9 @@ class TestNodeReservation:
weights fill the room kept for the forward."""
run = self._run(control_blocks=15)
- assert (run.estimate["num_control_blocks"], run.estimate["has_attention_mask"]) == (15, True)
- assert run.adapter_reserved == run.reserved == ACTIVATION_ESTIMATE
+ assert (run.estimate["control_blocks"], run.estimate["has_attention_mask"]) == (15, True)
+ assert run.reserved is ESTIMATE
+ assert run.adapter_reserved == ESTIMATE.reservation_bytes
def test_the_control_fields_tiling_reaches_the_control_encode(self):
"""The control image is encoded at generation size. For an upscale that is the enlarged frame, whose untiled
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
index ddb845227a..babcc84c85 100644
--- 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
@@ -35,6 +35,7 @@ from invokeai.backend.working_memory.spec import import_estimator_modules
from tests.fixtures.working_memory_calibration import measured_window
MIB = 2**20
+SPECS = import_estimator_modules()
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"})
@@ -126,7 +127,7 @@ def _features(dtype: str, side: int) -> dict:
def test_the_fragmented_fp32_1216px_windows_drop_out_and_the_others_count() -> None:
- reasons = exclusions(_file())
+ reasons = exclusions(_file(), SPECS)
# 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
@@ -136,7 +137,7 @@ def test_the_fragmented_fp32_1216px_windows_drop_out_and_the_others_count() -> N
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)
+ fit, problems = user_fit_of(_file(), CalibrationEnvironment.of(ENV).id, PLATFORM, SPECS)
assert fit is not None, problems
[fp32] = [line for (_, suffix), line in fit.lines.items() if suffix == "decode_fp32"]
@@ -194,7 +195,7 @@ def test_a_measurement_whose_reserve_grew_around_a_flat_allocation_drops_out_wit
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"}
+ assert exclusions(file, SPECS) == {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
@@ -238,7 +239,7 @@ def test_each_attempt_at_a_size_is_judged_on_its_own(order: str) -> None:
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)) == {
+ assert _reasons_by_attempt(file, exclusions(file, SPECS)) == {
"fragmented": ["partial_residency", "fragmented", "partial_residency"],
"clean": [None, None, None],
}
@@ -258,7 +259,7 @@ def test_two_owners_attempts_with_one_id_are_judged_apart() -> None:
for run, owner in zip(file.runs, ("admin-a", "admin-b"), strict=True)
]
- assert _reasons_by_attempt(file, exclusions(file)) == {
+ assert _reasons_by_attempt(file, exclusions(file, SPECS)) == {
"fragmented": ["partial_residency", "fragmented", "partial_residency"],
"clean": [None, None, None],
}
@@ -270,5 +271,5 @@ def test_a_running_attempts_windows_set_no_standard_for_finished_sizes() -> None
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()
+ assert "fragmented" in exclusions(file, SPECS).values()
+ assert "fragmented" not in exclusions(file, SPECS, {"running": "running"}).values()
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
index efec58ce81..ee5e17017c 100644
--- 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
@@ -53,6 +53,7 @@ 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 invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_DENOISE_SPEC
from tests.fixtures.working_memory_calibration import (
GPU,
HeldEnqueue,
@@ -229,10 +230,10 @@ def _baseline(value: int) -> CounterDelta:
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
+ """A fresh server reads 300 MiB outside torch where the stored decode 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)
@@ -243,13 +244,19 @@ def test_a_fresh_servers_plan_sizes_for_the_outside_use_its_stored_windows_recor
device_memory=lambda device: idle,
)
run_id = _create(service)
+ decode = measured_window(run_id, estimator=VAE_SD_SPEC.id, version=VAE_SD_SPEC.version)
windows = [
- measured_window(run_id).model_copy(update={"driver": _baseline(driver), "reserved": _baseline(reserved)})
+ decode.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))
+ # Nor does a Z-Image forward's, whose estimator no user calibration moves, however much it found outside torch.
+ forward = measured_window(
+ run_id, model_key="transformer-key", estimator=Z_IMAGE_DENOISE_SPEC.id, version=Z_IMAGE_DENOISE_SPEC.version
+ )
+ windows.append(forward.model_copy(update={"driver": _baseline(12 * 2**30), "reserved": _baseline(2**30)}))
service.record_windows(run_id, windows)
reads: list[str] = []
real_read = CalibrationStore.read
@@ -2109,3 +2116,34 @@ def test_a_stopped_service_no_longer_feeds_estimates(tmp_path: Path, started, mo
service.stop(mock_invoker)
assert _estimate() == _shipped()
+
+
+def _forward(run_id: str, image_tokens: int) -> MeasuredWindow:
+ """A plain Z-Image forward's window of model-a's transformer, on a token line its estimator's line admits."""
+ features = {"image_tokens": image_tokens, "text_tokens": 512, "tokens": image_tokens + 512, "dtype": "bf16",
+ "control_blocks": 0, "has_attention_mask": False, "regional_bias_bytes": 0, "score_matrix_bytes": 0,
+ "lora_count": 0, "dequant_transient_bytes": 0, "fp8_cast_transient_bytes": 0} # fmt: skip
+ window = measured_window(
+ run_id, model_key="model-a:transformer", estimator="denoise.z_image", version=Z_IMAGE_DENOISE_SPEC.version
+ )
+ return window.model_copy(update={"features": features, "demand_bytes": 5000 * image_tokens})
+
+
+def test_denoise_windows_are_kept_but_feed_no_user_line_and_count_as_fitting_none(tmp_path: Path, started) -> None:
+ """The Z-Image denoise is not user-calibrated: its windows stay in the store, the summary shows no line for them
+ and counts them among the model's windows that fit none, and its estimates stay shipped while the decode's move."""
+ service = started(tmp_path)
+ run_id = _create(service)
+ forwards = [_forward(run_id, image) for image in (1024, 4096, 16384)]
+ service.record_windows(run_id, _on_the_line(run_id) + forwards)
+
+ summary = service.get_model_summary("model-a")
+
+ assert [(line.estimator, line.line) for line in summary.lines] == [("vae.sd", "decode_fp16")]
+ assert summary.excluded_windows == len(forwards)
+ assert [run.point_count for run in summary.runs] == [6]
+ service.refresh_user_fits()
+ assert _estimate() == _user_bytes(1024)
+ features = forwards[1].features
+ shipped = shipped_coefficients(Z_IMAGE_DENOISE_SPEC, PLATFORM)
+ assert Z_IMAGE_DENOISE_SPEC.estimate(features, GPU) == Z_IMAGE_DENOISE_SPEC.evaluate(features, shipped)
diff --git a/tests/app/test_run_app_environment.py b/tests/app/test_run_app_environment.py
index 6b08ab21d7..583baa5d1c 100644
--- a/tests/app/test_run_app_environment.py
+++ b/tests/app/test_run_app_environment.py
@@ -1,10 +1,14 @@
-"""The console-script entry module pins process-wide environment defaults before any heavy import."""
+"""The console-script entry module: the process-wide environment defaults it pins before any heavy import, and the
+server's runtime, the startup steps that decide kernels and allocation, which the calibration scripts apply too."""
import importlib
+import logging
import os
import pytest
+from invokeai.app.services.config.config_default import InvokeAIAppConfig
+
@pytest.fixture
def reload_run_app(monkeypatch: pytest.MonkeyPatch):
@@ -30,3 +34,104 @@ def test_run_app_keeps_an_explicit_environment_value(name: str, monkeypatch: pyt
monkeypatch.setenv(name, "user-choice")
reload_run_app()
assert os.environ[name] == "user-choice"
+
+
+def runtime_steps(monkeypatch: pytest.MonkeyPatch) -> list[tuple]:
+ """The runtime's steps, recorded instead of run, each with the settings it was given; the first also with the
+ ``MIOPEN_FIND_MODE`` it ran under. Each does its work on its own platform only, and an explicit allocator
+ configuration refuses to apply once torch is imported."""
+ from invokeai.app.util import rocm_aotriton, rocm_integrated_gpu, startup_utils, torch_cuda_allocator
+
+ steps: list[tuple] = []
+
+ def hide_integrated_gpus(logger: logging.Logger) -> None:
+ steps.append(("hide integrated GPUs", os.environ.get("MIOPEN_FIND_MODE")))
+
+ def configure_allocator(conf: str, logger: logging.Logger) -> None:
+ steps.append(("configure the allocator", conf))
+
+ def allocator_default(logger: logging.Logger) -> None:
+ steps.append(("the platform's allocator default",))
+
+ def aotriton(setting: str, generation_devices: object, logger: logging.Logger) -> None:
+ steps.append(("AOTriton", setting, generation_devices))
+
+ def monkeypatches(attention_backend: str) -> None:
+ steps.append(("monkeypatches", attention_backend))
+
+ monkeypatch.setattr(rocm_integrated_gpu, "hide_integrated_gpus_on_rocm_windows", hide_integrated_gpus)
+ monkeypatch.setattr(torch_cuda_allocator, "configure_torch_cuda_allocator", configure_allocator)
+ monkeypatch.setattr(torch_cuda_allocator, "apply_rocm_windows_allocator_default", allocator_default)
+ monkeypatch.setattr(rocm_aotriton, "apply_rocm_aotriton_setting", aotriton)
+ monkeypatch.setattr(startup_utils, "apply_monkeypatches", monkeypatches)
+ return steps
+
+
+def _config(**settings) -> InvokeAIAppConfig:
+ """A config whose runtime settings each differ from their defaults."""
+ return InvokeAIAppConfig(
+ rocm_aotriton_experimental="off", generation_devices=["cuda:1"], attention_backend="sage", **settings
+ )
+
+
+ "alloc_conf, allocator_step",
+ [
+ (None, ("the platform's allocator default",)),
+ ("backend:cudaMallocAsync", ("configure the allocator", "backend:cudaMallocAsync")),
+ ],
+ ids=["platform-default", "configured"],
+)
+def test_the_server_runtime_applies_its_steps_in_the_servers_order(
+ runtime_steps: list[tuple], monkeypatch: pytest.MonkeyPatch, alloc_conf, allocator_step
+):
+ import invokeai.app.run_app as run_app
+
+ monkeypatch.delenv("MIOPEN_FIND_MODE", raising=False)
+
+ run_app.apply_server_runtime(_config(pytorch_cuda_alloc_conf=alloc_conf), logging.getLogger(__name__))
+
+ assert runtime_steps == [
+ ("hide integrated GPUs", "FAST"),
+ allocator_step,
+ ("AOTriton", "off", ["cuda:1"]),
+ ("monkeypatches", "sage"),
+ ]
+
+
+class _Started(Exception):
+ """Ends a server start once it is as far as a test needs."""
+
+
+def test_the_server_starts_with_the_runtime_it_gives_the_calibration_scripts(
+ runtime_steps: list[tuple], monkeypatch: pytest.MonkeyPatch
+):
+ import invokeai.app.run_app as run_app
+ from invokeai.app.services.config import config_default
+ from invokeai.app.util import startup_utils
+ from invokeai.backend.util.devices import TorchDevice
+ from invokeai.frontend.cli.arg_parser import InvokeAIArgs
+
+ config = _config(pytorch_cuda_alloc_conf="backend:cudaMallocAsync")
+
+ def started() -> None:
+ raise _Started
+
+ monkeypatch.setattr(InvokeAIArgs, "parse_args", staticmethod(lambda: None)) # pytest's arguments are not the app's
+ monkeypatch.setattr(config_default, "get_config", lambda: config)
+ # The server's own steps between the runtime's two parts, without asking a GPU or the network.
+ monkeypatch.setattr(TorchDevice, "get_generation_devices_summary", classmethod(lambda cls, devices: "a GPU"))
+ monkeypatch.setattr(startup_utils, "find_open_port", lambda port: port)
+ # The startup step after the runtime: the server is as far as this test needs. Should that step move, the app still
+ # does not come up.
+ monkeypatch.setattr(startup_utils, "register_mime_types", started)
+ monkeypatch.setattr(run_app, "get_app", started)
+
+ with pytest.raises(_Started):
+ run_app.run_app()
+ server = list(runtime_steps)
+ runtime_steps.clear()
+ run_app.apply_server_runtime(config, logging.getLogger(__name__))
+
+ assert server == runtime_steps
diff --git a/tests/backend/util/test_fp8.py b/tests/backend/util/test_fp8.py
index 62ea51c45e..25c3db86cf 100644
--- a/tests/backend/util/test_fp8.py
+++ b/tests/backend/util/test_fp8.py
@@ -1,4 +1,4 @@
-"""Tests for `get_model_compute_dtype`.
+"""Tests for the FP8 storage helpers: `get_model_compute_dtype`, and `peak_fp8_cast_transient_bytes` at the end.
Regression coverage for the SDXL + fp8_storage crash:
@@ -23,6 +23,7 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat,
from invokeai.backend.util.fp8 import (
FP8_COMPUTE_DTYPE_ATTR,
get_model_compute_dtype,
+ peak_fp8_cast_transient_bytes,
set_fp8_compute_dtype,
)
@@ -161,3 +162,72 @@ def test_double_cast_is_a_noop():
# the hooks would have been registered twice.
assert model.norm1.weight.dtype == torch.bfloat16
assert len(model.linear._forward_pre_hooks) == 1
+
+
+class _TwoLayers(torch.nn.Module):
+ """Two castable layers of different sizes, run one after the other, and a norm FP8 Storage leaves alone."""
+
+ def __init__(self):
+ super().__init__()
+ self.large = torch.nn.Linear(64, 64)
+ self.small = torch.nn.Linear(64, 8)
+ self.norm = torch.nn.LayerNorm(8)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.norm(self.small(self.large(x)))
+
+
[email protected](not _fp8_supported(), reason="torch.float8_e4m3fn not available")
+def test_the_fp8_cast_transient_is_the_largest_layer_fp8_storage_widens_in_a_forward():
+ """Measured on the loader's real cast: each layer's params are widened while its own forward runs, and put back
+ before the next layer widens, so what is widened at once peaks at the largest layer's, weight and bias. In fp32,
+ which CPU tests run in."""
+ model = _TwoLayers()
+ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.float32)
+ widened_at_once = []
+
+ def record(module: torch.nn.Module, args: object) -> None:
+ widened_at_once.append(
+ sum(
+ p.nbytes for layer in (model.large, model.small) for p in layer.parameters() if p.dtype == torch.float32
+ )
+ )
+
+ # Registered after the cast's hooks, so they see each layer's params as its forward runs on them.
+ for layer in (model.large, model.small):
+ layer.register_forward_pre_hook(record)
+ model(torch.randn(1, 64))
+
+ assert widened_at_once == [(64 * 64 + 64) * 4, (64 * 8 + 8) * 4]
+ assert peak_fp8_cast_transient_bytes(model, torch.float32) == max(widened_at_once)
+
+
[email protected](not _fp8_supported(), reason="torch.float8_e4m3fn not available")
[email protected]("scaled, copies", [(False, 1), (True, 2)], ids=["raw", "scaled"])
+def test_a_kept_fp8_checkpoint_weight_is_widened_per_forward_and_a_scaled_one_twice(scaled: bool, copies: int):
+ """`CustomLinear` dequantizes a kept fp8 weight per forward; `dequantize_weight` holds the widened weight and its
+ product with the `weight_scale` at once. Only the weight is kept in fp8, so the bias costs nothing."""
+ layer = torch.nn.Linear(64, 32, device="meta")
+ layer.weight = torch.nn.Parameter(
+ torch.empty(32, 64, dtype=torch.float8_e4m3fn, device="meta"), requires_grad=False
+ )
+ if scaled:
+ layer.register_buffer("weight_scale", torch.ones((), device="meta"), persistent=False)
+
+ assert peak_fp8_cast_transient_bytes(torch.nn.Sequential(layer), torch.bfloat16) == copies * 32 * 64 * 2
+
+
+class _PackedTensor(torch.Tensor):
+ """A quantized payload kept in a tensor subclass, as SDNQ and GGUF keep theirs."""
+
+
[email protected](not _fp8_supported(), reason="torch.float8_e4m3fn not available")
+def test_a_model_without_plain_fp8_weights_has_no_fp8_cast_transient():
+ """Dense weights are what the forward runs on, and a packed payload is its own scheme's to dequantize."""
+ dense = torch.nn.Linear(64, 64, device="meta", dtype=torch.bfloat16)
+ packed = torch.nn.Linear(64, 64, device="meta")
+ packed.weight = torch.nn.Parameter(
+ torch.empty(64, 64, dtype=torch.float8_e4m3fn, device="meta").as_subclass(_PackedTensor), requires_grad=False
+ )
+
+ assert peak_fp8_cast_transient_bytes(torch.nn.Sequential(dense, packed), torch.bfloat16) == 0
diff --git a/tests/backend/working_memory/test_fit.py b/tests/backend/working_memory/test_fit.py
index 65160bf37f..48c33e3991 100644
--- a/tests/backend/working_memory/test_fit.py
+++ b/tests/backend/working_memory/test_fit.py
@@ -4,17 +4,43 @@ from fractions import Fraction
import pytest
+from invokeai.backend.working_memory.bounds import bound_violation, evaluate_point
from invokeai.backend.working_memory.coefficients import CoefficientEntry, MeasuredPoint, ValuesFrom, WorkingMemoryData
+from invokeai.backend.working_memory.estimate import WorkingMemoryTerm
from invokeai.backend.working_memory.fit import (
SHIPPED_MARGIN,
+ Line,
+ convolution_line,
+ fit_points,
fitted_values,
hand_set_values,
shipped_pair,
upper_envelope,
)
from invokeai.backend.working_memory.spec import EstimatorSpec
+from invokeai.backend.z_image import denoise_working_memory
+from invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_DENOISE_SPEC
MIB = 2**20
+GIB = 2**30
+
+
+def _no_terms(features, values):
+ return ()
+
+
+# Throwaway estimators on the convolution line every VAE estimator declares.
+SPECS = {
+ estimator: EstimatorSpec(
+ id=estimator,
+ version=1,
+ coefficients=frozenset(),
+ platform_keys=("conv_backend",),
+ terms=_no_terms,
+ line=convolution_line,
+ )
+ for estimator in ("lender", "borrower")
+}
# A process base plus a per-pixel cost, read with the scatter real points have: the shape the VAE points take.
SCATTERED = [(262144, 940 * MIB), (589824, 1540 * MIB), (1048576, 2380 * MIB), (1638400, 3120 * MIB)]
@@ -126,7 +152,7 @@ def test_a_line_is_fitted_on_the_single_sample_untiled_points_of_every_member_th
MeasuredPoint.model_validate(_point("lender", "decode", 2048, 90000).model_dump() | {"in_fit": False}),
],
)
- fitted = fitted_values([data])[("lender", 1, (("conv_backend", "cudnn"),))]
+ fitted = fitted_values([data], SPECS)[("lender", 1, (("conv_backend", "cudnn"),))]
assert (fitted["k_decode_bf16"], fitted["b_decode_bf16"]) == shipped_pair(
[(512 * 512, 1100 * MIB), (1024 * 1024, 4400 * MIB)]
)
@@ -139,7 +165,7 @@ def test_a_line_without_enough_points_names_its_entry() -> None:
points=[_point("lender", "decode", 512, 1100)],
)
with pytest.raises(ValueError, match=r"lender on \{'conv_backend': 'cudnn'\}, decode_bf16"):
- fitted_values([data])
+ fitted_values([data], SPECS)
def _probe(px: int, mib: int) -> MeasuredPoint:
@@ -160,7 +186,7 @@ def test_a_line_its_fresh_process_points_do_not_span_is_not_fitted(points) -> No
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])
+ fitted_values([data], SPECS)
def test_a_probe_point_never_lowers_a_half_of_the_fresh_process_fit() -> None:
@@ -173,7 +199,7 @@ def test_a_probe_point_never_lowers_a_half_of_the_fresh_process_fit() -> None:
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"),))]
+ line = fitted_values([data], SPECS)[("lender", 1, (("conv_backend", "cudnn"),))]
fresh_k, fresh_b = shipped_pair([(512 * 512, 1024 * MIB), (1024 * 1024, 1229 * MIB)])
assert fresh_b == 1004 * MIB
@@ -187,22 +213,30 @@ def test_a_declared_stand_in_line_is_not_fitted() -> None:
update={"stand_ins": ["k_decode_bf16", "b_decode_bf16"]}
)
data = WorkingMemoryData(schema_version=1, coefficients=[entry], points=[])
- assert fitted_values([data]) == {}
+ assert fitted_values([data], SPECS) == {}
@pytest.mark.parametrize(
- "platform_keys, exempt", [(("conv_backend",), set()), ((), {"k_token"})], ids=["keyed", "unkeyed"]
+ "platform_keys, token_base, exempt",
+ [(("conv_backend",), False, set()), ((), False, {"k_token"}), ((), True, set())],
+ ids=["keyed", "unkeyed", "unkeyed-carried-line"],
)
-def test_only_an_estimator_keyed_by_no_platform_trait_carries_a_value_off_a_pixel_line(platform_keys, exempt) -> None:
+def test_only_an_estimator_keyed_by_no_platform_trait_carries_a_value_off_a_line(
+ platform_keys, token_base, exempt
+) -> None:
"""A keyed estimator's value off a line counts as unfitted; an unkeyed one's is hand-set. Lines are fitted either
- way."""
- entry = _entry("estimator", {"k_decode_bf16": 1.0, "b_decode_bf16": 0.0, "k_token": 220000.0})
+ way, and a slope whose base ships with it is a carried line, hand-set nowhere."""
+ values = {"k_decode_bf16": 1.0, "b_decode_bf16": 0.0, "k_token": 220000.0} | (
+ {"b_token": 0.0} if token_base else {}
+ )
+ entry = _entry("estimator", values)
spec = EstimatorSpec(
id="estimator",
version=1,
coefficients=frozenset(entry.values or {}),
platform_keys=platform_keys,
terms=lambda features, values: (),
+ line=convolution_line,
)
assert hand_set_values(entry, spec) == exempt
@@ -228,7 +262,7 @@ def test_a_probe_point_raises_a_line_but_does_not_choose_it() -> None:
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"),))]
+ line = fitted_values([data], SPECS)[("lender", 1, (("conv_backend", "cudnn"),))]
return line["k_decode_bf16"], line["b_decode_bf16"]
def probe(px: int, mib: int) -> MeasuredPoint:
@@ -243,3 +277,126 @@ def test_a_probe_point_raises_a_line_but_does_not_choose_it() -> None:
# 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
+
+
+DENOISE_PLATFORM = {"conv_backend": "cudnn", "allocator": "native"}
+SLOPE, BASE = 225280, 100 * MIB
+"""The line the Z-Image denoise forwards below are measured on: 220 KiB per attended token plus 100 MiB."""
+
+
+def _forward(image_tokens: int, text_tokens: int = 512, **off_line: object) -> dict:
+ """A Z-Image denoise forward's features as its estimator records them: the plain forward, unless `off_line` sets
+ one of its analytic features."""
+ plain = {"image_tokens": image_tokens, "text_tokens": text_tokens, "tokens": image_tokens + text_tokens,
+ "dtype": "bf16", "control_blocks": 0, "has_attention_mask": False, "regional_bias_bytes": 0,
+ "score_matrix_bytes": 0, "lora_count": 0, "dequant_transient_bytes": 0, "fp8_cast_transient_bytes": 0} # fmt: skip
+ return plain | off_line
+
+
+def _measured_forward(features: dict, above_the_line: int = 0) -> MeasuredPoint:
+ return MeasuredPoint(
+ estimator=Z_IMAGE_DENOISE_SPEC.id,
+ version=Z_IMAGE_DENOISE_SPEC.version,
+ platform=DENOISE_PLATFORM,
+ features=features,
+ measured_bytes=SLOPE * features["tokens"] + BASE + above_the_line,
+ method="demand_peak",
+ device="NVIDIA GeForce RTX 4090",
+ provenance="-",
+ )
+
+
+DENOISE_ENTRY = CoefficientEntry(
+ estimator=Z_IMAGE_DENOISE_SPEC.id,
+ version=Z_IMAGE_DENOISE_SPEC.version,
+ platform=DENOISE_PLATFORM,
+ values=dict.fromkeys(Z_IMAGE_DENOISE_SPEC.coefficients, 0.0),
+ stand_ins=[f"{part}_denoise_{dtype}" for part in ("k", "b") for dtype in ("fp16", "fp32")],
+ provenance="-",
+)
+"""An entry whose bf16 line the forwards below fit."""
+
+
+def test_a_token_line_is_fitted_on_the_plain_forwards_and_bounds_every_forward() -> None:
+ """Plain forwards of 1024 to 16384 image tokens and two caption lengths lie on one line in their image and caption
+ tokens together. A ControlNet forward, one whose score matrix is materialized and one of a quantized model measure
+ more, by what their own terms price; at 4096 image tokens, fitted on, each would raise the line. The fit is the
+ plain forwards' line plus 5%, and under it every forward holds its bounds, the others with their terms on top."""
+ hints = (6 + 4) * 4608 * 3840 * 2
+ forwards = [
+ *(_measured_forward(_forward(image)) for image in (1024, 4096, 16384)),
+ _measured_forward(_forward(4096, text_tokens=96)),
+ _measured_forward(_forward(4096, control_blocks=6, has_attention_mask=True), above_the_line=hints * 9 // 10),
+ _measured_forward(_forward(4096, score_matrix_bytes=GIB), above_the_line=768 * MIB),
+ _measured_forward(_forward(4096, dequant_transient_bytes=200 * MIB), above_the_line=200 * MIB),
+ ]
+ data = WorkingMemoryData(schema_version=1, coefficients=[DENOISE_ENTRY], points=forwards)
+
+ [fitted] = fitted_values([data], {Z_IMAGE_DENOISE_SPEC.id: Z_IMAGE_DENOISE_SPEC}).values()
+
+ assert fitted == {"k_denoise_bf16": 236544, "b_denoise_bf16": 105 * MIB}
+ entry = DENOISE_ENTRY.model_copy(update={"values": (DENOISE_ENTRY.values or {}) | fitted})
+ shipped = data.model_copy(update={"coefficients": [entry]})
+ for forward in forwards:
+ estimate = evaluate_point(forward, Z_IMAGE_DENOISE_SPEC, [shipped])
+ assert bound_violation(forward, Z_IMAGE_DENOISE_SPEC, estimate) is None, forward.features
+
+
+def test_any_analytic_term_takes_the_forwards_it_prices_out_of_the_token_line_fit(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The line takes a forward only where every analytic term of the estimator comes to nothing, read off the terms
+ themselves: a term added to the estimator takes the forwards it prices out of the fit, and their ids say so. A
+ forward that passes an attention mask leaves it too, though no term prices the mask: it narrows the kernels SDPA
+ can pick."""
+ terms = denoise_working_memory._terms
+
+ def with_a_new_term(features, values):
+ return (*terms(features, values), WorkingMemoryTerm("new_transient", features.get("new_bytes", 0), True))
+
+ monkeypatch.setattr(denoise_working_memory, "_terms", with_a_new_term)
+ priced = _measured_forward(_forward(4096, new_bytes=GIB), above_the_line=GIB)
+ masked = _measured_forward(_forward(4096, has_attention_mask=True), above_the_line=GIB)
+ plain = [_measured_forward(_forward(image)) for image in (1024, 16384)]
+ data = WorkingMemoryData(schema_version=1, coefficients=[DENOISE_ENTRY], points=[*plain, priced, masked])
+
+ [line] = fit_points([data], {Z_IMAGE_DENOISE_SPEC.id: Z_IMAGE_DENOISE_SPEC}).values()
+
+ assert [point.size for point in line] == [1024 + 512, 16384 + 512]
+ assert Z_IMAGE_DENOISE_SPEC.line(priced.features) == Line(
+ "denoise_bf16", 4608, False, "denoise-bf16-4096+512tok-new_transient=1073741824"
+ )
+ assert Z_IMAGE_DENOISE_SPEC.line(masked.features) == Line(
+ "denoise_bf16", 4608, False, "denoise-bf16-4096+512tok-attention_mask"
+ )
+
+
+def _probe_forward(features: dict, above_the_line: int = 0) -> MeasuredPoint:
+ return _measured_forward(features, above_the_line).model_copy(update={"method": "probe_demand"})
+
+
+def test_a_token_line_its_fresh_forwards_do_not_span_is_not_fitted() -> None:
+ """One fresh forward at 4096 image tokens and warm windows at 1024 and 16384: together they span 11x, but the one
+ fresh size pins nothing at the others, where a cold first run can lie above the windows."""
+ forwards = [_probe_forward(_forward(1024)), _measured_forward(_forward(4096)), _probe_forward(_forward(16384))]
+ data = WorkingMemoryData(schema_version=1, coefficients=[DENOISE_ENTRY], points=forwards)
+
+ with pytest.raises(ValueError, match=r"denoise_bf16: its fresh-process points measure .* keep it a stand-in"):
+ fitted_values([data], {Z_IMAGE_DENOISE_SPEC.id: Z_IMAGE_DENOISE_SPEC})
+
+
+def test_a_probe_forward_never_lowers_a_half_of_the_fresh_token_fit() -> None:
+ """A warm window at 16384 image tokens 2 GiB above the fresh forwards' line drops their 4096-token vertex from the
+ hull: rated on the fresh forwards, the edge through the origin then wins, steeper and with no base. The shipped
+ line keeps the fresh fit's 105 MiB base and the steeper slope, so it still covers the window."""
+ fresh = [_measured_forward(_forward(image)) for image in (1024, 4096)]
+ window = _probe_forward(_forward(16384), above_the_line=2 * GIB)
+ data = WorkingMemoryData(schema_version=1, coefficients=[DENOISE_ENTRY], points=[*fresh, window])
+
+ [fitted] = fitted_values([data], {Z_IMAGE_DENOISE_SPEC.id: Z_IMAGE_DENOISE_SPEC}).values()
+
+ fresh_k, fresh_b = shipped_pair([(p.features["tokens"], p.measured_bytes) for p in fresh])
+ assert (fresh_k, fresh_b) == (236544, 105 * MIB)
+ assert fitted["b_denoise_bf16"] == fresh_b
+ assert fitted["k_denoise_bf16"] > fresh_k
+ assert fitted["k_denoise_bf16"] * window.features["tokens"] + fitted["b_denoise_bf16"] >= window.measured_bytes
diff --git a/tests/backend/working_memory/test_measurement.py b/tests/backend/working_memory/test_measurement.py
new file mode 100644
index 0000000000..c733097354
--- /dev/null
+++ b/tests/backend/working_memory/test_measurement.py
@@ -0,0 +1,99 @@
+"""Fresh windows (`measurement.measure`): one operation measured alone, as the calibration scripts measure their points.
+
+They run on the probe tests' scripted device, whose release returns the allocator's cached blocks when
+`TorchDevice.empty_cache` runs. What a window's readings mean -- the demand, the method, the reasons -- is shared with
+the probe's windows and tested there; these cover what a fresh window does around the operation.
+"""
+
+from typing import Iterator
+
+import pytest
+import torch
+
+from invokeai.backend.util import devices
+from invokeai.backend.working_memory import counters, measurement
+from invokeai.backend.working_memory.measurement import measure
+from tests.backend.working_memory.test_probe import FakeCounters, FakeDevice
+
+GIB = 2**30
+MIB = 2**20
+
+
+def device(monkeypatch: pytest.MonkeyPatch) -> Iterator[FakeDevice]:
+ fake = FakeDevice()
+ opened: list[FakeCounters] = []
+
+ def device_counters(torch_device: torch.device) -> FakeCounters:
+ opened.append(FakeCounters(fake))
+ return opened[-1]
+
+ monkeypatch.setattr(devices, "EMPTY_CACHE_OBSERVERS", [fake])
+ monkeypatch.setattr(counters, "DeviceCounters", device_counters)
+ monkeypatch.setattr(measurement, "SPILL_SETTLE_S", 0.0)
+ yield fake
+ assert opened and all(c.closed for c in opened), "every window closes its counters"
+
+
+def test_a_fresh_window_takes_what_the_operation_took_over_a_released_baseline(device: FakeDevice):
+ device.alloc(1 * GIB) # the weights and inputs, in place
+ device.alloc(3 * GIB)
+ device.free(3 * GIB) # an earlier forward's blocks, still cached, and its peak
+
+ def forward() -> None:
+ device.alloc(2 * GIB)
+ device.free(2 * GIB)
+
+ window = measure(torch.device("cpu"), forward)
+
+ # Served from the cached blocks, the forward would grow neither the driver nor reserved; under the earlier peak,
+ # neither peak would show it.
+ assert (window.driver, window.reserved, window.allocated, window.demand) == (2 * GIB, 2 * GIB, 2 * GIB, 2 * GIB)
+ assert (window.reasons, window.counter_method) == ((), "windows-d3dkmt")
+
+
+def test_an_operation_out_of_memory_gives_an_invalid_window_and_other_errors_propagate(device: FakeDevice):
+ def out_of_memory() -> None:
+ device.num_ooms += 1 # the allocator counts the allocation it failed
+ raise torch.OutOfMemoryError("CUDA out of memory. Tried to allocate 20.00 GiB")
+
+ def wrong_shapes() -> None:
+ raise RuntimeError("mat1 and mat2 shapes cannot be multiplied")
+
+ window = measure(torch.device("cpu"), out_of_memory)
+ with pytest.raises(RuntimeError, match="shapes"):
+ measure(torch.device("cpu"), wrong_shapes)
+
+ assert window.reasons == ("oom",)
+
+
[email protected]("step", ["synchronize", "reset_peaks"])
+def test_a_synchronization_or_peak_reset_that_fails_gives_no_window(
+ device: FakeDevice, monkeypatch: pytest.MonkeyPatch, step: str
+):
+ """No reading after it could be trusted. The error propagates, and the calibration script records the point as
+ failed; the counters still close."""
+
+ def fail(self: FakeCounters) -> None:
+ raise RuntimeError("CUDA error: an illegal memory access was encountered")
+
+ monkeypatch.setattr(FakeCounters, step, fail)
+
+ with pytest.raises(RuntimeError, match="illegal memory access"):
+ measure(torch.device("cpu"), lambda: None)
+
+
+ ("paged", "reasons"),
+ [([0, 600 * MIB, 9 * MIB], ()), ([0, 600 * MIB, 600 * MIB], ("spill",))],
+ ids=["transient", "persistent"],
+)
+def test_only_spill_that_persists_after_the_operation_voids_a_fresh_window(
+ device: FakeDevice, paged: list[int], reasons: tuple[str, ...]
+):
+ """The readings at the baseline, at the close and after the settle time."""
+ device.paged = list(paged)
+
+ window = measure(torch.device("cpu"), lambda: None)
+
+ assert (window.paged, window.reasons) == (600 * MIB, reasons)
diff --git a/tests/backend/working_memory/test_probe.py b/tests/backend/working_memory/test_probe.py
index 28f7e4ad8c..e6c29440c2 100644
--- a/tests/backend/working_memory/test_probe.py
+++ b/tests/backend/working_memory/test_probe.py
@@ -27,7 +27,7 @@ from invokeai.backend.model_manager.load.model_cache.cache_record import CacheRe
from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
from invokeai.backend.util import devices
from invokeai.backend.util.devices import TorchDevice
-from invokeai.backend.working_memory import counters, probe
+from invokeai.backend.working_memory import counters, measurement, probe
from invokeai.backend.working_memory.counters import CounterReading, Method
from invokeai.backend.working_memory.estimate import WorkingMemoryEstimate, WorkingMemoryTerm
from invokeai.backend.working_memory.probe import MeasuredWindow, ProbeScope, calibration_scope
@@ -48,6 +48,8 @@ class FakeDevice:
self.allocated = 0
self.cached = 0
self.retained = 0
+ self.outside = 0
+ """What the driver counts beyond the allocator's blocks: library workspaces, kernel modules."""
self.peak_reserved = 0
self.peak_allocated = 0
self.num_ooms = 0
@@ -107,7 +109,7 @@ class FakeDevice:
peak_allocated=self.peak_allocated,
num_ooms=self.num_ooms,
num_alloc_retries=self.num_alloc_retries,
- driver=self.reserved + self.retained if self.has_driver else None,
+ driver=self.reserved + self.retained + self.outside if self.has_driver else None,
peak_driver=None,
paged=paged,
device_used=None if self.device_used_by_others is None else self.reserved + self.device_used_by_others,
@@ -306,7 +308,7 @@ def device(monkeypatch: pytest.MonkeyPatch) -> Iterator[FakeDevice]:
# The fake allocator observes releases ahead of the probe, which registers when a scope opens.
monkeypatch.setattr(devices, "EMPTY_CACHE_OBSERVERS", [fake])
monkeypatch.setattr(counters, "DeviceCounters", device_counters)
- monkeypatch.setattr(probe, "SPILL_SETTLE_S", 0.0)
+ monkeypatch.setattr(measurement, "SPILL_SETTLE_S", 0.0)
yield fake
assert all(c.closed for c in opened), "every window's counters are closed, so no sampler outlives it"
assert probe.armed is False
@@ -939,6 +941,23 @@ def test_a_driver_that_keeps_a_retained_pool_reads_below_reserved_and_reserved_d
assert window.demand_bytes == 6 * GIB
+def test_memory_outside_torchs_allocator_decides_the_demand_through_the_drivers_figure(device: FakeDevice):
+ """On HIP the first operation of a process maps ~300 MiB beyond the reserved peak, and library workspaces and
+ kernel modules are the driver's alone everywhere: torch's counters never see them."""
+ cache = FakeCache(device)
+
+ with _scope() as scope:
+ with _model(cache, "vae").model_on_device(working_memory=_estimate()):
+ device.alloc(1 * GIB)
+ device.free(1 * GIB)
+ device.outside += 300 * MIB
+
+ (window,) = scope.windows
+ assert window.reserved is not None and window.reserved.delta == 1 * GIB
+ assert window.driver is not None and window.driver.delta == 1 * GIB + 300 * MIB
+ assert window.demand_bytes == 1 * GIB + 300 * MIB
+
+
def test_without_a_driver_reading_the_window_rests_on_torch_and_is_unverified(device: FakeDevice):
device.has_driver = False
cache = FakeCache(device)
diff --git a/tests/backend/working_memory/test_shipped_coefficients.py b/tests/backend/working_memory/test_shipped_coefficients.py
index 14bc4806dd..d6fdb5eefe 100644
--- a/tests/backend/working_memory/test_shipped_coefficients.py
+++ b/tests/backend/working_memory/test_shipped_coefficients.py
@@ -1,12 +1,12 @@
"""The shipped working-memory data, checked against the estimators that read it.
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. 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`.
+no platform trait. Every value an entry carries is a declared stand-in, a hand-set constant of a `legacy` entry listed
+in `LEGACY_ENTRIES`, or decided by at least one in-fit point and, on a line its entry carries, the shipped fit
+(`fit.py`) of the points it is resolved for; only an estimator keyed by no 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
@@ -48,7 +48,9 @@ from invokeai.backend.working_memory.estimate import WorkingMemoryEstimate
from invokeai.backend.working_memory.fingerprint import environment_for
from invokeai.backend.working_memory.fit import (
capping_spans,
+ carried_lines,
carrier_of,
+ convolution_line,
entry_key,
fit_points,
fitted_values,
@@ -68,6 +70,11 @@ OUT_OF_FIT = {((("allocator", "native"), ("conv_backend", "cudnn")), "RTX 4090",
"""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."""
+LEGACY_ENTRIES = {("denoise.z_image", (("allocator", "native"), ("conv_backend", "miopen")))}
+"""The entries, by estimator and platform keys, that carry hand-set constants (`CoefficientEntry.legacy`) rather than
+fits of measured points: the Z-Image denoise on ROCm with the native allocator off Windows, which nothing measures yet.
+Shipping an entry's points and fit removes it from here."""
+
# Imported deliberately rather than relying on whichever modules ran first: a spec missing from the registry is a spec
# whose data nobody checks.
SPECS = import_estimator_modules()
@@ -90,8 +97,12 @@ def _evaluate(point: MeasuredPoint) -> WorkingMemoryEstimate:
return evaluate_point(point, spec, shipped_data().values())
+def _id(point: MeasuredPoint) -> str:
+ return point_id(point, SPECS[point.estimator])
+
+
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=_id(point)) for point in ALL_POINTS]
ENTRIES = [entry for data in shipped_data().values() for entry in data.coefficients]
@@ -161,7 +172,7 @@ def test_an_unmeasured_platform_is_priced_as_the_measured_one_at_least_and_says_
def test_every_fitted_value_is_decided_by_an_in_fit_point() -> None:
"""A value no point decides is unguarded: any number would pass. An estimator without points of its own takes a
measured one's values with `values_from`, and is then held to that one's points. Only declared stand-ins are
- exempt, and they are listed in the entry."""
+ exempt, and they are listed in the entry, as are the values of a `legacy` entry."""
decided: set[tuple[tuple[str, int, tuple[tuple[str, str], ...]], str]] = set()
for point in ALL_POINTS:
if point.in_fit:
@@ -172,19 +183,19 @@ def test_every_fitted_value_is_decided_by_an_in_fit_point() -> None:
f"{entry.estimator} {entry.platform} {name}"
for entry in ENTRIES
for name in entry.values or {}
- if (entry_key(entry), name) not in decided and name not in entry.stand_ins
+ if (entry_key(entry), name) not in decided and name not in entry.stand_ins and not entry.legacy
]
assert not undecided, f"no measured point decides these shipped values: {undecided}"
def test_every_fitted_value_is_the_shipped_fit_of_its_points() -> None:
"""The values are reproducible from the points rather than hand-tuned. A new point that moves a fit fails here,
- naming the values to ship. Only `hand_set_values` are exempt: values off a pixel line of an estimator keyed by no
- platform trait, which its points decide and bound but nothing fits."""
- fitted = fitted_values(shipped_data().values())
+ naming the values to ship. Only `hand_set_values` are exempt: values off a line their entry carries, of an
+ estimator keyed by no platform trait, which its points decide and bound but nothing fits."""
+ fitted = fitted_values(shipped_data().values(), SPECS)
stale = {}
for entry in ENTRIES:
- if entry.values is None:
+ if entry.values is None or entry.legacy:
continue
expected = fitted.get(entry_key(entry), {})
hand_set = hand_set_values(entry, SPECS[entry.estimator])
@@ -198,11 +209,31 @@ def test_every_fitted_value_is_the_shipped_fit_of_its_points() -> None:
assert not stale, f"ship these fitted values: {stale}"
+def test_only_the_listed_entries_ship_hand_set_values() -> None:
+ """The exemption from being decided by and fitted to points is declared per entry here, so it never spreads by a
+ quiet flag in the data, and shipping an entry's fit has to remove it."""
+ legacy = {(entry.estimator, tuple(sorted(entry.platform.items()))) for entry in ENTRIES if entry.legacy}
+ assert legacy == LEGACY_ENTRIES
+
+
+def test_only_an_estimator_keyed_by_no_platform_trait_carries_values_off_a_line() -> None:
+ """The fit check above skips `legacy` entries. An estimator keyed by a platform trait prices lines whose every
+ value is half of one, so a value off one there, legacy or not, is a typo or a term the fit would never check."""
+ off_line = {
+ f"{entry.estimator} {entry.platform}": sorted(
+ set(entry.values) - {f"{part}_{line}" for line in carried_lines(entry) for part in ("k", "b")}
+ )
+ for entry in ENTRIES
+ if entry.values is not None and SPECS[entry.estimator].platform_keys
+ }
+ assert not {where: names for where, names in off_line.items() if names}, off_line
+
+
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())
+ groups = fit_points(shipped_data().values(), SPECS)
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
@@ -220,7 +251,7 @@ 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}
+ ids = {_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"
@@ -231,14 +262,14 @@ def test_every_listed_upper_bound_exception_is_a_shipped_point_that_needs_it() -
@pytest.mark.parametrize("point", POINTS)
def test_every_measured_point_is_bounded_by_its_estimate(point: MeasuredPoint) -> None:
- assert bound_violation(point, _evaluate(point)) is None
+ assert bound_violation(point, SPECS[point.estimator], _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, _id(point)
@pytest.mark.parametrize(
@@ -393,7 +424,12 @@ def _no_terms(features, values):
def _spec(spec_id: str, version: int = 1, coefficients: frozenset[str] = frozenset({"k"})) -> EstimatorSpec:
return EstimatorSpec(
- id=spec_id, version=version, coefficients=coefficients, platform_keys=("conv_backend",), terms=_no_terms
+ id=spec_id,
+ version=version,
+ coefficients=coefficients,
+ platform_keys=("conv_backend",),
+ terms=_no_terms,
+ line=convolution_line,
)
diff --git a/tests/backend/working_memory/test_spec_registry.py b/tests/backend/working_memory/test_spec_registry.py
index 0c323aa179..8cb29a1a52 100644
--- a/tests/backend/working_memory/test_spec_registry.py
+++ b/tests/backend/working_memory/test_spec_registry.py
@@ -3,6 +3,7 @@
import pytest
from invokeai.backend.working_memory import spec as spec_module
+from invokeai.backend.working_memory.fit import convolution_line
from invokeai.backend.working_memory.spec import EstimatorSpec, register, registered_specs
@@ -32,6 +33,7 @@ def _spec(terms, version: int = 1) -> EstimatorSpec:
coefficients=frozenset({"k"}),
platform_keys=("conv_backend",),
terms=terms,
+ line=convolution_line,
)
diff --git a/tests/backend/working_memory/test_user_fit.py b/tests/backend/working_memory/test_user_fit.py
index 64a197a430..431eb259b2 100644
--- a/tests/backend/working_memory/test_user_fit.py
+++ b/tests/backend/working_memory/test_user_fit.py
@@ -10,12 +10,14 @@ 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
+from invokeai.backend.working_memory.spec import EstimatorSpec, import_estimator_modules
+from invokeai.backend.working_memory.user_fit import UserFit, UserLine, UserPoint, fit_user_lines
+from invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_DENOISE_SPEC
MIB = 2**20
DEVICE = torch.device("cuda:0")
PLATFORM = platform_for(DEVICE)
+SPECS = import_estimator_modules()
def _features(side: int, dtype: str = "fp16", tile: int | None = None, **extra: object) -> dict:
@@ -38,7 +40,7 @@ def _points(slope: int, base: int, sides: tuple[int, ...] = (512, 768, 1024), dt
def _fit(points: list[UserPoint]) -> UserFit:
- lines, problems = fit_user_lines(points, PLATFORM)
+ lines, problems = fit_user_lines(points, PLATFORM, SPECS)
assert lines, problems
return UserFit(label="user:dc:env", platform=PLATFORM, lines=lines)
@@ -171,14 +173,14 @@ def test_only_untiled_single_sample_autoencoder_kl_windows_with_demand_and_a_kno
UserPoint("vae.unknown", 2, _features(2048), 10**12),
]
- lines, _ = fit_user_lines(good + ignored, PLATFORM)
+ lines, _ = fit_user_lines(good + ignored, PLATFORM, SPECS)
[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)
+ lines, problems = fit_user_lines(_points(900, 400 * MIB, sides=(1024, 1280)), PLATFORM, SPECS)
assert not lines
[problem] = problems.values()
assert "measure more sizes" in problem
@@ -200,3 +202,31 @@ def test_a_provider_that_raises_leaves_estimates_shipped_and_only_its_own_regist
provide(_fit(_points(900, 400 * MIB)))
user_fit.clear_user_fit_provider(broken)
assert VAE_SD_SPEC.estimate(features, DEVICE).source.startswith("user:")
+
+
+def _denoise_features(image_tokens: int) -> dict:
+ """A plain Z-Image forward, whose features its line admits (`EstimatorSpec.line`)."""
+ return {"image_tokens": image_tokens, "text_tokens": 512, "tokens": image_tokens + 512, "dtype": "bf16",
+ "control_blocks": 0, "has_attention_mask": False, "regional_bias_bytes": 0, "score_matrix_bytes": 0,
+ "lora_count": 0, "dequant_transient_bytes": 0, "fp8_cast_transient_bytes": 0} # fmt: skip
+
+
+def test_the_z_image_denoise_is_moved_by_no_user_line(provide) -> None:
+ """Its line is the shipped fit's alone (`user_calibrated` is off): plain forwards on a token line fit no user line
+ beside a decode's, and a fit that carried a line for its entry anyway leaves its estimates shipped."""
+ forwards = [
+ UserPoint(Z_IMAGE_DENOISE_SPEC.id, Z_IMAGE_DENOISE_SPEC.version, _denoise_features(image), 5000 * image)
+ for image in (1024, 4096, 16384)
+ ]
+ assert Z_IMAGE_DENOISE_SPEC.line(forwards[0].features).fits
+
+ lines, problems = fit_user_lines([*forwards, *_points(900, 400 * MIB)], PLATFORM, SPECS)
+
+ assert [suffix for _, suffix in lines] == ["decode_fp16"] and not problems
+ carrier = user_fit.carrier_key(Z_IMAGE_DENOISE_SPEC.id, Z_IMAGE_DENOISE_SPEC.version, PLATFORM)
+ assert carrier is not None
+ low = UserLine(k=1, b=MIB, x_min=1024, x_max=2**20, points=3)
+ provide(UserFit(label="user:dc:env", platform=PLATFORM, lines={(carrier, "denoise_bf16"): low}))
+ features = _denoise_features(4096)
+ shipped = Z_IMAGE_DENOISE_SPEC.evaluate(features, shipped_coefficients(Z_IMAGE_DENOISE_SPEC, PLATFORM))
+ assert Z_IMAGE_DENOISE_SPEC.estimate(features, DEVICE) == shipped
diff --git a/tests/test_build_shipped_working_memory.py b/tests/test_build_shipped_working_memory.py
index 7b789a51c0..77810cc3d2 100644
--- a/tests/test_build_shipped_working_memory.py
+++ b/tests/test_build_shipped_working_memory.py
@@ -1,5 +1,7 @@
-"""scripts/working_memory/build_shipped.py: calibration store exports into shipped working-memory points and fits."""
+"""scripts/working_memory/build_shipped.py: calibration store exports and point files into shipped working-memory
+points and fits."""
+import itertools
import json
import platform as stdlib_platform
import shutil
@@ -26,6 +28,7 @@ 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 invokeai.backend.z_image.denoise_working_memory import Z_IMAGE_DENOISE_SPEC
from scripts.working_memory.build_shipped import (
DATA_DIR,
RAISE_NOTE,
@@ -37,7 +40,9 @@ from scripts.working_memory.build_shipped import (
merge_points,
point_identity,
point_platform,
+ read_point_files,
refit,
+ write_data,
)
CUDA0 = torch.device("cuda", 0)
@@ -332,6 +337,7 @@ def shipped_checks(monkeypatch: pytest.MonkeyPatch) -> Iterator[Callable[[Path],
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_only_the_listed_entries_ship_hand_set_values()
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()
@@ -489,7 +495,7 @@ def _miopen_native_point(
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))
+ after = refit(merge_points(coefficients.shipped_data(), points), specs)
assert bound_violations(after, specs) == []
[entry] = [
entry
@@ -654,9 +660,7 @@ def test_cards_of_one_name_are_separate_points_and_spreads(
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
- )
+ measurement = Measurement(line="decode_fp32", size=1280**2, demand=reserved, reserved=reserved, allocated=allocated)
assert fragmentation.fragmented([measurement]) == [fragmented]
@@ -687,3 +691,225 @@ def test_a_size_whose_one_window_stands_out_from_the_smaller_sizes_is_flagged_wi
assert flagged == {1216}
main([str(export), "--data-dir", str(DATA_DIR)])
assert "warning: fragmentation? vae.sd" in capsys.readouterr().out
+
+
+DENOISE_SLOPE, DENOISE_BASE = 225280, 100 * MIB
+"""The line the Z-Image denoise points below lie on in bf16 and fp16, 220 KiB per attended token plus 100 MiB; fp32
+measures twice that. The shipped fit adds 5%: 236544 B per token and 105 MiB, and 473088 B and 210 MiB."""
+FITTED = {"bf16": (236544, 105 * MIB), "fp16": (236544, 105 * MIB), "fp32": (473088, 210 * MIB)}
+
+
+def _forward_record(image_tokens: int, dtype: str, *, check: bool = False, **changes: object) -> dict:
+ """A point file record of a plain Z-Image forward as `scripts/calibrate_z_image_working_memory.py` writes one: the
+ platform as `platform_for` gives it, and the script's own keys beside the point's. A check's point is out of the
+ fit."""
+ tokens = image_tokens + 512
+ features = {"image_tokens": image_tokens, "text_tokens": 512, "tokens": tokens, "dtype": dtype,
+ "control_blocks": 0, "has_attention_mask": False, "regional_bias_bytes": 0, "score_matrix_bytes": 0,
+ "lora_count": 0, "dequant_transient_bytes": 0, "fp8_cast_transient_bytes": 0} # fmt: skip
+ measured = (DENOISE_SLOPE * tokens + DENOISE_BASE) * (2 if dtype == "fp32" else 1)
+ return {
+ "estimator": Z_IMAGE_DENOISE_SPEC.id,
+ "version": Z_IMAGE_DENOISE_SPEC.version,
+ "platform": CUDNN_NATIVE | {"os": "linux"},
+ "features": features,
+ "measured_bytes": measured,
+ "method": "demand_peak",
+ "device": "NVIDIA GeForce RTX 4090",
+ "in_fit": not check,
+ "provenance": "scripts/calibrate_z_image_working_memory.py, test",
+ "fit": not check,
+ "point": {"kind": "check" if check else "fit", "image_tokens": image_tokens, "dtype": dtype},
+ "raw": {"cold": {"reserved": measured}, "warm": {"reserved": measured - MIB}},
+ } | changes
+
+
+def _point_file(path: Path, records: list[dict]) -> Path:
+ path.write_text("".join(json.dumps(record) + "\n" for record in records), encoding="utf-8")
+ return path
+
+
+def _denoise_entries(data_dir: Path) -> dict[str, coefficients.CoefficientEntry]:
+ return {",".join(entry.platform.values()): entry for entry in load_data(data_dir)["denoise.json"].coefficients}
+
+
+LEGACY_DENOISE = {f"{part}_denoise_{dtype}": value for dtype in FITTED for part, value in (("k", 262144), ("b", GIB))}
+"""The hand-set constants of a `legacy` Z-Image denoise entry."""
+
+
+def _legacy_data_copy(tmp_path: Path) -> tuple[Path, dict[str, bytes]]:
+ """The shipped data as it was before the RTX 4090's native-allocator denoise points shipped: that entry hand-set
+ and `legacy` again, without its points."""
+ data_dir, _ = _data_copy(tmp_path)
+ data = load_data(data_dir)["denoise.json"]
+ coefficients = [
+ entry.model_copy(update={"values": LEGACY_DENOISE, "legacy": True}) if entry.platform == CUDNN_NATIVE else entry
+ for entry in data.coefficients
+ ]
+ points = [point for point in data.points if point.platform != CUDNN_NATIVE]
+ write_data(data_dir / "denoise.json", data.model_copy(update={"coefficients": coefficients, "points": points}))
+ return data_dir, _files(data_dir)
+
+
+def _test_points(data_dir: Path) -> list[MeasuredPoint]:
+ """The denoise points the test's records or export wrote: their device is not the shipped points' `RTX 4090`. A
+ record names the card as the calibration script does, an export's point by name and device class id."""
+ devices = {RTX_4090.name, f"{RTX_4090.name} ({RTX_4090.id})"}
+ return [point for point in load_data(data_dir)["denoise.json"].points if point.device in devices]
+
+
+def test_fresh_process_points_replace_the_legacy_entry_they_fit_and_leave_the_others_as_they_were(
+ tmp_path: Path, shipped_checks, capsys
+) -> None:
+ """RTX 4090 points under the native allocator, all three dtypes at three sizes: that platform's legacy entry
+ becomes their fit and passes the data checks. Every other entry stays as shipped, the one still legacy included,
+ which no point measures. The script's own keys in a record are ignored."""
+ forwards = [_forward_record(image, dtype) for dtype in FITTED for image in (1024, 4096, 16384)]
+ points = _point_file(tmp_path / "z_image_points.jsonl", forwards)
+ data_dir, _ = _legacy_data_copy(tmp_path)
+
+ assert main(["--points", str(points), "--data-dir", str(data_dir), "--write"]) == 0
+
+ out = capsys.readouterr().out
+ assert "9 fresh-process points from 1 point files; records left out: none" in out
+ assert f"denoise.json: denoise.z_image {CUDNN_NATIVE} is fitted now, no longer legacy" in out
+ assert (
+ "{'conv_backend': 'miopen', 'allocator': 'native'} stays legacy: no in-fit point measures this platform" in out
+ )
+ entries, shipped = _denoise_entries(data_dir), _denoise_entries(DATA_DIR)
+ native, shipped_native = entries.pop("cudnn,native"), shipped.pop("cudnn,native")
+ assert not native.legacy and native.values == {
+ f"{part}_denoise_{dtype}": value
+ for dtype, line in FITTED.items()
+ for part, value in zip("kb", line, strict=True)
+ }
+ # What it floors the platforms it prices unmeasured at stays as declared.
+ assert native.unmeasured_floor == shipped_native.unmeasured_floor != {}
+ assert entries == shipped
+ # The points name the platform as the data keys it: no OS where no entry names one.
+ written = _test_points(data_dir)
+ assert len(written) == 9 and {tuple(point.platform) for point in written} == {("conv_backend", "allocator")}
+ shipped_checks(data_dir)
+
+
+def test_a_check_ships_out_of_the_fit_beside_the_fit_point_whose_features_it_shares(tmp_path: Path) -> None:
+ """The script's checks test an assumption or an analytic term, not the line: a forward with four blocks instead
+ of two, whose features are a fit point's, and one forced onto the math kernel, priced with the score matrix that
+ builds. Both ship out of the fit, bounding their estimates from below only. The four-block forward measured more
+ than the two-block one, yet sits beside it rather than in its place, and neither moves the fit."""
+ forwards = [_forward_record(image, dtype) for dtype in FITTED for image in (1024, 4096, 16384)]
+ two_blocks = forwards[1]
+ four_blocks = _forward_record(4096, "bf16", check=True, measured_bytes=two_blocks["measured_bytes"] + 20 * MIB)
+ forced_math = _forward_record(4096, "bf16", check=True, measured_bytes=9 * GIB)
+ forced_math["features"] |= {"score_matrix_bytes": 30 * 4608 * 4608 * 17}
+ points = _point_file(tmp_path / "with_checks.jsonl", [*forwards, four_blocks, forced_math])
+ data_dir, _ = _legacy_data_copy(tmp_path)
+
+ assert main(["--points", str(points), "--data-dir", str(data_dir), "--write"]) == 0
+
+ written = _test_points(data_dir)
+ shared = [p for p in written if p.features == two_blocks["features"]]
+ assert sorted((p.in_fit, p.measured_bytes) for p in shared) == [
+ (False, four_blocks["measured_bytes"]),
+ (True, two_blocks["measured_bytes"]),
+ ]
+ assert [p.in_fit for p in written].count(False) == 2
+ native = _denoise_entries(data_dir)["cudnn,native"]
+ assert native.values == {
+ f"{part}_denoise_{dtype}": value
+ for dtype, line in FITTED.items()
+ for part, value in zip("kb", line, strict=True)
+ }
+
+
+def test_a_legacy_entry_keeps_its_values_unless_the_points_fit_every_line_and_its_points_bound_them(
+ tmp_path: Path, capsys
+) -> None:
+ """bf16 points alone fit no fp16 or fp32 line, so the entry stays legacy. Its hand-set values then reserve over 3x
+ what the points measured, which the bound rule refuses to write."""
+ points = _point_file(tmp_path / "bf16.jsonl", [_forward_record(image, "bf16") for image in (1024, 4096, 16384)])
+ data_dir, before = _legacy_data_copy(tmp_path)
+
+ assert main(["--points", str(points), "--data-dir", str(data_dir), "--write"]) == 1
+
+ captured = capsys.readouterr()
+ assert (
+ f"note: denoise.z_image {CUDNN_NATIVE} stays legacy: denoise_fp16: no in-fit point measures it; "
+ "denoise_fp32: no in-fit point measures it"
+ ) in captured.out
+ assert "the bounds of these points reject the result" in captured.err
+ assert (
+ "denoise.z_image-cudnn,native-denoise-bf16-1024+512tok-NVIDIAGeForceRTX4090-demand_peak: reserves 3.27x"
+ ) in captured.err
+ assert _files(data_dir) == before
+
+
+def test_probe_windows_alone_never_replace_a_legacy_entrys_hand_set_values(tmp_path: Path, machine, capsys) -> None:
+ """RTX 4090 windows of every dtype at three sizes would fit each line the legacy entry carries. But a window is a
+ warm reading in a running server, which can lie below the cold first run, so it bounds a line from below only: the
+ entry keeps its hand-set values, the windows ship as lower bounds under them, and the note says why."""
+ windows = []
+ for item, (dtype, image) in enumerate(itertools.product(FITTED, (1024, 4096, 16384)), start=1):
+ features = _forward_record(image, dtype)["features"]
+ demand = DENOISE_SLOPE * features["tokens"] + DENOISE_BASE
+ windows.append(
+ _window(item, features, demand, estimator=Z_IMAGE_DENOISE_SPEC.id, version=Z_IMAGE_DENOISE_SPEC.version)
+ )
+ machine(None, "linux")
+ export = _export(tmp_path / f"20261018-120000-box-1-{RTX_4090.id}.json", RTX_4090, windows)
+ data_dir, _ = _legacy_data_copy(tmp_path)
+
+ assert main([str(export), "--data-dir", str(data_dir), "--write"]) == 0
+
+ reasons = "; ".join(
+ f"denoise_{dtype}: only probe_demand points measure it, which bound it from below only" for dtype in FITTED
+ )
+ assert f"note: denoise.z_image {CUDNN_NATIVE} stays legacy: {reasons}" in capsys.readouterr().out
+ native = _denoise_entries(data_dir)["cudnn,native"]
+ assert native.legacy and native.values == LEGACY_DENOISE
+ assert [p.method for p in _test_points(data_dir)] == ["probe_demand"] * len(windows)
+
+
+def test_a_measurement_a_point_file_gives_twice_keeps_its_larger_reading(tmp_path: Path, entries, specs) -> None:
+ """A rerun that reads less, recorded after the first run, does not take its place."""
+ larger = _forward_record(4096, "bf16")
+ smaller = larger | {"measured_bytes": larger["measured_bytes"] - 64 * MIB}
+
+ build = read_point_files([_point_file(tmp_path / "twice.jsonl", [larger, smaller])], specs, entries)
+
+ assert [point.measured_bytes for point in build.points] == [larger["measured_bytes"]]
+ assert build.skipped == {"remeasured, the larger kept": 1}
+
+
+ "changes, message",
+ [
+ pytest.param({"method": "probe_demand"}, "bounds its estimate from below only", id="probe-window"),
+ pytest.param(
+ {"platform": {"conv_backend": "cudnn", "allocator": "expandable", "os": "linux"}},
+ "which `platform.MEASURED` does not list",
+ id="unmeasured-platform",
+ ),
+ ],
+)
+def test_a_record_that_is_no_fresh_process_point_of_a_measured_platform_is_refused(
+ changes: dict, message: str, tmp_path: Path, capsys
+) -> None:
+ points = _point_file(tmp_path / "refused.jsonl", [_forward_record(4096, "bf16", **changes)])
+
+ assert main(["--points", str(points), "--data-dir", str(DATA_DIR)]) == 2
+ assert message in capsys.readouterr().err
+
+
+def test_a_remeasurement_below_the_shipped_point_keeps_it_and_says_so(tmp_path: Path, capsys) -> None:
+ """The shipped point is the larger reading, so it stays; the build names the lower one rather than drop it unseen."""
+ shipped = load_data(DATA_DIR)["denoise.json"].points[0]
+ rerun = shipped.model_dump(mode="json") | {"measured_bytes": shipped.measured_bytes - 64 * MIB}
+ points = _point_file(tmp_path / "rerun.jsonl", [rerun])
+ data_dir, before = _data_copy(tmp_path)
+
+ assert main(["--points", str(points), "--data-dir", str(data_dir), "--write"]) == 0
+
+ out = capsys.readouterr().out
+ assert f"kept shipped {shipped.measured_bytes} over remeasured {shipped.measured_bytes - 64 * MIB}" in out
+ assert _files(data_dir) == before
diff --git a/tests/test_calibrate_z_image_working_memory.py b/tests/test_calibrate_z_image_working_memory.py
new file mode 100644
index 0000000000..d62fb2c81e
--- /dev/null
+++ b/tests/test_calibrate_z_image_working_memory.py
@@ -0,0 +1,407 @@
+"""scripts/calibrate_z_image_working_memory.py: the forwards it plans, the runtime it measures them in, and the lines it
+makes of their windows.
+
+The measurement needs a CUDA or ROCm device and runs by hand (see the script's docstring). These cover what decides the
+lines it writes: which forwards a run measures, that a measuring process applies the server's runtime with the
+allocator it was asked for, and how a cold and a warm forward become a `MeasuredPoint` in the point file, or an invalid
+line that stays out of it. What one window measures is `measurement`'s, tested with the probe's windows.
+"""
+
+import dataclasses
+import json
+import re
+import shutil
+import subprocess
+import sys
+from importlib.util import module_from_spec, spec_from_file_location
+from pathlib import Path
+
+import pytest
+import torch
+from pydantic import ValidationError
+
+from invokeai.backend.working_memory import coefficients, counters
+from invokeai.backend.working_memory.coefficients import MeasuredPoint
+from invokeai.backend.working_memory.counters import CounterReading
+from invokeai.backend.working_memory.measurement import FreshWindow, fresh_window, measure
+from invokeai.backend.working_memory.platform import Platform
+from invokeai.backend.z_image.denoise_working_memory import estimate_z_image_denoise_working_memory
+from scripts.working_memory import build_shipped
+
+pytestmark = pytest.mark.platform_independent
+
+SCRIPT = Path(__file__).parents[1] / "scripts" / "calibrate_z_image_working_memory.py"
+MIB = 2**20
+GIB = 2**30
+
+
+def _load_script():
+ spec = spec_from_file_location("calibrate_z_image_working_memory", SCRIPT)
+ assert spec is not None and spec.loader is not None
+ module = module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+script = _load_script()
+Point = script.Point
+
+GRID = {
+ "text_tokens": 512,
+ "short_text_tokens": 77,
+ "blocks": 2,
+ "extra_blocks": 0,
+ "control_blocks": 15,
+}
+
+
+def _reading(**values) -> CounterReading:
+ """A reading as a measuring process takes it: 1000 bytes reserved, 800 allocated, 1200 at the driver, nothing
+ paged, no failed or retried allocation."""
+ fields = {
+ "reserved": 1000,
+ "allocated": 800,
+ "peak_reserved": 1000,
+ "peak_allocated": 800,
+ "num_ooms": 0,
+ "num_alloc_retries": 0,
+ "driver": 1200,
+ "peak_driver": None,
+ "paged": 0,
+ "device_used": None,
+ "method": "windows-d3dkmt",
+ }
+ return CounterReading(**(fields | values))
+
+
+def _window(oom: bool = False, spill: bool = False, **final) -> FreshWindow:
+ return fresh_window(_reading(), _reading(**final), oom=oom, spill=spill)
+
+
+def _common() -> dict:
+ """The fields of a point the measurement does not decide, as the measuring process takes them."""
+ estimate = estimate_z_image_denoise_working_memory(
+ torch.nn.Module(),
+ image_seq_len=script.image_tokens(1024),
+ text_seq_len=512,
+ lora_count=0,
+ device=torch.device("cpu"),
+ dtype=torch.float32,
+ )
+ return {
+ "estimator": estimate.estimator,
+ "version": estimate.version,
+ "platform": dataclasses.asdict(Platform("cudnn", "native", "windows")),
+ "features": dict(estimate.features),
+ "device": "NVIDIA GeForce RTX 4090",
+ }
+
+
+def _measured_point(line: dict) -> MeasuredPoint:
+ return MeasuredPoint.model_validate(
+ {key: value for key, value in line.items() if key in MeasuredPoint.model_fields}
+ )
+
+
+def test_the_fit_grid_runs_every_size_in_every_dtype_and_the_short_caption_at_its_sizes() -> None:
+ points = script.plan(
+ "fit", sizes=[512, 1024, 1440], dtypes=["bfloat16", "float32"], short_text_sizes=[1024, 1440, 2048], **GRID
+ )
+
+ expected = [
+ (dtype, px, text)
+ for dtype in ("bfloat16", "float32")
+ for px, text in ((512, 512), (1024, 512), (1440, 512), (1024, 77), (1440, 77))
+ ]
+ # 2048px runs no caption at all: it is not among the sizes.
+ assert [(point.dtype, point.px, point.text_tokens) for point in points] == expected
+ assert all(
+ point.fit and point.blocks == 2 and not point.force_math and not point.control_blocks for point in points
+ )
+
+
+def test_extra_blocks_add_one_forward_outside_the_fit_at_1024px_in_the_first_dtype() -> None:
+ points = script.plan(
+ "fit", sizes=[512], dtypes=["float16", "bfloat16"], short_text_sizes=[], **(GRID | {"extra_blocks": 4})
+ )
+
+ assert [point for point in points if not point.fit] == [Point("blocks", 1024, 512, "float16", 4)]
+ assert points[-1].kind == "blocks"
+
+
+def test_each_check_pairs_its_forward_with_a_default_kernel_forward_in_every_dtype() -> None:
+ dtypes = ["bfloat16", "float32"]
+ checks = GRID | {"extra_blocks": 4, "control_blocks": 6}
+ math = script.plan("math", sizes=[512], dtypes=dtypes, short_text_sizes=[], **checks)
+ control = script.plan("control", sizes=[512], dtypes=dtypes, short_text_sizes=[], **checks)
+
+ assert math == [
+ Point("reference", 1024, 512, "bfloat16", 2),
+ Point("math", 1024, 512, "bfloat16", 2, force_math=True),
+ Point("reference", 1024, 512, "float32", 2),
+ Point("math", 1024, 512, "float32", 2, force_math=True),
+ ]
+ assert control == [
+ Point("reference", 1024, 512, "bfloat16", 2),
+ Point("control", 1024, 512, "bfloat16", 2, control_blocks=6),
+ Point("reference", 1024, 512, "float32", 2),
+ Point("control", 1024, 512, "float32", 2, control_blocks=6),
+ ]
+ assert not any(point.fit for point in math + control)
+
+
+ "alloc_conf, configured",
+ [("backend:cudaMallocAsync", "backend:cudaMallocAsync"), ("", None)],
+ ids=["--alloc-conf", "platform-default"],
+)
+def test_a_measuring_process_applies_the_server_runtime_with_the_allocator_it_measures(
+ monkeypatch: pytest.MonkeyPatch, alloc_conf: str, configured
+) -> None:
+ from invokeai.app import run_app
+ from invokeai.app.services.config.config_default import get_config
+
+ applied = []
+ monkeypatch.setattr(run_app, "apply_server_runtime", lambda config, logger: applied.append(config))
+
+ script._apply_server_runtime(alloc_conf)
+
+ (config,) = applied
+ assert config.pytorch_cuda_alloc_conf == configured
+ # Every other setting as a server without a config file reads it.
+ assert config.model_dump(exclude={"pytorch_cuda_alloc_conf"}) == get_config().model_dump(
+ exclude={"pytorch_cuda_alloc_conf"}
+ )
+
+
+WEIGHTS = 1463092352
+"""The bf16 weights of the measured transformer, 2 main blocks: allocated and reserved when a window opens."""
+CONTEXT = 256 * MIB
+"""What the driver counts beyond them at that point: the context and the libraries' workspaces."""
+
+RECORDED = {
+ "RTX 4090, native allocator, 512px": (
+ (367001600, 350224384, 195313664, 8388608),
+ (350224384, 350224384, 186466304, 0),
+ 367001600,
+ ),
+ # HIP's retained pool serves the warm forward: its driver figure does not grow, its reserved bytes decide.
+ "RX 9060 XT, expandable segments, 512px": (
+ (500629504, 316669952, 266485760, 149520384),
+ (0, 232783872, 186466304, 0),
+ 500629504,
+ ),
+ # Here the warm forward demands more than the cold one.
+ "RTX 4090, cudaMallocAsync, 1024px": (
+ (754974720, 738197504, 568122368, 8388608),
+ (838860800, 838860800, 559275008, 0),
+ 838860800,
+ ),
+}
+"""Per run, bf16 with a 512-token caption: the growth of each counter of its cold and its warm forward (driver,
+reserved, allocated and shared-memory bytes) and the point's `measured_bytes`, as the point files of this script's runs
+on these GPUs recorded them."""
+
+
+class _RecordedCounters:
+ """`counters.DeviceCounters` replaying a forward's readings: its baseline, then its close."""
+
+ def __init__(self, first: CounterReading, final: CounterReading):
+ self._readings = [first, final]
+
+ def read(self) -> CounterReading:
+ return self._readings.pop(0) if len(self._readings) > 1 else self._readings[0]
+
+ def synchronize(self) -> None:
+ pass
+
+ def reset_peaks(self) -> None:
+ pass
+
+ def close(self) -> None:
+ pass
+
+
+def _recorded_forward(monkeypatch: pytest.MonkeyPatch, growth: tuple[int, int, int, int]) -> FreshWindow:
+ """A forward measured as the script measures it, on readings that grow by `growth` over the baseline."""
+ driver, reserved, allocated, paged = growth
+ first = _reading(
+ reserved=WEIGHTS,
+ allocated=WEIGHTS,
+ peak_reserved=WEIGHTS,
+ peak_allocated=WEIGHTS,
+ driver=WEIGHTS + CONTEXT,
+ paged=0,
+ )
+ final = _reading(
+ reserved=WEIGHTS + reserved,
+ allocated=WEIGHTS,
+ peak_reserved=WEIGHTS + reserved,
+ peak_allocated=WEIGHTS + allocated,
+ driver=WEIGHTS + CONTEXT + driver,
+ paged=paged,
+ )
+ monkeypatch.setattr(counters, "DeviceCounters", lambda device: _RecordedCounters(first, final))
+ return measure(torch.device("cpu"), lambda: None)
+
+
[email protected]("run", RECORDED)
+def test_recorded_counters_give_the_demand_and_the_method_of_the_shipped_points(
+ monkeypatch: pytest.MonkeyPatch, run: str
+) -> None:
+ cold_growth, warm_growth, measured_bytes = RECORDED[run]
+ cold, warm = _recorded_forward(monkeypatch, cold_growth), _recorded_forward(monkeypatch, warm_growth)
+
+ line = script.point_line(
+ Point("fit", 512, 512, "bfloat16", 2), common=_common(), provenance="m", windows=[cold, warm], raw={}
+ )
+
+ # The paged growth stays below the spill tolerance, 143 MiB on the RX 9060 XT included.
+ assert cold.reasons == warm.reasons == ()
+ assert cold.counter_method == warm.counter_method == "windows-d3dkmt"
+ point = _measured_point(line)
+ assert (point.measured_bytes, point.method) == (measured_bytes, "demand_peak")
+
+
+def test_a_point_is_the_larger_demand_of_its_cold_and_warm_forward_and_the_file_gets_it_as_a_measured_point() -> None:
+ cold = _window(peak_reserved=5000, driver=6200)
+ warm = _window(peak_reserved=5400, driver=5300)
+ common = _common()
+
+ line = script.point_line(
+ Point("fit", 1024, 512, "float32", 2), common=common, provenance="measured", windows=[cold, warm], raw={"x": 1}
+ )
+ record = script.file_record(line)
+
+ assert line["status"] == "point" and record is not None and "status" not in record
+ point = _measured_point(record)
+ assert (point.measured_bytes, point.method, point.in_fit) == (5000, "demand_peak", True)
+ assert point.estimator == "denoise.z_image" and point.features == common["features"]
+ assert point.platform == {"conv_backend": "cudnn", "allocator": "native", "os": "windows"}
+ assert record["fit"] is True
+ assert record["raw"] == {"x": 1, "cold": dataclasses.asdict(cold), "warm": dataclasses.asdict(warm)}
+ assert record["point"] == {
+ "kind": "fit",
+ "px": 1024,
+ "text_tokens": 512,
+ "dtype": "float32",
+ "blocks": 2,
+ "force_math": False,
+ "control_blocks": 0,
+ }
+
+
+def test_a_check_point_stays_out_of_the_fit() -> None:
+ windows = [_window(peak_reserved=5000), _window(peak_reserved=5000)]
+
+ line = script.point_line(
+ Point("math", 1024, 512, "float32", 2, force_math=True),
+ common=_common(),
+ provenance="measured",
+ windows=windows,
+ raw={},
+ )
+
+ assert line["fit"] is False
+ assert _measured_point(line).in_fit is False
+
+
+def test_a_fit_grid_forward_its_line_does_not_admit_ships_out_of_the_fit_and_an_admitted_one_stays_bounded(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ """On a build whose SDPA kernel materializes the score matrix, a fit-grid forward carries a score term its line
+ does not price: it measures that term, as a check does. The data builder takes it out of the fit, so the estimate,
+ its line plus the term, only has to cover the measured peak. The same peak of a forward its line admits stays in
+ the fit, and the upper bound still refuses an estimate over 1.3x of it."""
+ # A card of its own: no shipped point of the same measurement keeps its place.
+ common = _common() | {"device": "Test GPU"}
+ with_scores = common | {"features": common["features"] | {"score_matrix_bytes": GIB}}
+ windows = [_window(peak_reserved=GIB), _window(peak_reserved=GIB)]
+ data_dir = tmp_path / "data"
+ shutil.copytree(build_shipped.DATA_DIR, data_dir)
+
+ def build(name: str, common: dict, *flags: str) -> tuple[dict, int]:
+ line = script.point_line(
+ Point("fit", 1024, 512, "float32", 2), common=common, provenance="m", windows=windows, raw={}
+ )
+ points = tmp_path / f"{name}.jsonl"
+ points.write_text(json.dumps(script.file_record(line)) + "\n", encoding="utf-8")
+ return line, build_shipped.main(["--points", str(points), "--data-dir", str(data_dir), *flags])
+
+ admitted, refused = build("admitted", common)
+ assert admitted["in_fit"] is True and refused == 1
+ point_id = "denoise.z_image-cudnn,native-denoise-fp32-4096+512tok-TestGPU-demand_peak"
+ assert re.search(
+ rf"{re.escape(point_id)}: reserves [0-9.]+x the measured peak, over 1\.3x", capsys.readouterr().err
+ )
+
+ off_line, written = build("with_scores", with_scores, "--write")
+ assert written == 0, capsys.readouterr().err
+ assert off_line["fit"] is True and off_line["in_fit"] is False
+ points = coefficients.load_data(data_dir)["denoise.json"].points
+ assert [point.in_fit for point in points if point.device == "Test GPU"] == [False]
+
+
+def test_without_the_drivers_figure_a_point_is_a_reserved_peak_of_torchs_counters_alone() -> None:
+ with_driver = _window(peak_reserved=3000, driver=9000)
+ without = _window(peak_reserved=3500, peak_allocated=3600, driver=None, method="torch-only")
+
+ line = script.point_line(
+ Point("fit", 1024, 512, "float32", 2), common=_common(), provenance="m", windows=[with_driver, without], raw={}
+ )
+
+ # The driver's 7800 bytes of the cold forward are not torch's: the bytes are what the method says they are.
+ assert (line["measured_bytes"], line["method"]) == (2800, "reserved_peak")
+
+
+def test_an_invalid_forward_is_no_measured_point_and_stays_out_of_the_file() -> None:
+ clean = _window(peak_reserved=3000)
+ retried = _window(num_alloc_retries=1, peak_reserved=2500)
+ out_of_memory = _window(oom=True, peak_reserved=9000)
+ point = Point("fit", 2048, 512, "float32", 2)
+
+ retried_line = script.point_line(point, common=_common(), provenance="m", windows=[clean, retried], raw={})
+ oom_line = script.point_line(point, common=_common(), provenance="m", windows=[out_of_memory], raw={})
+
+ assert (retried_line["status"], retried_line["reasons"]) == ("invalid", ["alloc_retry"])
+ assert (oom_line["status"], oom_line["reasons"], set(oom_line["raw"])) == ("invalid", ["oom"], {"cold"})
+ for line in (retried_line, oom_line):
+ assert not {"measured_bytes", "method", "provenance"} & set(line)
+ with pytest.raises(ValidationError):
+ _measured_point(line)
+ # The data builder refuses a point file record that is no measured point.
+ assert script.file_record(line) is None
+ assert script.file_record(script.failed_line(point, "exit code 1")) is None
+
+
+def test_the_runtime_facts_name_the_estimator_file_and_feed_the_provenance_and_the_header(monkeypatch) -> None:
+ # The questions only a GPU answers; the rest is this process's own runtime.
+ monkeypatch.setattr(torch.version, "hip", None)
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device=None: "NVIDIA GeForce RTX 4090")
+ monkeypatch.setattr(torch.cuda, "get_allocator_backend", lambda: "native")
+
+ facts = script._runtime_facts(torch.device("cuda"), "windows")
+
+ module = (Path(__file__).parents[1] / "invokeai" / "backend" / "z_image" / "denoise_working_memory.py").resolve()
+ assert Path(facts["estimator_module"]) == module
+ provenance = script.provenance(Point("fit", 1024, 512, "bfloat16", 2), facts, "2026-10-18")
+ assert provenance.startswith("scripts/calibrate_z_image_working_memory.py (2026-10-18): NVIDIA GeForce RTX 4090, ")
+ header = script._runtime_header(facts, {"conv_backend": "cudnn", "allocator": "native", "os": "windows"})
+ assert header.endswith(f"estimator from {module}")
+
+
+def test_the_script_leaves_torch_unimported_so_a_measuring_process_can_configure_the_allocator_first() -> None:
+ # A measuring process runs the script; `apply_rocm_windows_allocator_default` skips with a warning, and
+ # `configure_torch_cuda_allocator` raises, once torch is imported.
+ program = (
+ "import sys\n"
+ "from importlib.util import module_from_spec, spec_from_file_location\n"
+ f"spec = spec_from_file_location('calibrate_z_image_working_memory', {str(SCRIPT)!r})\n"
+ "spec.loader.exec_module(module_from_spec(spec))\n"
+ "print(sorted(name for name in sys.modules if name == 'torch' or name.startswith('torch.')))\n"
+ )
+
+ result = subprocess.run([sys.executable, "-c", program], capture_output=True, text=True, timeout=300)
+
+ assert result.returncode == 0, result.stderr[-3000:]
+ assert result.stdout.strip() == "[]"