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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
perf(webv2): grow layer caches without a CPU round trip
joshistoast1931bc289788
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.tsindex f1c6073783..72d9c8b1b8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/renderController.ts@@ -20,6 +20,21 @@ const wrapCanvasSurface = (canvas: HTMLCanvasElement): RasterSurface => {canvas.width = width;canvas.height = height;},+ // This wraps the canvas ELEMENT that is mounted in the document, so it+ // cannot use the swap-the-backing-store trick the offscreen surfaces use —+ // the element has to stay the one the page is displaying. It copies through+ // a temporary instead. Nothing calls this on the display surface (only layer+ // caches grow), so the slower shape costs nothing; it is here to honour the+ // contract rather than to be used.+ resizePreserving(width: number, height: number, dx: number, dy: number) {+ const previous = document.createElement('canvas');+ previous.width = canvas.width;+ previous.height = canvas.height;+ previous.getContext('2d')?.drawImage(canvas, 0, 0);+ canvas.width = width;+ canvas.height = height;+ ctx.drawImage(previous, dx, dy);+ },get width() {return canvas.width;},diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.tsindex c2be3c8b27..0149fb0d19 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.test.ts@@ -61,6 +61,7 @@ const createFixedPixelBackend = (pixel: readonly [number, number, number, numberdrawnCanvases,height,resize: () => {},+ resizePreserving: () => {},transforms,width,};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.test.tsindex 2e2feb91e2..886ef4c79b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/controlTransparency.test.ts@@ -112,6 +112,7 @@ const createFakeBackend = (sourcePixels: Uint8ClampedArray): RasterBackend & { rheight,putImageDataCalls,resize: () => {},+ resizePreserving: () => {},width,};created.push(surface);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.tsindex 12e6605b18..9313b8323a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.test.ts@@ -263,17 +263,15 @@ describe('growToRect (paint caches grow with strokes)', () => {expect(grown.surface.width).toBe(40);expect(grown.surface.height).toBe(40);- // The old pixels were snapshotted before the (clearing) resize and blitted- // back at their layer-local position within the grown surface: old origin- // (10,10) minus new origin (-10,-10) = surface (20,20).+ // The growth preserves the old pixels at their layer-local position within+ // the grown surface: old origin (10,10) minus new origin (-10,-10) =+ // surface (20,20). It must NOT go through a CPU round trip to do it — the+ // whole point of `resizePreserving` is that the copy stays on the GPU, and+ // a `getImageData` here would mean that regressed.const log = (grown.surface as StubRasterSurface).callLog;- const snapshot = log.find((e) => e.op === 'getImageData');- expect(snapshot?.args).toEqual([0, 0, 20, 20]);- const resizeIndex = log.findIndex((e) => e.op === 'resize');- const putIndex = log.findIndex((e) => e.op === 'putImageData');- expect(resizeIndex).toBeGreaterThan(-1);- expect(putIndex).toBeGreaterThan(resizeIndex);- expect(log[putIndex]?.args.slice(1)).toEqual([20, 20]);+ expect(log.filter((e) => e.op === 'resizePreserving').map((e) => e.args)).toEqual([[40, 40, 20, 20]]);+ expect(log.map((e) => e.op)).not.toContain('getImageData');+ expect(log.map((e) => e.op)).not.toContain('putImageData');});it('is a no-op (no resize, no blit) when the current extent already covers the request', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.tsindex 66dedaded3..0f7da28823 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCache.ts@@ -318,21 +318,21 @@ export const createLayerCacheStore = (touch(existing);return existing;}- // Snapshot the old pixels BEFORE resizing (resize clears the backing canvas),- // then blit them back at their new offset within the grown surface. Skip the- // copy when the old extent was empty (nothing to preserve).- const surface = existing.surface;- let snapshot: ImageData | null = null;- if (!curEmpty && cur.width > 0 && cur.height > 0) {- snapshot = surface.ctx.getImageData(0, 0, cur.width, cur.height);- }// The surface origin moves with the grown rect, so every surface-local rect// recorded so far is void. Dropping the trail makes derived surfaces rebuild// wholesale for one frame rather than refresh the wrong pixels.damageTrails.delete(layerId);- surface.resize(newRect.width, newRect.height);- if (snapshot) {- surface.ctx.putImageData(snapshot, cur.x - newRect.x, cur.y - newRect.y);+ // Grow onto a fresh backing store with the old pixels blitted across, at+ // their new offset within it. `resize` cannot do this — it clears — so the+ // pixels would otherwise have to make a CPU round trip, which measured as+ // roughly the whole cost of the growth again on top of the allocation. This+ // is the hot path for a stroke: painting outward grows the cache once per+ // chunk boundary crossed, and each growth stalls the gesture.+ const surface = existing.surface;+ if (!curEmpty && cur.width > 0 && cur.height > 0) {+ surface.resizePreserving(newRect.width, newRect.height, cur.x - newRect.x, cur.y - newRect.y);+ } else {+ surface.resize(newRect.width, newRect.height);}existing.rect = newRect;touch(existing);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheGrowth.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheGrowth.browser.test.tsnew file mode 100644index 0000000000..a54d9b9038--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/layerCacheGrowth.browser.test.ts@@ -0,0 +1,124 @@+import type { Rect } from '@workbench/canvas-engine/types';++import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { describe, expect, it } from 'vitest';++/**+ * Growing a layer cache is the one place the engine moves a whole surface's+ * pixels, and it happens repeatedly mid-stroke. It preserves them by adopting a+ * fresh backing store and blitting the old canvas into it (`resizePreserving`)+ * rather than round-tripping through `getImageData`/`putImageData`. That is+ * measurably faster, but it also means the copy is real GPU work with a real+ * offset — a wrong `dx`/`dy`, or a blit that silently does nothing, would+ * corrupt layer content on any stroke that paints outward.+ *+ * The node tests can only assert the ARGUMENTS, because the stub surface holds+ * no pixels. These assert the pixels.+ */++/** Distinctly-coloured marks, addressed in layer-local space. */+const MARKS: { color: [number, number, number, number]; local: { x: number; y: number } }[] = [+ { color: [255, 0, 0, 255], local: { x: 105, y: 105 } },+ { color: [0, 255, 0, 255], local: { x: 285, y: 105 } },+ { color: [0, 0, 255, 255], local: { x: 105, y: 285 } },+ { color: [255, 255, 0, 255], local: { x: 285, y: 285 } },+ // A semi-transparent mark: a blit that un-premultiplies and re-premultiplies+ // would shift these channels, and a stroke's "before" snapshot is only+ // pristine if they survive intact.+ { color: [40, 180, 220, 128], local: { x: 200, y: 200 } },+];++const START: Rect = { height: 200, width: 200, x: 100, y: 100 };++const growthCases: { grow: Rect; label: string }[] = [+ { grow: { height: 200, width: 200, x: -50, y: -50 }, label: 'up and to the left (origin moves)' },+ { grow: { height: 200, width: 200, x: 250, y: 250 }, label: 'down and to the right (origin fixed)' },+ { grow: { height: 100, width: 800, x: -300, y: 150 }, label: 'sideways only' },+ { grow: { height: 900, width: 100, x: 150, y: -400 }, label: 'upward only' },+];++describe('growToRect preserves pixels', () => {+ it.each(growthCases)('$label', ({ grow }) => {+ const store = createLayerCacheStore(createDomRasterBackend());+ const entry = store.growToRect('L', START);+ const before = entry.surface;++ for (const mark of MARKS) {+ const [r, g, b, a] = mark.color;+ entry.surface.ctx.fillStyle = `rgba(${r},${g},${b},${a / 255})`;+ entry.surface.ctx.fillRect(mark.local.x - START.x, mark.local.y - START.y, 10, 10);+ }++ // Sample what is actually on the surface rather than the nominal fill+ // colour: a semi-transparent fill is stored premultiplied, so it reads back+ // a step off what was asked for whether or not it is ever moved. Comparing+ // against this isolates the growth, which is what is under test.+ const priorRect = entry.rect;+ const prior = MARKS.map(+ (mark) =>+ entry.surface.ctx.getImageData(mark.local.x - priorRect.x + 5, mark.local.y - priorRect.y + 5, 1, 1).data+ );++ const grown = store.growToRect('L', grow);++ // Derived-surface caches key on the surface OBJECT, so swapping the backing+ // canvas must not swap the surface out from under them.+ expect(grown.surface).toBe(before);+ expect(grown.surface.width).toBe(grown.rect.width);+ expect(grown.surface.height).toBe(grown.rect.height);++ MARKS.forEach((mark, i) => {+ const sx = mark.local.x - grown.rect.x;+ const sy = mark.local.y - grown.rect.y;+ const pixel = grown.surface.ctx.getImageData(sx + 5, sy + 5, 1, 1).data;+ const expected = prior[i]!;+ expect({+ at: `${mark.color.join(',')}`,+ px: [pixel[0], pixel[1], pixel[2], pixel[3]],+ }).toEqual({ at: `${mark.color.join(',')}`, px: [expected[0], expected[1], expected[2], expected[3]] });+ });+ });++ it('leaves the area the growth exposed transparent', () => {+ const store = createLayerCacheStore(createDomRasterBackend());+ const entry = store.growToRect('L', START);+ entry.surface.ctx.fillStyle = '#ffffff';+ entry.surface.ctx.fillRect(0, 0, START.width, START.height);++ const grown = store.growToRect('L', { height: 200, width: 200, x: -50, y: -50 });+ // (0,0) in the grown surface is layer-local (-50,-50) — outside the old+ // extent, so it must be untouched, not a smeared edge of the blit.+ const pixel = grown.surface.ctx.getImageData(0, 0, 1, 1).data;+ expect([pixel[0], pixel[1], pixel[2], pixel[3]]).toEqual([0, 0, 0, 0]);+ });++ it('keeps the pixels across a run of successive growths', () => {+ // A single stroke crosses many chunk boundaries, so the pixels are copied+ // again and again. Any per-growth drift (a rounding slip in the offset, or a+ // blit that resamples) compounds; one growth is not enough to catch it.+ const store = createLayerCacheStore(createDomRasterBackend());+ store.growToRect('L', START);+ const entry = store.get('L')!;+ entry.surface.ctx.fillStyle = 'rgb(220,30,90)';+ entry.surface.ctx.fillRect(100, 100, 10, 10); // layer-local (200,200)+ // A semi-transparent mark too: this is the one that could drift, since a+ // copy that un-premultiplies and re-premultiplies loses a step. It must+ // settle rather than lose a step per growth — a stroke's "before" snapshot+ // is read off this surface, so drift here would slowly lift the pixels the+ // gesture is supposed to leave pristine.+ entry.surface.ctx.fillStyle = 'rgba(40,180,220,0.5)';+ entry.surface.ctx.fillRect(20, 20, 10, 10); // layer-local (120,120)+ const settled = entry.surface.ctx.getImageData(25, 25, 1, 1).data;++ for (let i = 1; i <= 12; i++) {+ store.growToRect('L', { height: 64, width: 64, x: 100 - i * 37, y: 100 - i * 53 });+ }++ const grown = store.get('L')!;+ const opaque = grown.surface.ctx.getImageData(205 - grown.rect.x, 205 - grown.rect.y, 1, 1).data;+ expect([opaque[0], opaque[1], opaque[2], opaque[3]]).toEqual([220, 30, 90, 255]);+ const faint = grown.surface.ctx.getImageData(125 - grown.rect.x, 125 - grown.rect.y, 1, 1).data;+ expect([faint[0], faint[1], faint[2], faint[3]]).toEqual([settled[0], settled[1], settled[2], settled[3]]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.tsindex 5ae536cf31..dff337fd5b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts@@ -164,6 +164,18 @@ class StubRasterSurfaceImpl implements StubRasterSurface {this.width = w;this.height = h;}++ /**+ * The stub holds no pixels, so this only records the resize and the offset the+ * real surface would have blitted the old canvas to. Unlike the real surface+ * the `ctx` is NOT replaced — keeping one call log per surface is what lets+ * tests assert on a surface's whole history across a growth.+ */+ resizePreserving(w: number, h: number, dx: number, dy: number): void {+ this.callLog.push({ args: [w, h, dx, dy], op: 'resizePreserving' });+ this.width = w;+ this.height = h;+ }}/**diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.tsindex f3b7af6276..ade9a2df50 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.ts@@ -13,6 +13,29 @@ export interface RasterSurface {readonly width: number;readonly height: number;resize(w: number, h: number): void;+ /**+ * Resizes to `w`×`h` while keeping the current pixels, placed at `(dx, dy)`+ * in the new surface.+ *+ * This exists because {@link resize} cannot preserve anything: assigning+ * `canvas.width` resets the backing store, so a caller that wants its pixels+ * back has to read them out to the CPU first and upload them again. That+ * round trip is the dominant cost of growing a layer cache during a stroke —+ * measured at 33.8 ms for a 3520×3200 → 3840×3712 growth, against a 14.9 ms+ * floor for reallocating and preserving nothing.+ *+ * Adopting a fresh canvas and blitting the old one into it does the copy on+ * the GPU instead, for 17.9 ms on the same growth. It costs no extra+ * allocation — the copy's target IS the new surface, and the old canvas is+ * dropped — which is what separates it from a temp-buffer scheme, where the+ * second allocation gives back everything the faster copy wins.+ *+ * `canvas` and `ctx` are therefore REPLACED, not mutated. The surface object+ * itself keeps its identity (caches key derived surfaces on it), but anything+ * holding a reference to the old `canvas`/`ctx` across this call is holding a+ * detached one. As with `resize`, all context state resets to defaults.+ */+ resizePreserving(w: number, h: number, dx: number, dy: number): void;}export interface RasterSurfaceOptions {@@ -56,16 +79,22 @@ class OffscreenRasterSurface implements RasterSurface {ctx: OffscreenCanvasRenderingContext2D;width: number;height: number;+ private readonly options: RasterSurfaceOptions | undefined;constructor(width: number, height: number, options?: RasterSurfaceOptions) {+ this.options = options;this.canvas = new OffscreenCanvas(width, height);- const ctx = this.canvas.getContext('2d', { willReadFrequently: options?.willReadFrequently });+ this.ctx = this.acquire();+ this.width = width;+ this.height = height;+ }++ private acquire(): OffscreenCanvasRenderingContext2D {+ const ctx = this.canvas.getContext('2d', { willReadFrequently: this.options?.willReadFrequently });if (!ctx) {throw new Error('Failed to acquire a 2D context from OffscreenCanvas');}- this.ctx = ctx;- this.width = width;- this.height = height;+ return ctx;}resize(w: number, h: number): void {@@ -74,6 +103,15 @@ class OffscreenRasterSurface implements RasterSurface {this.width = w;this.height = h;}++ resizePreserving(w: number, h: number, dx: number, dy: number): void {+ const previous = this.canvas;+ this.canvas = new OffscreenCanvas(w, h);+ this.ctx = this.acquire();+ this.ctx.drawImage(previous, dx, dy);+ this.width = w;+ this.height = h;+ }}class DomCanvasRasterSurface implements RasterSurface {@@ -81,18 +119,24 @@ class DomCanvasRasterSurface implements RasterSurface {ctx: CanvasRenderingContext2D;width: number;height: number;+ private readonly options: RasterSurfaceOptions | undefined;constructor(width: number, height: number, options?: RasterSurfaceOptions) {+ this.options = options;this.canvas = document.createElement('canvas');this.canvas.width = width;this.canvas.height = height;- const ctx = this.canvas.getContext('2d', { willReadFrequently: options?.willReadFrequently });+ this.ctx = this.acquire();+ this.width = width;+ this.height = height;+ }++ private acquire(): CanvasRenderingContext2D {+ const ctx = this.canvas.getContext('2d', { willReadFrequently: this.options?.willReadFrequently });if (!ctx) {throw new Error('Failed to acquire a 2D context from HTMLCanvasElement');}- this.ctx = ctx;- this.width = width;- this.height = height;+ return ctx;}resize(w: number, h: number): void {@@ -101,6 +145,17 @@ class DomCanvasRasterSurface implements RasterSurface {this.width = w;this.height = h;}++ resizePreserving(w: number, h: number, dx: number, dy: number): void {+ const previous = this.canvas;+ this.canvas = document.createElement('canvas');+ this.canvas.width = w;+ this.canvas.height = h;+ this.ctx = this.acquire();+ this.ctx.drawImage(previous, dx, dy);+ this.width = w;+ this.height = h;+ }}/**diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.tsindex 13bbb42ae3..8c5ff82348 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts@@ -36,7 +36,7 @@ const createFixedPixelBackend = (pixel: MutablePixel): RasterBackend => ({save: () => {},setTransform: () => {},} as unknown as OffscreenCanvasRenderingContext2D;- return { canvas, ctx, height, resize: () => {}, width };+ return { canvas, ctx, height, resize: () => {}, resizePreserving: () => {}, width };},encodeSurface: () => Promise.resolve(new Blob()),});