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(image-map): make zooming a large map cheap
Lincoln Steinc6a8d0e5309a
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.tsindex 8ca7d35397..367f3dcc52 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.ts@@ -27,11 +27,12 @@ const mountHost = (): HTMLElement => {return element;};-const attach = (element: HTMLElement, ranges: AxisRanges): { current: AxisRanges } => {- const state = { current: ranges };+const attach = (element: HTMLElement, ranges: AxisRanges): { applied: number; current: AxisRanges } => {+ const state = { applied: 0, current: ranges };detach = attachWheelZoom(element, {applyRanges: (next) => {+ state.applied += 1;state.current = next;},readRanges: () => state.current,@@ -40,6 +41,16 @@ const attach = (element: HTMLElement, ranges: AxisRanges): { current: AxisRangesreturn state;};+/**+ * Zooms are coalesced into the next animation frame, so nothing is applied+ * until one passes. Two frames, because the first only guarantees the+ * callback has been scheduled by the dispatch above.+ */+const settleFrames = (): Promise<void> =>+ new Promise((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+const spanOf = (ranges: AxisRanges): number => ranges.x[1] - ranges.x[0];const touchAt = (element: HTMLElement, identifier: number, clientX: number): Touch =>@@ -57,7 +68,7 @@ afterEach(() => {});describe('attachWheelZoom pinch bookkeeping', () => {- it('re-baselines when a third finger lifts instead of jumping the viewport', () => {+ it('re-baselines when a third finger lifts instead of jumping the viewport', async () => {const element = mountHost();const state = attach(element, { x: [0, 100], y: [0, 100] });@@ -75,14 +86,21 @@ describe('attachWheelZoom pinch bookkeeping', () => {// Back to two fingers, now far apart. Measuring against the stale 100px// baseline would scale the view by ~1/3.8 in a single frame.dispatchTouch(element, 'touchend', [touchAt(element, 1, 10), touchAt(element, 2, 390)]);+ await settleFrames();const spanBefore = spanOf(state.current);+ const appliedBefore = state.applied;+dispatchTouch(element, 'touchmove', [touchAt(element, 1, 10), touchAt(element, 2, 390)]);+ await settleFrames();+ // "Nothing moved" has to mean the gesture ran and correctly produced no+ // movement — a zoom that never applied would satisfy the span check too.+ expect(state.applied).toBe(appliedBefore);expect(spanOf(state.current)).toBeCloseTo(spanBefore, 6);});- it('still pinches normally after the interruption', () => {+ it('still pinches normally after the interruption', async () => {const element = mountHost();const state = attach(element, { x: [0, 100], y: [0, 100] });@@ -91,25 +109,66 @@ describe('attachWheelZoom pinch bookkeeping', () => {// Fingers apart by 2x zooms in, halving the visible span.dispatchTouch(element, 'touchmove', [touchAt(element, 1, 100), touchAt(element, 2, 300)]);+ await settleFrames();expect(spanOf(state.current)).toBeCloseTo(spanBefore / 2, 6);});});describe('attachWheelZoom wheel deltas', () => {- it('zooms usefully for a line-mode wheel, as Firefox reports one', () => {+ it('zooms usefully for a line-mode wheel, as Firefox reports one', async () => {const element = mountHost();const state = attach(element, { x: [0, 100], y: [0, 100] });element.dispatchEvent(new WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 200, clientY: 200, deltaMode: 1, deltaY: 3 }));+ await settleFrames();// Read as pixels this would be a 0.3% change, which is no zoom at all.expect(spanOf(state.current)).toBeGreaterThan(102);});- it('does not let ctrl held over a real wheel jump the view', () => {+ it('applies one zoom per frame however fast the wheel emits', async () => {+ // A wheel outruns a frame by an order of magnitude, and each applied zoom+ // is a plotly relayout over the whole scene: one per event queued+ // relayouts behind the cursor on a large map.+ const element = mountHost();+ const state = attach(element, { x: [0, 100], y: [0, 100] });++ for (let index = 0; index < 12; index++) {+ element.dispatchEvent(+ new WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 200, clientY: 200, deltaY: -100 })+ );+ }++ expect(state.applied).toBe(0);++ await settleFrames();++ expect(state.applied).toBe(1);+ // Coalesced, not dropped: twelve zoom-ins compose into one much larger+ // step rather than collapsing to a single event's worth.+ expect(spanOf(state.current)).toBeLessThan(50);+ });++ it('drops a queued zoom when the map goes away before the frame runs', async () => {+ // The owning effect detaches and then purges the plotly div; a frame+ // that survived the detach would relayout a purged container.+ const element = mountHost();+ const state = attach(element, { x: [0, 100], y: [0, 100] });++ element.dispatchEvent(+ new WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 200, clientY: 200, deltaY: -100 })+ );+ detach?.();+ detach = null;+ await settleFrames();++ expect(state.applied).toBe(0);+ });++ it('does not let ctrl held over a real wheel jump the view', async () => {const element = mountHost();const state = attach(element, { x: [0, 100], y: [0, 100] });@@ -123,7 +182,11 @@ describe('attachWheelZoom wheel deltas', () => {deltaY: 100,}));+ await settleFrames();+ // An unapplied zoom would also satisfy the bound below, so check the+ // gesture actually landed before reading it.+ expect(state.applied).toBe(1);// The trackpad-pinch gain on a mouse-sized delta would be ~2.7x.expect(spanOf(state.current)).toBeLessThan(125);});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.tsindex 4f8e040fde..93976b889c 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts@@ -26,6 +26,44 @@ const touchDistance = (touches: TouchList): number => {};export const attachWheelZoom = (element: HTMLElement, host: ZoomHost): (() => void) => {+ // A wheel emits far faster than a frame, and each applied zoom is a plotly+ // relayout over the whole scene. Applying one per event queued relayouts+ // behind the cursor on a large map; coalescing into the next frame caps it+ // at one, and costs nothing on a map small enough not to care.+ //+ // Factors multiply, so a frame's worth of events composes into a single+ // equivalent zoom. The anchor is the newest pointer position: events inside+ // one frame are milliseconds apart, so it has barely moved.+ let queuedFactor = 1;+ let queuedClientX = 0;+ let queuedClientY = 0;+ let frame: number | null = null;++ const applyQueuedZoom = () => {+ frame = null;+ const factor = queuedFactor;++ queuedFactor = 1;++ if (factor !== 1) {+ zoomAtClientPoint(queuedClientX, queuedClientY, factor);+ }+ };++ const queueZoom = (clientX: number, clientY: number, factor: number) => {+ if (factor === 1) {+ // A horizontal-only wheel scales nothing; scheduling a frame for it+ // would cost a callback per event to apply no change.+ return;+ }++ queuedFactor *= factor;+ queuedClientX = clientX;+ queuedClientY = clientY;++ frame ??= requestAnimationFrame(applyQueuedZoom);+ };+const zoomAtClientPoint = (clientX: number, clientY: number, factor: number) => {const ranges = host.readRanges();@@ -48,7 +86,7 @@ export const attachWheelZoom = (element: HTMLElement, host: ZoomHost): (() => voconst handleWheel = (event: WheelEvent) => {// Also stops ctrl+wheel browser page zoom over the map.event.preventDefault();- zoomAtClientPoint(event.clientX, event.clientY, zoomFactorFromWheel(event.deltaY, event.deltaMode, event.ctrlKey));+ queueZoom(event.clientX, event.clientY, zoomFactorFromWheel(event.deltaY, event.deltaMode, event.ctrlKey));};let pinchDistance: number | null = null;@@ -85,7 +123,7 @@ export const attachWheelZoom = (element: HTMLElement, host: ZoomHost): (() => voif (distance > 0) {const centerX = (event.touches[0].clientX + event.touches[1].clientX) / 2;const centerY = (event.touches[0].clientY + event.touches[1].clientY) / 2;- zoomAtClientPoint(centerX, centerY, pinchDistance / distance);+ queueZoom(centerX, centerY, pinchDistance / distance);pinchDistance = distance;host.onPinch?.();}@@ -113,6 +151,11 @@ export const attachWheelZoom = (element: HTMLElement, host: ZoomHost): (() => voelement.addEventListener('touchcancel', handleTouchEnd, { capture: true, passive: true });return () => {+ if (frame !== null) {+ cancelAnimationFrame(frame);+ frame = null;+ }+element.removeEventListener('wheel', handleWheel);element.removeEventListener('touchstart', handleTouchStart, { capture: true });element.removeEventListener('touchmove', handleTouchMove, { capture: true });diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.tsindex 3e238c80ad..cd0a7f509b 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts@@ -32,7 +32,7 @@ import {} from './imageMapStore';import {ALL_POINTS_TRACE,- buildAllPointsTrace,+ buildAllPointsTraces,buildCurrentImageTrace,buildMapLayout,CURRENT_IMAGE_TRACE,@@ -607,28 +607,124 @@ describe('cluster palette', () => {});});+/** Cluster and kind vary on different cycles, so neither can stand in for the other. */+const manyPoints = (): ImageMapPoint[] =>+ Array.from({ length: 500 }, (_, index) => {+ const kind = index % 11 === 0 ? ('video' as const) : ('image' as const);+ const name = `${index}.${kind === 'video' ? 'mp4' : 'png'}`;++ return {+ cluster: index % 7 === 0 ? -1 : index % 37,+ item: { kind, name },+ key: `${kind}:${name}` as ImageMapPoint['key'],+ x: index,+ y: -index,+ };+ });+describe('trace builders', () => {const points: ImageMapPoint[] = [{ cluster: 0, item: { kind: 'image', name: 'a.png' }, key: 'image:a.png', x: 1, y: 2 },{ cluster: -1, item: { kind: 'video', name: 'clip.mp4' }, key: 'video:clip.mp4', x: 3, y: 4 },];- it('builds the all-points scattergl trace with item keys as customdata', () => {- const trace = buildAllPointsTrace(points);+ it('splits the base points into one scattergl trace per appearance', () => {+ const traces = buildAllPointsTraces(points);++ // Every marker property is scalar. Per-point arrays are what plotly+ // reprocesses on each relayout, and a zoom is a relayout per frame.+ for (const trace of traces) {+ expect(trace.type).toBe('scattergl');+ expect(trace.name).toBe(ALL_POINTS_TRACE);+ expect(typeof trace.marker.color).toBe('string');+ expect(typeof trace.marker.opacity).toBe('number');+ expect(typeof trace.marker.symbol).toBe('string');+ }++ const clustered = traces.find((trace) => trace.marker.color === getClusterColor(0));+ const noise = traces.find((trace) => trace.marker.color === getClusterColor(-1));- expect(trace.type).toBe('scattergl');- expect(trace.name).toBe(ALL_POINTS_TRACE);- expect(trace.x).toEqual([1, 3]);- expect(trace.y).toEqual([2, 4]);+ expect(clustered?.x).toEqual([1]);+ expect(clustered?.y).toEqual([2]);// Keys, not bare names: a click has to know which namespace to resolve in.- expect(trace.customdata).toEqual(['image:a.png', 'video:clip.mp4']);+ expect(clustered?.customdata).toEqual(['image:a.png']);// Kind gets the one channel colour and size do not already carry, so a// clip is findable on the map without hovering every point.- expect(trace.marker.symbol).toEqual(['circle', 'diamond']);- expect((trace.marker.color as string[])[0]).toBe(getClusterColor(0));+ expect(clustered?.marker.symbol).toBe('circle');+ expect(noise?.marker.symbol).toBe('diamond');+ expect(noise?.customdata).toEqual(['video:clip.mp4']);// Noise points are dimmed relative to clustered points.- const opacities = trace.marker.opacity as number[];- expect(opacities[1]).toBeLessThan(opacities[0]);+ expect(noise?.marker.opacity as number).toBeLessThan(clustered?.marker.opacity as number);+ // And dimmed points are drawn first, so they sit under the clustered ones.+ expect(traces.indexOf(noise!)).toBeLessThan(traces.indexOf(clustered!));+ });++ it('gives every point the appearance it would have had, and keeps it exactly once', () => {+ // The split is the only thing standing between a point and the map. A+ // bucketing slip drops or duplicates part of the gallery; a subtler one+ // keys on the wrong field and every clustered point comes out the same+ // colour, or a video comes out a circle. Cluster and kind vary+ // independently here so that keying on either alone fails.+ const many = manyPoints();+ const byKey = new Map(many.map((point) => [point.key, point]));+ const traces = buildAllPointsTraces(many);+ const seen: string[] = [];++ for (const trace of traces) {+ for (const [index, key] of trace.customdata.entries()) {+ const point = byKey.get(key as ImageMapPoint['key']);++ expect(point).toBeDefined();+ seen.push(key);+ // Index alignment: plotly reads x, y and customdata positionally, so+ // a shuffle inside one trace plots a point at another's coordinates+ // and resolves a click to the wrong image.+ expect(trace.x[index]).toBe(point?.x);+ expect(trace.y[index]).toBe(point?.y);+ // And the scalar appearance has to be the one this point earned.+ expect(trace.marker.color).toBe(getClusterColor(point!.cluster));+ expect(trace.marker.opacity).toBe(point!.cluster < 0 ? 0.25 : 0.85);+ expect(trace.marker.symbol).toBe(point!.item.kind === 'video' ? 'diamond' : 'circle');+ }+ }++ expect(seen).toHaveLength(many.length);+ expect(new Set(seen).size).toBe(many.length);+ // Bounded by the palette, not by the gallery: 15 colours + noise, each+ // able to carry images and videos.+ expect(traces.length).toBeLessThanOrEqual((CLUSTER_PALETTE.length + 1) * 2);+ });++ it('draws a point whose cluster is not an integer rather than losing it', () => {+ // The bucket slot is an array index. A fractional label would collide+ // with another cluster's slot and steal its colour; a non-finite one+ // would write a string property the emit loop never visits, and those+ // points would vanish from the map with nothing to show for it. The+ // endpoint declares `int` and the client does not validate, so only this+ // stands between a contract slip and missing images.+ const odd: ImageMapPoint[] = [2.5, Number.NaN, Infinity, -0.5].map((cluster, index) => ({+ cluster,+ item: { kind: 'image', name: `${index}.png` },+ key: `image:${index}.png`,+ x: index,+ y: index,+ }));++ const traces = buildAllPointsTraces(odd);++ expect(traces.flatMap((trace) => trace.customdata)).toHaveLength(odd.length);+ // Treated as unclustered: nothing sensible names their cluster.+ for (const trace of traces) {+ expect(trace.marker.color).toBe(getClusterColor(-1));+ expect(trace.marker.opacity).toBe(0.25);+ }+ });++ it('yields no base traces for an empty map', () => {+ // The view never mounts the plot for an empty point set, and plotly+ // handles the trace count changing in either direction, so there is+ // nothing to stand in for.+ expect(buildAllPointsTraces([])).toEqual([]);});it('builds an empty gold current-image trace that stays last in z-order', () => {diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.tsindex fcfa43ba57..c10beecb32 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts@@ -4,7 +4,7 @@ import type { Layout } from 'plotly.js';import type { ImageMapPoint } from './api';import type { AxisRanges } from './imageMapViewport';-import { getClusterColor } from './clusterPalette';+import { CLUSTER_PALETTE, getClusterColor } from './clusterPalette';/*** Pure trace/layout builders for the map, kept apart from the plotly host so@@ -39,31 +39,108 @@ export interface ScatterTrace {};}-/** Marker shapes per media kind; see `buildAllPointsTrace`. */+/** Marker shapes per media kind; see `buildAllPointsTraces`. */const IMAGE_SYMBOL = 'circle';const VIDEO_SYMBOL = 'diamond';-export const buildAllPointsTrace = (points: ImageMapPoint[]): ScatterTrace => ({- // The gallery's item key, so a click or hover resolves back to the kind the- // point stands for — plotly carries strings, and a bare name would not say- // whether it names an image or a video.- customdata: points.map((point) => point.key),- hoverinfo: 'none',- marker: {- color: points.map((point) => getClusterColor(point.cluster)),- opacity: points.map((point) => (point.cluster < 0 ? NOISE_OPACITY : POINT_OPACITY)),- size: 5,- // Videos are diamonds. Color already carries the cluster, so kind needs- // the one remaining channel: without it a clip is pixel-identical to an- // image and can only be found by hovering points one at a time.- symbol: points.map((point) => (point.item.kind === 'video' ? VIDEO_SYMBOL : IMAGE_SYMBOL)),- },- mode: 'markers',- name: ALL_POINTS_TRACE,- type: 'scattergl',- x: points.map((point) => point.x),- y: points.map((point) => point.y),-});+/**+ * The base points, split into one trace per distinct appearance.+ *+ * A single trace carrying per-point `color`/`opacity`/`symbol` arrays is what+ * made zooming a large map slow: plotly reprocesses every one of those arrays+ * on each relayout, and a zoom is a relayout per frame. Splitting the points+ * so every marker property is scalar cuts a zoom step by roughly 14x at 170k+ * points and 20x at 300k, and builds the scene about twice as fast while+ * retaining half the heap.+ *+ * Each point keeps the appearance it had, but the ORDER changes: points now+ * paint grouped rather than in gallery order, so where two points overlap the+ * one on top can differ. Markers are translucent, so that is visible. Noise+ * is emitted first, which is the deliberate part — dimmed points belong under+ * the clustered ones. Within a group the original point order is preserved.+ *+ * The cost is hover. Plotly builds a kd-tree for hit-testing only on traces+ * of 100k points or more, so one 170k trace had one and none of these do:+ * hover goes from ~1.5ms to ~7ms at 170k and ~11ms at 300k, throttled to+ * 20/s. Zoom was 180ms+ at those sizes, so this trades a cost nobody could+ * work through for one that is merely warm.+ *+ * At most (palette + noise) x (image, video) groups exist, so the trace count+ * is bounded by the palette rather than by the gallery. Below roughly 5k+ * points the per-trace overhead makes this a small net loss (~2.5ms a frame+ * at 200 points) — accepted rather than switched on a threshold, because+ * making the draw order depend on gallery size is a worse bargain than the+ * milliseconds.+ */+export const buildAllPointsTraces = (points: ImageMapPoint[]): ScatterTrace[] => {+ // Bucketed by a small integer rather than a composed string key: this runs+ // over every point on each data change, and building a key per point is the+ // one part of it that would allocate.+ const buckets: ImageMapPoint[][] = [];++ for (const point of points) {+ const cluster = clusterOf(point);+ const colorSlot = cluster < 0 ? CLUSTER_PALETTE.length : cluster % CLUSTER_PALETTE.length;+ const slot = colorSlot * 2 + (point.item.kind === 'video' ? 1 : 0);++ (buckets[slot] ??= []).push(point);+ }++ const traces: ScatterTrace[] = [];+ // Noise occupies the slots just past the palette, and emitting it first is+ // what puts the dimmed points underneath.+ const order = [...buckets.keys()].sort(+ (left, right) => Number(right >= CLUSTER_PALETTE.length * 2) - Number(left >= CLUSTER_PALETTE.length * 2)+ );++ for (const slot of order) {+ const group = buckets[slot];++ if (group === undefined || group.length === 0) {+ continue;+ }++ const first = group[0]!;+ const cluster = clusterOf(first);++ traces.push({+ // The gallery's item key, so a click or hover resolves back to the kind+ // the point stands for — plotly carries strings, and a bare name would+ // not say whether it names an image or a video.+ customdata: group.map((point) => point.key),+ hoverinfo: 'none',+ marker: {+ color: getClusterColor(cluster),+ opacity: cluster < 0 ? NOISE_OPACITY : POINT_OPACITY,+ size: 5,+ // Videos are diamonds. Color already carries the cluster, so kind+ // needs the one remaining channel: without it a clip is+ // pixel-identical to an image and can only be found by hovering+ // points one at a time.+ symbol: first.item.kind === 'video' ? VIDEO_SYMBOL : IMAGE_SYMBOL,+ },+ mode: 'markers',+ name: ALL_POINTS_TRACE,+ type: 'scattergl',+ x: group.map((point) => point.x),+ y: group.map((point) => point.y),+ });+ }++ return traces;+};++/**+ * The point's DBSCAN label, or noise for anything that cannot be one.+ *+ * The bucket slot below is an array index, so a non-integer label would write+ * a string property that `buckets.keys()` never yields — those points would+ * silently never reach a trace, and a fractional one would collide with+ * another cluster's slot and take its colour. The endpoint declares `int` and+ * the client does not validate the body, so this is the guard that keeps a+ * contract slip from quietly deleting part of the map.+ */+const clusterOf = (point: ImageMapPoint): number => (Number.isInteger(point.cluster) ? point.cluster : -1);/*** The gallery's multi-selection (e.g. a cluster click), drawn larger with adiff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex 505ffd3de4..aaaa30f794 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -17,7 +17,7 @@ import { attachWheelZoom } from '@workbench/image-map/attachWheelZoom';import { collectClusterSelection } from '@workbench/image-map/clusterSelection';import { imageMapStore } from '@workbench/image-map/imageMapStore';import {- buildAllPointsTrace,+ buildAllPointsTraces,buildClusterAnnotations,buildCurrentImageTrace,buildHighlightedPointsTrace,@@ -253,10 +253,16 @@ const ImageMapPlot = ({return;}- // Overlay traces (highlight, marker) start empty; the overlay effects- // below restyle them, so a selection change never rebuilds the scene.+ // The base points come back as several traces, one per appearance; the+ // overlays are found by name, so their position among them does not+ // matter. That lookup is load-bearing now in a way it was not when the+ // base was a single trace at a fixed index: it is safe because+ // `Plotly.react` swaps `gd.data` synchronously, so the overlay effects+ // that run straight after this one already see the new indices. Overlay traces (highlight, marker) start empty; the overlay+ // effects below restyle them, so a selection change never rebuilds the+ // scene.const traces = [- buildAllPointsTrace(points),+ ...buildAllPointsTraces(points),buildHighlightedPointsTrace(points, new Set()),buildCurrentImageTrace(),];