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.

fix(ltx2): cap auto duration in frames at the run's own rate

Lincoln Steinee0d3d872b47
diff --git a/docs/src/content/docs/Users Guide/05.Video Generation/ltx-2.mdx b/docs/src/content/docs/Users Guide/05.Video Generation/ltx-2.mdx
index 35c823185a..eca75434f3 100644
--- a/docs/src/content/docs/Users Guide/05.Video Generation/ltx-2.mdx
+++ b/docs/src/content/docs/Users Guide/05.Video Generation/ltx-2.mdx
@@ -85,7 +85,7 @@ you wish.
LTX-2.5 ships with a small **duration head** that reads your prompt, as the model will see it, and predicts how long the shot it describes should run. With a duration head in the **Duration head** slot of **Model components**, an **Auto duration** switch appears above Frames:
* With it on, the head chooses the clip's length, and **Frames becomes Max frames** — the longest clip it may choose. That number still sizes the run's memory, so it stays editable, and its help text shows the range in seconds. Raise it to allow longer shots.
-* The head chooses between one second (or the shortest clip LTX-2 makes) and Max frames, at the panel's FPS, and lands on the 8·n + 1 frame grid. If Max frames is too short to leave it a choice, the clip simply runs at that length.
+* The head chooses between one second (or the shortest clip LTX-2 makes) and Max frames, at the clip's frame rate (the panel's FPS, or the source's for an extension), and lands on the 8·n + 1 frame grid. If Max frames is too short to leave it a choice, the clip simply runs at that length.
* For an [extension](#extending-with-ltx-2) the prompt describes the continuation, so the head chooses the length of the new material, at the source clip's frame rate, and the Context Frames are added in front of it. Max frames still counts the whole generated clip, context included.
* It is off for audio-to-video and video-to-audio, where the conditioning clip decides the length.
* The length that ran is what the video records, so recalling it reproduces that exact clip; recall turns Auto duration off for that reason.
@@ -96,7 +96,7 @@ The duration head is a separate, optional 3.6 MB install (**LTX-2.5 Duration Hea
LTX-2 continues a clip from its **closing frames and closing sound**, not from a single still. The final *Context Frames* of the trimmed source (default **17**, about 0.7 s at 24 fps) are held fixed at the start of the new clip, picture and audio together, so the model sees the motion and sound it is continuing. The same span is then cross-faded to join the new clip to the source, so the join blends two copies of the same moment rather than two different ones.
-Context comes out of the frame budget: the extension adds **Frames − Context Frames** new frames, and the Context Frames help text shows that number. Trade-offs when choosing it:
+Context comes out of the frame budget: the extension adds **Frames − Context Frames** new frames, and the Context Frames help text shows that number. Under [Auto duration](#auto-duration) that is the most it can add; the head may choose fewer. Trade-offs when choosing it:
* **Longer context carries more of the source.** 17 frames is enough for motion and the *tone* of a sound, but only about a syllable of it: extending a song at 17 tends to flatten the continuation into a sustained note. Raising context to 33–49 restores rhythm and cadence.
* **Raise Frames with it.** At 121 frames, context 17 adds 104 new frames; context 49 adds only 72.
diff --git a/invokeai/app/invocations/ltx2/ltx2_duration.py b/invokeai/app/invocations/ltx2/ltx2_duration.py
index 2cf10e0b80..7fb9d3d24b 100644
--- a/invokeai/app/invocations/ltx2/ltx2_duration.py
+++ b/invokeai/app/invocations/ltx2/ltx2_duration.py
@@ -12,7 +12,12 @@ from invokeai.app.invocations.baseinvocation import (
from invokeai.app.invocations.fields import Input, InputField, LTX2ConditioningField, OutputField
from invokeai.app.invocations.model import ModelIdentifierField
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.ltx2.constants import LTX2_DEFAULT_FPS, LTX2_FRAME_MODULUS, LTX2_TEMPORAL_COMPRESSION
+from invokeai.backend.ltx2.constants import (
+ LTX2_DEFAULT_FPS,
+ LTX2_FRAME_MODULUS,
+ LTX2_NUM_FRAMES_MAX,
+ LTX2_TEMPORAL_COMPRESSION,
+)
from invokeai.backend.ltx2.packing import snap_num_frames_down
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
@@ -49,7 +54,9 @@ class LTX2DurationInvocation(BaseInvocation):
The duration head reads the same connector outputs the transformer's prompt cross-attention
consumes, so it judges the prompt the model will actually see rather than its raw text. The
prediction is clamped to `min_seconds`/`max_seconds` and then snapped down onto the VAE's
- causal temporal grid (`8k + 1`), which is the only frame count a generation can run at.
+ causal temporal grid (`8k + 1`), which is the only frame count a generation can run at. The
+ total is then capped at `max_num_frames` (by default LTX-2's longest clip), which can be
+ shorter than `max_seconds` at a high frame rate.
For an extension, the prompt describes the continuation rather than the frames it opens with,
so the prediction sizes the new material and `context_frames` is added in front of it.
@@ -93,11 +100,12 @@ class LTX2DurationInvocation(BaseInvocation):
description="Source frames the run opens with, as an extension's `context_frames`. The prediction "
"covers what follows them, so they are added to it. 0 when nothing is held.",
)
- max_num_frames: int | None = InputField(
- default=None,
+ max_num_frames: int = InputField(
+ default=LTX2_NUM_FRAMES_MAX,
ge=1,
- description="Longest total frame count the run was sized for. The result never exceeds it, whatever "
- "frame rate the seconds bounds turn out to be read at.",
+ le=LTX2_NUM_FRAMES_MAX,
+ description="Longest total frame count, context included, the run was sized for. The result is "
+ "capped at it, so it holds at whatever `fps` the run turns out to have.",
)
@torch.no_grad()
@@ -113,8 +121,8 @@ class LTX2DurationInvocation(BaseInvocation):
# would put the sum below off the grid.
if self.context_frames and (self.context_frames - 1) % LTX2_FRAME_MODULUS:
raise ValueError(f"context_frames ({self.context_frames}) must be 0 or on the 8k+1 grid.")
- ceiling = snap_num_frames_down(self.max_num_frames) if self.max_num_frames is not None else None
- if ceiling is not None and self.context_frames and ceiling <= self.context_frames:
+ ceiling = snap_num_frames_down(self.max_num_frames)
+ if self.context_frames and ceiling <= self.context_frames:
raise ValueError(
f"max_num_frames ({self.max_num_frames}) leaves no room after {self.context_frames} context frames."
)
@@ -150,8 +158,10 @@ class LTX2DurationInvocation(BaseInvocation):
# that is itself 8k + 1, so the total stays on the grid. At least one group, or the
# continuation would be all replay.
num_frames = self.context_frames + max(num_frames - 1, LTX2_FRAME_MODULUS)
- if ceiling is not None:
- num_frames = min(num_frames, ceiling)
+ # The ceiling is in frames because only this node knows the rate the run plays at: seconds
+ # sized by a caller at a guessed rate would stop short of it or overrun it. Both sides are on
+ # the grid, so capping here is exactly the longest prediction that fits.
+ num_frames = min(num_frames, ceiling)
context.logger.info(
f"LTX-2 duration: predicted {seconds:.2f}s -> {num_frames} frames at {self.fps} fps"
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 8e16cefaca..4ffbe20959 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -62919,7 +62919,7 @@
"category": "video",
"class": "invocation",
"classification": "prototype",
- "description": "Predicts the natural length of the shot a prompt describes, as an LTX-2 frame count.\n\nThe duration head reads the same connector outputs the transformer's prompt cross-attention\nconsumes, so it judges the prompt the model will actually see rather than its raw text. The\nprediction is clamped to `min_seconds`/`max_seconds` and then snapped down onto the VAE's\ncausal temporal grid (`8k + 1`), which is the only frame count a generation can run at.\n\nFor an extension, the prompt describes the continuation rather than the frames it opens with,\nso the prediction sizes the new material and `context_frames` is added in front of it.\nConditioning clips fix the frame count by construction -- the clip decides it -- so this node\nhas nothing to say about those graphs.",
+ "description": "Predicts the natural length of the shot a prompt describes, as an LTX-2 frame count.\n\nThe duration head reads the same connector outputs the transformer's prompt cross-attention\nconsumes, so it judges the prompt the model will actually see rather than its raw text. The\nprediction is clamped to `min_seconds`/`max_seconds` and then snapped down onto the VAE's\ncausal temporal grid (`8k + 1`), which is the only frame count a generation can run at. The\ntotal is then capped at `max_num_frames` (by default LTX-2's longest clip), which can be\nshorter than `max_seconds` at a high frame rate.\n\nFor an extension, the prompt describes the continuation rather than the frames it opens with,\nso the prediction sizes the new material and `context_frames` is added in front of it.\nConditioning clips fix the frame count by construction -- the clip decides it -- so this node\nhas nothing to say about those graphs.",
"node_pack": "invokeai",
"properties": {
"id": {
@@ -63028,22 +63028,16 @@
"type": "integer"
},
"max_num_frames": {
- "anyOf": [
- {
- "minimum": 1,
- "type": "integer"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "description": "Longest total frame count the run was sized for. The result never exceeds it, whatever frame rate the seconds bounds turn out to be read at.",
+ "default": 481,
+ "description": "Longest total frame count, context included, the run was sized for. The result is capped at it, so it holds at whatever `fps` the run turns out to have.",
"field_kind": "input",
"input": "any",
- "orig_default": null,
+ "maximum": 481,
+ "minimum": 1,
+ "orig_default": 481,
"orig_required": false,
- "title": "Max Num Frames"
+ "title": "Max Num Frames",
+ "type": "integer"
},
"type": {
"const": "ltx2_duration",
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index ba5125401a..6a3f86376e 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -25089,7 +25089,9 @@ export type components = {
* The duration head reads the same connector outputs the transformer's prompt cross-attention
* consumes, so it judges the prompt the model will actually see rather than its raw text. The
* prediction is clamped to `min_seconds`/`max_seconds` and then snapped down onto the VAE's
- * causal temporal grid (`8k + 1`), which is the only frame count a generation can run at.
+ * causal temporal grid (`8k + 1`), which is the only frame count a generation can run at. The
+ * total is then capped at `max_num_frames` (by default LTX-2's longest clip), which can be
+ * shorter than `max_seconds` at a high frame rate.
*
* For an extension, the prompt describes the continuation rather than the frames it opens with,
* so the prediction sizes the new material and `context_frames` is added in front of it.
@@ -25152,10 +25154,10 @@ export type components = {
context_frames?: number;
/**
* Max Num Frames
- * @description Longest total frame count the run was sized for. The result never exceeds it, whatever frame rate the seconds bounds turn out to be read at.
- * @default null
+ * @description Longest total frame count, context included, the run was sized for. The result is capped at it, so it holds at whatever `fps` the run turns out to have.
+ * @default 481
*/
- max_num_frames?: number | null;
+ max_num_frames?: number;
/**
* type
* @default ltx2_duration
diff --git a/invokeai/frontend/webv2/src/features/video/core/__snapshots__/videoGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/video/core/__snapshots__/videoGraphNodeTypes.json
index eb0b955a07..361caa7041 100644
--- a/invokeai/frontend/webv2/src/features/video/core/__snapshots__/videoGraphNodeTypes.json
+++ b/invokeai/frontend/webv2/src/features/video/core/__snapshots__/videoGraphNodeTypes.json
@@ -487,10 +487,6 @@
"max_num_frames": [
121
],
- "max_seconds": [
- 4.375,
- 5.041666666666667
- ],
"min_seconds": [
1
],
diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
index 4450f04926..01b9118f1f 100644
--- a/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/graph.test.ts
@@ -1437,9 +1437,10 @@ describe('compileVideoGraph — LTX-2 auto duration', () => {
expect(hasEdge(backendGraph, extend.id, 'context_frames', duration.id, 'context_frames')).toBe(true);
expect(rateSource).toBeDefined();
expect(hasEdge(backendGraph, rateSource!.node_id, rateSource!.field, duration.id, 'fps')).toBe(true);
- // 17 context frames leave 121 - 16 = 105 for the prediction, read at the source's 30 fps.
- expect(duration.max_seconds).toBe(105 / 30);
+ // The ceiling goes in frames alone: the node converts it at the rate it receives, so a seconds
+ // bound sized here at the gallery's reading of that rate would override it.
expect(duration.max_num_frames).toBe(121);
+ expect(duration.max_seconds).toBeUndefined();
expect(
backendGraph.edges.filter(
(edge) => edge.destination.node_id === denoise.id && edge.destination.field === 'num_frames'
@@ -1471,10 +1472,39 @@ describe('compileVideoGraph — LTX-2 auto duration', () => {
// Frames is the ceiling the run's memory was sized for; the head reads seconds at the run's rate.
expect(duration.fps).toBe(60);
- expect(duration.max_seconds).toBe(241 / 60);
+ expect(duration.max_num_frames).toBe(241);
expect(duration.min_seconds).toBe(1);
});
+ it('runs both passes of a two-stage continuation at the length it chose, at the source rate', () => {
+ const model = ltx2Model('ltx2_dev');
+ const settings = autoSettings(model, { sourceVideo: LTX2_SOURCE_CLIP, targetResolution: '1024p' });
+ const { backendGraph } = compileVideoGraph(settings, model);
+ const duration = nodeOfType(backendGraph, 'ltx2_duration');
+ const denoises = nodesOfType(backendGraph, 'ltx2_denoise');
+ const rateSource = backendGraph.edges.find(
+ (edge) => edge.destination.node_id === duration.id && edge.destination.field === 'fps'
+ )?.source;
+
+ expect(denoises).toHaveLength(2);
+ expect(rateSource).toBeDefined();
+ for (const denoise of denoises) {
+ expect(hasEdge(backendGraph, duration.id, 'num_frames', denoise.id, 'num_frames'), denoise.id).toBe(true);
+ // Each pass plays at the rate the head converted at, or the chosen length means another duration.
+ expect(hasEdge(backendGraph, rateSource!.node_id, rateSource!.field, denoise.id, 'fps'), denoise.id).toBe(true);
+ }
+ });
+
+ it('skips the head when the context of a continuation leaves it no range to choose from', () => {
+ const model = ltx2Model('ltx2_dev');
+ // 17 held frames leave 33 - 16 = 17 for the prediction, 0.7 s at 24 fps: under the head's 1 s floor.
+ const settings = autoSettings(model, { numFrames: 33, sourceVideo: LTX2_SOURCE_CLIP });
+ const { backendGraph } = compileVideoGraph(settings, model);
+
+ expect(nodesOfType(backendGraph, 'ltx2_duration')).toHaveLength(0);
+ expect(nodeOfType(backendGraph, 'ltx2_denoise').num_frames).toBe(33);
+ });
+
it('skips the head when the Frames ceiling leaves it no range to choose from', () => {
const model = ltx2Model('ltx2_dev');
// 17 frames at 24 fps is 0.7 s, under the head's 1 s floor: the clip runs at 17 frames.
diff --git a/invokeai/frontend/webv2/src/features/video/core/graph.ts b/invokeai/frontend/webv2/src/features/video/core/graph.ts
index 1679e81426..db4477844d 100644
--- a/invokeai/frontend/webv2/src/features/video/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/graph.ts
@@ -778,8 +778,8 @@ const buildLtx2VideoGraph = (settings: VideoSettings, model: MainModelConfig): B
// own edge further down, and a second edge into one input is a malformed graph rather than a
// fallback. An extension's prompt sizes the continuation; its rate and held context arrive over
// edges once the join is laid out. The head chooses at most the Frames value, which under auto
- // duration is the ceiling the run's memory was sized for -- passed in frames as well, because a
- // continuation's seconds are read at a rate only the run knows.
+ // duration is the ceiling the run's memory was sized for. It goes in frames only: the node turns it
+ // into seconds at the rate it actually runs at, which for a continuation only the run knows.
const durationBounds = getAutoDurationBounds(model, settings);
const durationHead =
durationBounds && settings.ltx2DurationHeadModel
@@ -789,7 +789,6 @@ const buildLtx2VideoGraph = (settings: VideoSettings, model: MainModelConfig): B
id: 'duration',
type: 'ltx2_duration',
max_num_frames: timing.numFrames,
- max_seconds: durationBounds.maxSeconds,
min_seconds: durationBounds.minSeconds,
})
: null;
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts
index 7ac8c8f59c..b4fdaedffc 100644
--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts
@@ -2585,11 +2585,34 @@ describe('auto duration', () => {
contextFrames: 25,
fps: 30,
maxFrames: 121,
+ maxNewFrames: 96,
maxSeconds: 97 / 30,
minSeconds: 1,
});
});
+ it('holds a continuation inside the trained range of the head, below the Frames ceiling', () => {
+ const extending = settings({
+ ltx2ExtendContextFrames: 17,
+ numFrames: 481,
+ sourceVideo: {
+ endFrame: 48,
+ fps: 20,
+ height: 704,
+ numFrames: 49,
+ startFrame: 0,
+ video_name: 's.mp4',
+ width: 1248,
+ },
+ } as Partial<VideoSettings>);
+ const bounds = getAutoDurationBounds(ltx2('ltx2_dev'), extending);
+
+ // 465 frames of room is 23 s at 20 fps; the head stops at 20 s, i.e. 393 frames on the grid.
+ expect(bounds?.maxSeconds).toBe(20);
+ expect(bounds?.maxNewFrames).toBe(392);
+ expect(bounds?.maxFrames).toBe(17 + 392);
+ });
+
it('is inactive without a head, however the flag is stored', () => {
expect(isAutoDurationActive(settings({ ltx2DurationHeadModel: null }))).toBe(false);
expect(isAutoDurationActive(settings({ autoDuration: false }))).toBe(false);
diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
index b133e9a5b0..0c7ce98704 100644
--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts
@@ -848,6 +848,8 @@ export interface AutoDurationBounds {
contextFrames: number;
/** The longest total the head can hand the run, context included, at `fps`. */
maxFrames: number;
+ /** The most new material that total holds: `maxFrames` less the context. */
+ maxNewFrames: number;
/** The rate the seconds are read at; a continuation's is the source's. */
fps: number;
}
@@ -878,7 +880,7 @@ export const getAutoDurationBounds = (
}
const timing = getEffectiveVideoTiming(model, settings);
const source = resolveVideoMode(settings) === 'extend' ? settings.sourceVideo : null;
- const fps = source?.fps ?? timing.fps;
+ const fps = source ? source.fps : timing.fps;
const contextFrames = source ? settings.ltx2ExtendContextFrames : 0;
// Both 8k + 1, so their difference plus one is too: the longest prediction that still fits.
const bounds = ltx2AutoDurationBounds(fps, frames.min, timing.numFrames - Math.max(0, contextFrames - 1));
@@ -893,6 +895,7 @@ export const getAutoDurationBounds = (
contextFrames,
fps,
maxFrames: contextFrames ? contextFrames + predicted - 1 : predicted,
+ maxNewFrames: contextFrames ? predicted - 1 : predicted,
};
};
diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
index 7477c6c0c5..4cc76f31bd 100644
--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx
@@ -160,9 +160,7 @@ export const VideoWidgetView = () => {
[autoDurationBounds]
);
const autoDurationSupported = useMemo(() => isAutoDurationSupportedForMode(values), [values]);
- const extendNewFrames = autoDurationBounds
- ? autoDurationBounds.maxFrames - autoDurationBounds.contextFrames
- : (policy.ui.extendContext?.newFrames ?? 0);
+ const extendNewFrames = autoDurationBounds?.maxNewFrames ?? policy.ui.extendContext?.newFrames ?? 0;
const durationSeconds = getVideoDurationSeconds(
timing.numFrames,
// In extend mode the extension inherits the SOURCE clip's frame rate.
diff --git a/tests/app/invocations/test_ltx2_duration.py b/tests/app/invocations/test_ltx2_duration.py
index fe66a7bf88..4f19550c96 100644
--- a/tests/app/invocations/test_ltx2_duration.py
+++ b/tests/app/invocations/test_ltx2_duration.py
@@ -13,6 +13,7 @@ from unittest.mock import MagicMock
import pytest
import torch
from diffusers.pipelines.ltx2.duration_head import LTX2DurationHead
+from pydantic import ValidationError
from invokeai.app.invocations.fields import LTX2ConditioningField
from invokeai.app.invocations.ltx2.ltx2_duration import LTX2DurationInvocation
@@ -166,12 +167,33 @@ def test_the_frame_ceiling_holds_when_the_rate_is_higher_than_the_bounds_assumed
assert output.num_frames == 121 # 124 snapped down onto the grid
+def test_the_frame_ceiling_is_reached_when_the_rate_is_lower_than_the_caller_assumed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A source recorded at 24 fps that really plays at 16: seconds sized at 24 would stop at 81 of 121 frames."""
+ head = _head(monkeypatch, seconds=30.0)
+ output = _node(fps=16.0, context_frames=17, max_num_frames=121).invoke(_context(head))
+
+ assert output.num_frames == 121
+
+
+def test_a_standalone_extension_stays_within_the_family_s_longest_clip(monkeypatch: pytest.MonkeyPatch) -> None:
+ """241 held frames plus a 20 s prediction at 24 fps would be 713 frames, past what LTX-2 generates."""
+ head = _head(monkeypatch, seconds=30.0)
+ output = _node(fps=24.0, context_frames=241).invoke(_context(head))
+
+ assert output.num_frames == 481
+ # Nor can a caller ask for more: no LTX-2 run goes past it.
+ with pytest.raises(ValidationError):
+ _node(max_num_frames=482)
+
+
@pytest.mark.parametrize(
("context_frames", "max_num_frames", "match"),
- [(16, None, "8k\\+1 grid"), (17, 20, "leaves no room")],
+ [(16, 481, "8k\\+1 grid"), (17, 20, "leaves no room")],
)
def test_it_refuses_a_context_it_cannot_continue_from(
- monkeypatch: pytest.MonkeyPatch, context_frames: int, max_num_frames: int | None, match: str
+ monkeypatch: pytest.MonkeyPatch, context_frames: int, max_num_frames: int, match: str
) -> None:
head = _head(monkeypatch, seconds=5.0)
with pytest.raises(ValueError, match=match):