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.

refactor(webv2): record workflow seed starts instead of expanded batch data

Josh Corbettef3df0403242
diff --git a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
index 1e9bbe6b52..7d95ae4c3c 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/promptBatch.ts
@@ -51,21 +51,74 @@ export interface GeneratePromptBatchDatum extends QueueBatchDatum {
field_name: 'value';
}
-/** Structural check for batch data read back from a persisted snapshot. */
-export const isQueueBatchData = (value: unknown): value is QueueBatchDatum[][] =>
- Array.isArray(value) &&
- value.every(
- (group) =>
- Array.isArray(group) &&
- group.every(
- (datum) =>
- typeof datum === 'object' &&
- datum !== null &&
- typeof (datum as QueueBatchDatum).field_name === 'string' &&
- typeof (datum as QueueBatchDatum).node_path === 'string' &&
- Array.isArray((datum as QueueBatchDatum).items)
- )
+/**
+ * One workflow seed input that varies between runs: its first seed and the
+ * direction of the rest. Compact on purpose — the snapshot records the start
+ * the plan drew, and the runs expand from it deterministically at send time.
+ */
+export interface QueueWorkflowSeed {
+ fieldName: string;
+ nodeId: string;
+ seed: number;
+ seedStep: -1 | 1;
+}
+
+export const isQueueWorkflowSeed = (value: unknown): value is QueueWorkflowSeed => {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+
+ const seed = value as Partial<QueueWorkflowSeed>;
+
+ return (
+ typeof seed.fieldName === 'string' &&
+ seed.fieldName.length > 0 &&
+ typeof seed.nodeId === 'string' &&
+ seed.nodeId.length > 0 &&
+ typeof seed.seed === 'number' &&
+ Number.isInteger(seed.seed) &&
+ seed.seed >= 0 &&
+ seed.seed <= SEED_MAX &&
+ (seed.seedStep === -1 || seed.seedStep === 1)
);
+};
+
+export interface WorkflowSeedBatchPlan {
+ /** One zipped group over every varying input, or undefined while every seed holds. */
+ data?: QueueBatchDatum[][];
+ runs: number;
+}
+
+/**
+ * A workflow batch repeats one graph unless a seed input varies, in which case
+ * every varying input joins one zipped group so `batchCount` runs stay
+ * `batchCount` runs. A single run needs no data: the plan already wrote each
+ * start seed into the graph.
+ */
+export const buildWorkflowSeedBatchPlan = ({
+ batchCount,
+ seeds,
+}: {
+ batchCount: number;
+ seeds: readonly QueueWorkflowSeed[] | undefined;
+}): WorkflowSeedBatchPlan => {
+ const runs = sanitizeBatchCount(batchCount);
+
+ if (!seeds || seeds.length === 0 || runs === 1) {
+ return { runs };
+ }
+
+ return {
+ data: [
+ seeds.map((seed) => ({
+ field_name: seed.fieldName,
+ items: generateSeedSequence(seed.seed, runs, seed.seedStep),
+ node_path: seed.nodeId,
+ })),
+ ],
+ runs: 1,
+ };
+};
export interface GeneratePromptBatchPlanInput {
batchCount: number;
diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.ts
index 6261555152..5f0b68c139 100644
--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts
+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts
@@ -1,6 +1,6 @@
-import type { QueueBatchDatum, QueuePromptSeedBehaviour, QueueSeedStep } from '@features/queue/core/promptBatch';
+import type { QueuePromptSeedBehaviour, QueueSeedStep, QueueWorkflowSeed } from '@features/queue/core/promptBatch';
-export type { QueueBatchDatum, QueueSeedStep };
+export type { QueueSeedStep, QueueWorkflowSeed };
export interface QueueBackendInvocation {
id: string;
@@ -43,8 +43,8 @@ interface QueueEnqueueRequestBase {
}
export interface QueueEnqueueWorkflowRequest extends QueueEnqueueRequestBase {
- /** Zipped batch groups over graph fields; the backend takes their product `batchCount` times. */
- data?: QueueBatchDatum[][];
+ /** The seed inputs that vary between the `batchCount` runs; the graph carries each one's first seed. */
+ seeds?: QueueWorkflowSeed[];
}
export interface QueueEnqueueGenerateRequest extends QueueEnqueueRequestBase {
@@ -73,12 +73,11 @@ export interface QueueEnqueueResult {
/** Immutable source-compiled payload. Queue submits it without reading source widget state. */
export type QueueCompiledSubmission =
| {
- /** Backend `runs`; with `data` present the runs are enumerated there and this is 1. */
batchCount: number;
- /** The seed inputs that vary between runs, zipped so every run gets one seed per field. */
- data?: QueueBatchDatum[][];
graph: QueueBackendGraph;
kind: 'workflow';
+ /** The seed inputs that vary between runs, expanded into one zipped batch group at send time. */
+ seeds?: QueueWorkflowSeed[];
/**
* The library record this run's workflow was loaded from, when the project
* graph is bound to one. Stamped at compile time so a completed run can be
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
index b5f4422937..fe0ab0c7d2 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.test.ts
@@ -278,23 +278,33 @@ describe('enqueueWorkflow', () => {
expect(getSubmittedBody().batch.batch_id).toBeUndefined();
});
- it('sends zipped seed batch data alongside the run count', async () => {
+ it('expands recorded seeds into one zipped group and never redraws them', async () => {
const { enqueueWorkflow } = await import('./submissionApi');
- const data = [
- [
- { field_name: 'seed', items: [1, 2, 3], node_path: 'noise-a' },
- { field_name: 'seed', items: [9, 8, 7], node_path: 'noise-b' },
- ],
+ const seeds = [
+ { fieldName: 'seed', nodeId: 'noise-a', seed: 1, seedStep: 1 as const },
+ { fieldName: 'seed', nodeId: 'noise-b', seed: 4_294_967_295, seedStep: -1 as const },
];
- await enqueueWorkflow(createWorkflowRequest({ batchCount: 1, data }));
+ await enqueueWorkflow(createWorkflowRequest({ batchCount: 3, seeds }));
- expect(getSubmittedBody().batch).toMatchObject({ data, runs: 1 });
+ expect(getSubmittedBody().batch).toMatchObject({
+ data: [
+ [
+ { field_name: 'seed', items: [1, 2, 3], node_path: 'noise-a' },
+ { field_name: 'seed', items: [4_294_967_295, 4_294_967_294, 4_294_967_293], node_path: 'noise-b' },
+ ],
+ ],
+ runs: 1,
+ });
- mocks.apiFetchJson.mockClear();
- await enqueueWorkflow(createWorkflowRequest());
+ // A single run already carries its seed in the graph; a seedless batch repeats the graph.
+ for (const request of [createWorkflowRequest({ batchCount: 1, seeds }), createWorkflowRequest({ batchCount: 2 })]) {
+ mocks.apiFetchJson.mockClear();
+ await enqueueWorkflow(request);
- expect(getSubmittedBody().batch).not.toHaveProperty('data');
+ expect(getSubmittedBody().batch).not.toHaveProperty('data');
+ expect(getSubmittedBody().batch.runs).toBe(request.batchCount);
+ }
});
it('does not cap workflow runs', async () => {
diff --git a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
index ffee606b7b..c962227745 100644
--- a/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
+++ b/invokeai/frontend/webv2/src/features/queue/data/submissionApi.ts
@@ -7,7 +7,11 @@ import type {
QueueResultVideoOptions,
} from '@features/queue/core/types';
-import { buildGeneratePromptBatchPlan, sanitizeBatchCount } from '@features/queue/core/promptBatch';
+import {
+ buildGeneratePromptBatchPlan,
+ buildWorkflowSeedBatchPlan,
+ sanitizeBatchCount,
+} from '@features/queue/core/promptBatch';
import { mapWithConcurrency } from '@platform/core/concurrency';
import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';
import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';
@@ -102,16 +106,17 @@ export const enqueueGenerate = async (request: QueueEnqueueGenerateRequest): Pro
};
export const enqueueWorkflow = async (request: QueueEnqueueWorkflowRequest): Promise<QueueEnqueueResult> => {
+ const plan = buildWorkflowSeedBatchPlan({ batchCount: request.batchCount, seeds: request.seeds });
const result = await apiFetchJson<unknown>('/api/v1/queue/default/enqueue_batch', {
body: JSON.stringify({
batch: {
- ...(request.data ? { data: request.data } : {}),
+ ...(plan.data ? { data: plan.data } : {}),
destination: request.destination,
graph: request.graph,
idempotency_key: getQueueIdempotencyKey(request.projectId, request.sourceQueueItemId),
project_id: request.projectId,
origin: buildQueueItemOrigin(request.sourceQueueItemId, request.projectId),
- runs: sanitizeBatchCount(request.batchCount),
+ runs: plan.runs,
},
prepend: false,
}),
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
index d54a9810d1..88bee15191 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts
@@ -148,31 +148,37 @@ describe('queue runtime', () => {
).not.toHaveProperty('shouldRandomizeSeed');
});
- it('replays workflow batch data as recorded and rejects a malformed record', () => {
- const asWorkflow = (data: unknown) => {
+ it('replays workflow seeds as recorded and rejects records the graph cannot honour', () => {
+ const asWorkflow = (seeds: unknown) => {
const queueItem = createPendingQueueItem();
queueItem.snapshot.backendSubmission = {
- batchCount: 1,
- graph: { edges: [], id: 'backend-graph', nodes: {} },
+ batchCount: 3,
+ graph: { edges: [], id: 'backend-graph', nodes: { noise: { id: 'noise', seed: 7, type: 'noise' } } },
kind: 'workflow',
- ...(data === undefined ? {} : { data: data as never }),
+ ...(seeds === undefined ? {} : { seeds: seeds as never }),
};
queueItem.snapshot.sourceId = 'workflow';
return queueItem;
};
- const data = [[{ field_name: 'seed', items: [1, 2], node_path: 'noise' }]];
+ const seed = { fieldName: 'seed', nodeId: 'noise', seed: 7, seedStep: 1 };
+ const invalid = { error: 'Queue item has malformed workflow seed metadata.', kind: 'invalid' };
- expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow(data))).toMatchObject({
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([seed]))).toMatchObject({
kind: 'workflow',
- request: { batchCount: 1, data },
+ request: { batchCount: 3, seeds: [seed] },
});
expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow(undefined))).toMatchObject({
kind: 'workflow',
});
- expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([{ items: [1] }]))).toEqual({
- error: 'Queue item has malformed workflow batch data.',
- kind: 'invalid',
- });
+ // Out of range, a step the plan never emits, a node the graph lost, and the same field twice.
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([{ ...seed, seed: -1 }]))).toEqual(invalid);
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([{ ...seed, seedStep: 0 }]))).toEqual(
+ invalid
+ );
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([{ ...seed, nodeId: 'gone' }]))).toEqual(
+ invalid
+ );
+ expect(createQueueItemBackendSubmission({ id: 'project-1' }, asWorkflow([seed, seed]))).toEqual(invalid);
});
it('rejects a generate item that records neither a seed step nor the legacy toggle', () => {
diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.ts
index 9a088e1704..bb9fc376e7 100644
--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts
+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts
@@ -11,9 +11,9 @@ import type { BackendConnectionStatus } from '@platform/transport/types';
import { collectGraphInputMediaNames } from '@features/queue/core/graphInputMedia';
import {
- isQueueBatchData,
isQueuePromptSeedBehaviour,
isQueueSeedStep,
+ isQueueWorkflowSeed,
MAX_QUEUE_BATCH_ITEMS,
} from '@features/queue/core/promptBatch';
import { shouldSubmitPendingQueueItem } from '@features/queue/core/submissionRules';
@@ -137,6 +137,25 @@ const readSubmissionSeedStep = (submission: { seedStep?: unknown; shouldRandomiz
: 0
: null;
+/** Every recorded seed must name a distinct field on a node the graph still has, in the seed range, stepping ±1. */
+const areQueueWorkflowSeedsValid = (seeds: unknown, graph: { nodes?: Record<string, unknown> }): boolean => {
+ if (!Array.isArray(seeds)) {
+ return false;
+ }
+
+ const targets = new Set<string>();
+
+ return seeds.every((seed) => {
+ if (!isQueueWorkflowSeed(seed) || !graph.nodes || !(seed.nodeId in graph.nodes)) {
+ return false;
+ }
+
+ const target = `${seed.nodeId}:${seed.fieldName}`;
+
+ return targets.has(target) ? false : (targets.add(target), true);
+ });
+};
+
export const createQueueItemBackendSubmission = (
project: Pick<QueueHistoryProject, 'id'>,
queueItem: QueueItem
@@ -207,8 +226,8 @@ export const createQueueItemBackendSubmission = (
};
}
- if (submission.data !== undefined && !isQueueBatchData(submission.data)) {
- return { error: 'Queue item has malformed workflow batch data.', kind: 'invalid' };
+ if (submission.seeds !== undefined && !areQueueWorkflowSeedsValid(submission.seeds, submission.graph)) {
+ return { error: 'Queue item has malformed workflow seed metadata.', kind: 'invalid' };
}
// `libraryWorkflowId` is provenance for the completed-run sink, not something
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
index 58d71a6831..16e58b98bb 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.test.ts
@@ -613,12 +613,12 @@ describe('planWorkflowSubmission', () => {
const { doc, ids } = buildSeeded([{ seed: 7 }, { seed: 9, seedMode: 'fixed' }]);
const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 3 });
- expect(plan).toMatchObject({ data: null, generationCount: 3, runs: 3, seedAdvances: [] });
+ expect(plan).toMatchObject({ batchCount: 3, seedAdvances: [], seeds: [] });
expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(7);
expect(plan.graph.backendGraph.nodes[ids[1] as string]?.seed).toBe(9);
});
- it('zips every stepping seed into one group so three runs stay three runs', () => {
+ it('records one start per stepping seed and where each field goes after the batch', () => {
const { doc, ids } = buildSeeded([
{ seed: 42, seedMode: 'increment' },
{ seed: 100, seedMode: 'decrement' },
@@ -626,31 +626,29 @@ describe('planWorkflowSubmission', () => {
]);
const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 3 });
- expect(plan.runs).toBe(1);
- expect(plan.generationCount).toBe(3);
- expect(plan.data).toEqual([
- [
- { field_name: 'seed', items: [42, 43, 44], node_path: ids[0] },
- { field_name: 'seed', items: [100, 99, 98], node_path: ids[1] },
- ],
+ expect(plan.seeds).toEqual([
+ { fieldName: 'seed', nodeId: ids[0], seed: 42, seedStep: 1 },
+ { fieldName: 'seed', nodeId: ids[1], seed: 100, seedStep: -1 },
]);
expect(plan.seedAdvances).toEqual([
{ fieldName: 'seed', fromSeed: 42, nodeId: ids[0], seedMode: 'increment', toSeed: 45 },
{ fieldName: 'seed', fromSeed: 100, nodeId: ids[1], seedMode: 'decrement', toSeed: 97 },
]);
- // The fixed node keeps its constant in the graph; the varying ones keep theirs as the fallback the batch overrides.
+ // Every node carries its first run's seed as a constant; the fixed one stays as authored.
+ expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(42);
expect(plan.graph.backendGraph.nodes[ids[2] as string]?.seed).toBe(5);
+ expect(plan.graph.nodes.find((node) => node.id === ids[1])?.inputs.seed).toBe(100);
});
- it('wraps the sequence over the inclusive seed range', () => {
+ it('wraps the authored seed and the advance over the inclusive seed range', () => {
const { doc } = buildSeeded([{ seed: 1, seedMode: 'decrement' }]);
const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 3 });
- expect(plan.data?.[0]?.[0]?.items).toEqual([1, 0, SEED_MAX]);
+ expect(plan.seeds[0]).toMatchObject({ seed: 1, seedStep: -1 });
expect(plan.seedAdvances[0]?.toSeed).toBe(SEED_MAX - 1);
});
- it('draws a random start per input, runs consecutively from it, and never advances the entered seed', () => {
+ it('draws a random start into the graph and never advances the entered seed', () => {
const { doc, ids } = buildSeeded([
{ seed: 42, seedMode: 'random' },
{ seed: 42, seedMode: 'random' },
@@ -662,14 +660,14 @@ describe('planWorkflowSubmission', () => {
try {
const plan = planWorkflowSubmission(doc, seededTemplates, { batchCount: 2 });
- expect(plan.data).toEqual([
- [
- { field_name: 'seed', items: [start, start + 1], node_path: ids[0] },
- { field_name: 'seed', items: [start, start + 1], node_path: ids[1] },
- ],
+ expect(plan.seeds).toEqual([
+ { fieldName: 'seed', nodeId: ids[0], seed: start, seedStep: 1 },
+ { fieldName: 'seed', nodeId: ids[1], seed: start, seedStep: 1 },
]);
expect(plan.seedAdvances).toEqual([]);
- expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(42);
+ expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(start);
+ // The document keeps the entered seed in reserve.
+ expect(doc.nodes[0]).toMatchObject({ data: { inputs: { seed: { value: 42 } } } });
} finally {
random.mockRestore();
}
@@ -691,13 +689,14 @@ describe('planWorkflowSubmission', () => {
});
const plan = planWorkflowSubmission(connected, seededTemplates, { batchCount: 2 });
- expect(plan).toMatchObject({ data: null, runs: 2, seedAdvances: [] });
+ expect(plan).toMatchObject({ seedAdvances: [], seeds: [] });
+ expect(plan.graph.backendGraph.nodes[ids[0] as string]).not.toHaveProperty('seed');
expect(connected.nodes.find((node) => node.id === ids[0])).toMatchObject({
data: { inputs: { seed: { seedMode: 'increment', value: 42 } } },
});
});
- it('steps an empty seed input from the template default', () => {
+ it('steps an empty seed input from the template default and fills it in afterwards', () => {
const { doc, ids } = buildSeeded([{ seedMode: 'increment' }]);
const emptied = projectGraphReducer(doc, {
fieldName: 'seed',
@@ -707,7 +706,8 @@ describe('planWorkflowSubmission', () => {
});
const plan = planWorkflowSubmission(emptied, seededTemplates, { batchCount: 2 });
- expect(plan.data?.[0]?.[0]?.items).toEqual([0, 1]);
+ expect(plan.seeds).toEqual([{ fieldName: 'seed', nodeId: ids[0], seed: 0, seedStep: 1 }]);
+ expect(plan.graph.backendGraph.nodes[ids[0] as string]?.seed).toBe(0);
// The advance is fenced on the empty value, so the field fills in with the seed after the batch.
expect(plan.seedAdvances).toEqual([{ fieldName: 'seed', nodeId: ids[0], seedMode: 'increment', toSeed: 2 }]);
expect(
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
index b3f66285e9..8620a94391 100644
--- a/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
+++ b/invokeai/frontend/webv2/src/features/workflow/core/buildGraph.ts
@@ -294,73 +294,38 @@ export const isSeedInputField = (template: FieldInputTemplate): boolean =>
export const getWorkflowFieldSeedMode = (instance: Pick<WorkflowFieldInstance, 'seedMode'> | undefined): SeedMode =>
isSeedMode(instance?.seedMode) ? instance.seedMode : 'fixed';
-/**
- * The seeds one varying input contributes to a submission of `runCount` runs,
- * and where its authored seed goes afterwards. Stepping modes count from the
- * authored seed; random draws its start and runs consecutively from it, like
- * Generate's random mode, leaving the authored seed in reserve.
- */
-const getWorkflowSeedFieldSequence = (
- seedMode: Exclude<SeedMode, 'fixed'>,
- authoredSeed: number,
- runCount: number
-): { nextSeed: number | null; seeds: number[] } => {
- const startSeed = seedMode === 'random' ? Math.floor(Math.random() * SEED_MAX) : wrapSeed(authoredSeed);
- const plan = planSeedSubmission({
- batchCount: runCount,
- promptCount: 1,
- seedBehaviour: 'per-iteration',
- seedMode,
- startSeed,
- });
-
- return {
- nextSeed: plan.nextSeed,
- seeds: Array.from({ length: plan.sequenceLength }, (_, index) => wrapSeed(startSeed + plan.step * index)),
- };
-};
-
-/** One value list of a zipped batch group, in the backend's `BatchDatum` shape. */
-export interface WorkflowBatchDatum {
- field_name: string;
- items: number[];
- node_path: string;
+/** One seed input that varies between runs: the seed the first run uses and the direction of the rest. */
+export interface WorkflowSeedAssignment {
+ fieldName: string;
+ nodeId: string;
+ seed: number;
+ seedStep: -1 | 1;
}
-export interface WorkflowSubmissionPlan {
- graph: CompiledWorkflowGraph;
- /** One zipped group over every seed input that varies between runs; null while every seed holds. */
- data: WorkflowBatchDatum[][] | null;
- /** Backend `runs`: the batch count while every seed holds, else 1 with the runs enumerated by `data`. */
- runs: number;
- /** Sessions the submission produces either way. */
- generationCount: number;
- /** Stepping-mode fields to move once the submission is queued. */
+export interface WorkflowSeedPlan {
+ /** Every unconnected seed input in a varying mode, with its first seed; fixed inputs are absent. */
+ seeds: WorkflowSeedAssignment[];
+ /** Stepping-mode fields to move once the submission is reserved. */
seedAdvances: WorkflowSeedFieldAdvance[];
}
-export interface WorkflowSubmissionPlanOptions {
- /** Runs per submission; already sanitized to a positive integer by the caller. */
- batchCount: number;
-}
-
/**
- * Compiles the document and fixes every seed input's values for one submission.
- * Seeds vary per queued run, not per iteration of a loop inside a run, which
- * repeats its run's seed. Every varying input joins one zipped group, so three
- * runs over two stepping seeds stay three runs rather than nine combinations;
- * fixed inputs stay constants in the graph. A random input draws its start here
- * and runs consecutively from it, like Generate's random mode, while the entered
- * seed stays in reserve. Only the stepping modes report an advance.
+ * Decides every seed input's start for a submission of `batchCount` runs. Seeds
+ * vary per queued run, not per iteration of a loop inside a run. A random input
+ * draws its start here and the runs step consecutively from it, like Generate's
+ * random mode, while the entered seed stays in reserve; a stepping input counts
+ * from the authored seed and reports where the field goes afterwards. Expansion
+ * into per-run values happens at send time from these starts, never redrawing.
*/
-export const planWorkflowSubmission = (
+export const planWorkflowSeeds = (
document: ProjectGraphState,
templates: InvocationTemplates,
- { batchCount }: WorkflowSubmissionPlanOptions
-): WorkflowSubmissionPlan => {
- const graph = compileProjectGraph(document, templates);
- const connectedInputs = new Set(graph.edges.map((edge) => `${edge.targetNodeId}:${edge.targetField}`));
- const data: WorkflowBatchDatum[] = [];
+ batchCount: number
+): WorkflowSeedPlan => {
+ const connectedInputs = new Set(
+ getCanonicalWorkflowEdges(document).map((edge) => `${edge.destination.node_id}:${edge.destination.field}`)
+ );
+ const seeds: WorkflowSeedAssignment[] = [];
const seedAdvances: WorkflowSeedFieldAdvance[] = [];
for (const node of getExecutableNodes(document)) {
@@ -388,27 +353,80 @@ export const planWorkflowSubmission = (
: typeof inputTemplate.default === 'number'
? inputTemplate.default
: 0;
- const sequence = getWorkflowSeedFieldSequence(seedMode, authoredSeed, batchCount);
+ const startSeed = seedMode === 'random' ? Math.floor(Math.random() * SEED_MAX) : wrapSeed(authoredSeed);
+ const plan = planSeedSubmission({
+ batchCount,
+ promptCount: 1,
+ seedBehaviour: 'per-iteration',
+ seedMode,
+ startSeed,
+ });
- data.push({ field_name: inputTemplate.name, items: sequence.seeds, node_path: node.id });
+ seeds.push({
+ fieldName: inputTemplate.name,
+ nodeId: node.id,
+ seed: startSeed,
+ seedStep: seedMode === 'decrement' ? -1 : 1,
+ });
- if (sequence.nextSeed !== null) {
+ if (plan.nextSeed !== null) {
seedAdvances.push({
fieldName: inputTemplate.name,
...(typeof instance?.value === 'number' ? { fromSeed: instance.value } : {}),
nodeId: node.id,
seedMode,
- toSeed: sequence.nextSeed,
+ toSeed: plan.nextSeed,
});
}
}
}
+ return { seedAdvances, seeds };
+};
+
+/** Writes each planned first seed into the compiled graph, so a single run needs no batch data. */
+export const applyWorkflowSeeds = (
+ graph: CompiledWorkflowGraph,
+ seeds: readonly WorkflowSeedAssignment[]
+): CompiledWorkflowGraph => {
+ for (const { fieldName, nodeId, seed } of seeds) {
+ const backendNode = graph.backendGraph.nodes[nodeId];
+ const node = graph.nodes.find((candidate) => candidate.id === nodeId);
+
+ if (backendNode) {
+ backendNode[fieldName] = seed;
+ }
+
+ if (node) {
+ node.inputs[fieldName] = seed;
+ }
+ }
+
+ return graph;
+};
+
+export interface WorkflowSubmissionPlan extends WorkflowSeedPlan {
+ /** Runs the submission produces. */
+ batchCount: number;
+ graph: CompiledWorkflowGraph;
+}
+
+export interface WorkflowSubmissionPlanOptions {
+ /** Runs per submission; already sanitized to a positive integer by the caller. */
+ batchCount: number;
+}
+
+/** Compiles the document with every planned first seed in place and reports the seeds that vary. */
+export const planWorkflowSubmission = (
+ document: ProjectGraphState,
+ templates: InvocationTemplates,
+ { batchCount }: WorkflowSubmissionPlanOptions
+): WorkflowSubmissionPlan => {
+ const seedPlan = planWorkflowSeeds(document, templates, batchCount);
+
return {
- data: data.length > 0 ? [data] : null,
- generationCount: batchCount,
- graph,
- runs: data.length > 0 ? 1 : batchCount,
- seedAdvances,
+ ...seedPlan,
+ batchCount,
+ graph: applyWorkflowSeeds(compileProjectGraph(document, templates), seedPlan.seeds),
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index 357b71a19e..10a727971b 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -3372,17 +3372,18 @@ describe('workbenchReducer Phase 5 generation flow', () => {
let state = submitWorkflow(primeWorkflow(42, 'increment'));
expect(readSubmission(state)).toMatchObject({
- batchCount: 1,
- data: [[{ field_name: 'seed', items: [42, 43, 44], node_path: 'noise-1' }]],
+ batchCount: 3,
kind: 'workflow',
+ seeds: [{ fieldName: 'seed', nodeId: 'noise-1', seed: 42, seedStep: 1 }],
});
+ expect(readSubmission(state)).toMatchObject({ graph: { nodes: { 'noise-1': { seed: 42 } } } });
expect(getActiveProject(state).queue.items[0]?.snapshot.presentation.batchCount).toBe(3);
expect(readNodeSeed(state)).toBe(45);
state = submitWorkflow(state);
- expect(readSubmission(state)).toMatchObject({ data: [[{ items: [45, 46, 47] }]] });
- expect(readSubmission(state, 1)).toMatchObject({ data: [[{ items: [42, 43, 44] }]] });
+ expect(readSubmission(state)).toMatchObject({ seeds: [{ seed: 45 }] });
+ expect(readSubmission(state, 1)).toMatchObject({ seeds: [{ seed: 42 }] });
expect(readNodeSeed(state)).toBe(48);
});
@@ -3391,7 +3392,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const submission = readSubmission(state);
expect(submission).toMatchObject({ batchCount: 3, kind: 'workflow' });
- expect(submission).not.toHaveProperty('data');
+ expect(submission).not.toHaveProperty('seeds');
expect(submission?.kind === 'workflow' && submission.graph.nodes['noise-1']?.seed).toBe(42);
expect(readNodeSeed(state)).toBe(42);
});
@@ -3403,7 +3404,10 @@ describe('workbenchReducer Phase 5 generation flow', () => {
const state = submitWorkflow(primeWorkflow(42, 'random', 2));
const start = Math.floor(0.25 * SEED_MAX);
- expect(readSubmission(state)).toMatchObject({ data: [[{ items: [start, start + 1] }]] });
+ expect(readSubmission(state)).toMatchObject({
+ graph: { nodes: { 'noise-1': { seed: start } } },
+ seeds: [{ seed: start, seedStep: 1 }],
+ });
expect(readNodeSeed(state)).toBe(42);
} finally {
random.mockRestore();
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 9861c83132..f93619297c 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -3177,8 +3177,8 @@ const enqueueCompiledSnapshot = (
? { error: `${route.sourceId} queue item is missing a compiled backend graph.`, kind: 'invalid' }
: route.sourceId === 'workflow'
? {
- batchCount: compiled.workflow?.runs ?? sanitizeBatchCount(widgetStates.generate?.values.batchCount),
- ...(compiled.workflow?.data ? { data: compiled.workflow.data } : {}),
+ batchCount: compiled.workflow?.batchCount ?? sanitizeBatchCount(widgetStates.generate?.values.batchCount),
+ ...(compiled.workflow?.seeds.length ? { seeds: compiled.workflow.seeds } : {}),
graph: backendGraph,
kind: 'workflow',
// Provenance for the completed-run capture: a run submitted from a
@@ -3257,9 +3257,7 @@ const enqueueCompiledSnapshot = (
batchCount:
backendSubmission.kind === 'invalid'
? 1
- : compiled.workflow
- ? compiled.workflow.generationCount
- : backendSubmission.batchCount * (expandedPositivePrompts?.length ?? 1),
+ : backendSubmission.batchCount * (expandedPositivePrompts?.length ?? 1),
height: presentationDimensions.height,
// The merged prompt, so the queue row reads the same before and after the
// backend session arrives with its own (already merged) field values.