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.

perf(webv2): sweep the highlight annotations in one pass

joshistoasta7458cb696c7
diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
index 639bf3dd86..11d4bc726c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/dynamicPromptSyntax.ts
@@ -239,11 +239,14 @@ export const scanDynamicPromptSyntax = (
}
const wildcardPattern = new RegExp(WILDCARD_REFERENCE_RE, 'g');
+ // Concatenated once. Built inside the loop, this allocated a fresh array of
+ // every variable and comment in the prompt for every wildcard reference in it.
+ const enclosingRanges = [...variableRanges, ...commentRanges];
for (let match = wildcardPattern.exec(prompt); match; match = wildcardPattern.exec(prompt)) {
const wildcardRange = { end: match.index + match[0].length, start: match.index };
- if (![...variableRanges, ...commentRanges].some((outer) => covers(outer, wildcardRange))) {
+ if (!enclosingRanges.some((outer) => covers(outer, wildcardRange))) {
// An unresolvable wildcard survives expansion as its own literal text, so it earns the
// same treatment as an unbalanced brace rather than looking like ordinary recognised
// syntax. `matchesKnownWildcard` resolves globs, which is why a valid `__artists/*__`
diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts
index ed630e03dd..c4e32c082e 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.test.ts
@@ -124,3 +124,28 @@ describe('prompt highlight segments', () => {
});
});
});
+
+// The annotation lookup used to filter and sort every annotation for every
+// token. Dynamic prompts made that bite: a variant-heavy prompt now carries an
+// annotation per brace, separator, weight, sampler, variable and wildcard, so
+// the annotation count became proportional to the token count. This ran to
+// 469ms on the prompt below, synchronously inside a render, on every keystroke.
+describe('buildPromptHighlightSegments on a large prompt', () => {
+ // eslint-disable-next-line no-template-curly-in-string -- `${v=1}` is dynamic-prompts syntax, not interpolation
+ const prompt = '{a|b|c} __colours__ ${v=1} '.repeat(700);
+ const options = { dynamicPrompts: true, knownWildcards: new Set(['colours']) };
+
+ it('covers the whole prompt exactly once', () => {
+ const segments = buildPromptHighlightSegments(prompt, options);
+
+ expect(segments.map((segment) => segment.text).join('')).toBe(prompt);
+ });
+
+ it('stays well inside a frame', () => {
+ const started = performance.now();
+
+ buildPromptHighlightSegments(prompt, options);
+
+ expect(performance.now() - started).toBeLessThan(150);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts
index b63882719e..54151e7030 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/prompt/highlight.ts
@@ -112,13 +112,72 @@ const tokenKind = (token: PromptToken): PromptHighlightKind => {
const covers = (outer: PromptRange, inner: PromptRange): boolean =>
outer.start <= inner.start && outer.end >= inner.end;
-const getBestAnnotation = (
- annotations: HighlightAnnotation[],
- tokenRange: PromptRange
-): HighlightAnnotation | undefined =>
- annotations
- .filter((annotation) => covers(annotation.range, tokenRange))
- .sort((left, right) => right.priority - left.priority)[0];
+/**
+ * Walks the tokens and the annotations together, keeping only the annotations
+ * that could still cover the token in hand.
+ *
+ * This replaced a `filter().sort()` over every annotation for every token. That
+ * is quadratic, and dynamic-prompt highlighting made it bite: a prompt full of
+ * `{a|b|c}` now produces an annotation per brace, separator, weight, range,
+ * sampler, variable, operator, comment and wildcard, so the annotation count
+ * grew to be proportional to the token count. At the 20 000-character ceiling
+ * the highlighter allows, that was tens of milliseconds of blocked main thread
+ * on every keystroke.
+ *
+ * Both inputs are in document order, and an annotation that ends before the
+ * current token cannot reach any later one either, so it is dropped for good.
+ * What is left is the nesting depth at that point, which is small.
+ */
+const forEachTokenAnnotation = (
+ tokens: readonly PromptToken[],
+ annotations: readonly HighlightAnnotation[],
+ visit: (token: PromptToken, annotation: HighlightAnnotation | undefined) => void
+): void => {
+ // Ties are broken by the order the annotations were collected in, which the
+ // stable sort this replaced preserved by accident and callers may rely on.
+ const ordered = annotations
+ .map((annotation, index) => ({ annotation, index }))
+ .sort((left, right) => left.annotation.range.start - right.annotation.range.start || left.index - right.index);
+ const active: { annotation: HighlightAnnotation; index: number }[] = [];
+ let next = 0;
+
+ for (const token of tokens) {
+ while (next < ordered.length && (ordered[next]?.annotation.range.start ?? Infinity) <= token.range.start) {
+ const entry = ordered[next];
+
+ if (entry) {
+ active.push(entry);
+ }
+
+ next++;
+ }
+
+ let kept = 0;
+
+ for (const entry of active) {
+ if (entry.annotation.range.end >= token.range.end) {
+ active[kept] = entry;
+ kept++;
+ }
+ }
+
+ active.length = kept;
+
+ let best: { annotation: HighlightAnnotation; index: number } | undefined;
+
+ for (const entry of active) {
+ if (!covers(entry.annotation.range, token.range)) {
+ continue;
+ }
+
+ if (!best || entry.annotation.priority > best.annotation.priority) {
+ best = entry;
+ }
+ }
+
+ visit(token, best?.annotation);
+ }
+};
const addPromptFunctionAnnotations = (
prompt: string,
@@ -233,8 +292,7 @@ export const buildPromptHighlightSegments = (
];
const segments: PromptHighlightSegment[] = [];
- for (const token of tokens) {
- const annotation = getBestAnnotation(annotations, token.range);
+ forEachTokenAnnotation(tokens, annotations, (token, annotation) => {
const baseKind = tokenKind(token);
const kind = annotation && annotation.priority > BASE_PRIORITY[baseKind] ? annotation.kind : baseKind;
@@ -243,7 +301,7 @@ export const buildPromptHighlightSegments = (
range: { ...token.range },
text: prompt.slice(token.range.start, token.range.end),
});
- }
+ });
return segments;
} catch {