Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: reuse MiniMax H3 models and prompts for sequential video batches

[._.]/ Adam Eivy127fb28b4a7a
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsx
index c3ff9ecaaf..f9eaad7a82 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx
@@ -34,6 +34,7 @@ export default function AdvancedParamsPanel({
contextFrames, onContextFramesChange,
fps, onFpsChange,
seed, onSeedChange, onRandomSeed,
+ batchSize = 1, onBatchSizeChange,
steps, onStepsChange,
guidanceScale, onGuidanceScaleChange,
speedProfileId = DEFAULT_SPEED_PROFILE_ID, onSpeedProfileChange,
@@ -254,6 +255,22 @@ export default function AdvancedParamsPanel({
</select>
</FormField>
+ {onBatchSizeChange && (
+ <div>
+ <label htmlFor={fieldId('video-batch-size')} className="block text-xs font-medium text-gray-400 mb-1">Renders in batch</label>
+ <select id={fieldId('video-batch-size')} className={inputCls}
+ value={currentModel?.supportsWarmBatch && !chainingActive ? batchSize : 1}
+ disabled={!currentModel?.supportsWarmBatch || chainingActive}
+ onChange={(event) => onBatchSizeChange(Number(event.target.value))}>
+ {Array.from({ length: 20 }, (_, index) => <option key={index + 1} value={index + 1}>{index + 1}</option>)}
+ </select>
+ <p className="mt-1 text-xs text-gray-500">
+ {!currentModel?.supportsWarmBatch ? 'Warm batching is available for local MiniMax H3 MLX models.'
+ : chainingActive ? 'Use one chunk to batch separate videos.'
+ : 'Sequential videos reuse the model and prompt. Blank seed: random each time. Number: increment per render.'}
+ </p>
+ </div>
+ )}
<div>
<label htmlFor={fieldId('video-seed')} className="block text-xs font-medium text-gray-400 mb-1">Seed</label>
<div className="flex items-center gap-1">
@@ -269,7 +286,7 @@ export default function AdvancedParamsPanel({
type="button"
onClick={onRandomSeed}
className="p-2 text-gray-400 hover:text-white border border-port-border rounded-lg hover:bg-port-border/50 disabled:opacity-50 min-h-[40px] min-w-[40px] flex items-center justify-center"
- title="Randomize seed" aria-label="Randomize seed"
+ title="Use a random seed for each render" aria-label="Randomize seed"
>
<Dice5 className="w-4 h-4" />
</button>
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
index efc8d14e29..2e1f9851c3 100644
--- a/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
+++ b/client/src/components/videoGen/AdvancedParamsPanel.test.jsx
@@ -56,7 +56,7 @@ describe('AdvancedParamsPanel', () => {
it('fires onRandomSeed from the dice button', () => {
const onRandomSeed = vi.fn();
renderPanel({ onRandomSeed });
- fireEvent.click(screen.getByTitle('Randomize seed'));
+ fireEvent.click(screen.getByRole('button', { name: 'Randomize seed' }));
expect(onRandomSeed).toHaveBeenCalled();
});
@@ -532,3 +532,20 @@ describe('AdvancedParamsPanel — draft decode', () => {
expect(screen.getByText(/Example Delivery is a delivery model/)).toBeTruthy();
});
});
+
+it('offers a bounded batch selector and explains unsupported models and chaining', () => {
+ const onBatchSizeChange = vi.fn();
+ const props = { ...baseProps, currentModel: { ...baseProps.currentModel, supportsWarmBatch: true }, batchSize: 3, onBatchSizeChange };
+ const { rerender } = render(<AdvancedParamsPanel {...props} />);
+ const picker = screen.getByLabelText('Renders in batch');
+ expect(picker.value).toBe('3');
+ fireEvent.change(picker, { target: { value: '5' } });
+ expect(onBatchSizeChange).toHaveBeenCalledWith(5);
+ expect(screen.getByText(/Blank seed: random each time/)).toBeTruthy();
+ rerender(<AdvancedParamsPanel {...props} chainingActive />);
+ expect(picker.disabled).toBe(true);
+ expect(picker.value).toBe('1');
+ rerender(<AdvancedParamsPanel {...props} currentModel={baseProps.currentModel} />);
+ expect(picker.disabled).toBe(true);
+ expect(screen.getByText(/available for local MiniMax H3/)).toBeTruthy();
+});
diff --git a/client/src/hooks/useMediaCompletionRefresh.js b/client/src/hooks/useMediaCompletionRefresh.js
index 4d6a3a1113..217b45cc8c 100644
--- a/client/src/hooks/useMediaCompletionRefresh.js
+++ b/client/src/hooks/useMediaCompletionRefresh.js
@@ -21,13 +21,19 @@ export function useMediaCompletionRefresh({ onImageCompleted, onVideoCompleted,
const onImageDone = () => schedule('image', imageCallbackRef);
const onVideoDone = () => schedule('video', videoCallbackRef);
+ // A batch can save usable videos before a later render fails or is canceled.
+ const onVideoFailed = (event) => {
+ if (Array.isArray(event?.results) && event.results.length > 0) onVideoDone();
+ };
socket.on('image-gen:completed', onImageDone);
socket.on('video-gen:completed', onVideoDone);
+ socket.on('video-gen:failed', onVideoFailed);
return () => {
socket.off('image-gen:completed', onImageDone);
socket.off('video-gen:completed', onVideoDone);
+ socket.off('video-gen:failed', onVideoFailed);
Object.values(timersRef.current).forEach((timer) => {
if (timer) clearTimeout(timer);
});
diff --git a/client/src/hooks/useMediaCompletionRefresh.test.jsx b/client/src/hooks/useMediaCompletionRefresh.test.jsx
new file mode 100644
index 0000000000..ef307f8a24
--- /dev/null
+++ b/client/src/hooks/useMediaCompletionRefresh.test.jsx
@@ -0,0 +1,27 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import socket from '../services/socket';
+import { useMediaCompletionRefresh } from './useMediaCompletionRefresh';
+
+vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+afterEach(() => vi.useRealTimers());
+
+it('refreshes usable batch outputs after failure without treating an empty failure as new media', () => {
+ vi.useFakeTimers();
+ const refresh = vi.fn();
+ const { unmount } = renderHook(() => useMediaCompletionRefresh({ onVideoCompleted: refresh }));
+ const failed = socket.on.mock.calls.find(([event]) => event === 'video-gen:failed')[1];
+ act(() => {
+ failed({ error: 'No outputs' });
+ failed({ results: [] });
+ vi.advanceTimersByTime(250);
+ });
+ expect(refresh).not.toHaveBeenCalled();
+ act(() => {
+ failed({ results: [{ filename: 'example.mp4', seed: 0 }] });
+ vi.advanceTimersByTime(250);
+ });
+ expect(refresh).toHaveBeenCalledTimes(1);
+ unmount();
+ expect(socket.off).toHaveBeenCalledWith('video-gen:failed', failed);
+});
diff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.js
index 56cbe69c7a..e14bf5059e 100644
--- a/client/src/hooks/useVideoGenFieldState.js
+++ b/client/src/hooks/useVideoGenFieldState.js
@@ -50,6 +50,7 @@ export function useVideoGenFieldState({
const [guidanceScale, setGuidanceScale] = useState('');
const [imageStrength, setImageStrength] = useState('');
const [i2vReferenceMode, setI2vReferenceMode] = useState(DEFAULT_I2V_REFERENCE_MODE);
+ const [batchSize, setBatchSize] = useState(1);
const [seed, setSeed] = useState('');
const [tiling, setTiling] = useState('auto');
const [textEncoderId, setTextEncoderId] = useState(STOCK_TEXT_ENCODER_ID);
@@ -119,7 +120,7 @@ export function useVideoGenFieldState({
prompt, setPrompt,
remixModelFallback, setRemixModelFallback,
remixSourceModel, setRemixSourceModel,
- seed, setSeed,
+ seed, setSeed, batchSize, setBatchSize,
selectedLoras, setSelectedLoras,
selectedUniverse, setSelectedUniverse,
sizeManuallySetRef,
diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.js
index bb4c7a1c5b..0dd2d01a20 100644
--- a/client/src/hooks/useVideoGenForm.js
+++ b/client/src/hooks/useVideoGenForm.js
@@ -8,7 +8,6 @@ import {
DEFAULT_I2V_REFERENCE_MODE, isDefaultI2vReferenceMode, normalizeI2vReferenceMode,
runtimeSupportsI2vReferenceMode, resolveI2vReferenceStrength,
} from '../lib/videoReferenceModes';
-import { randomSeed } from '../lib/genUtils';
import {
resolutionOptionsForModel, defaultResolutionForModel, snapAspectToImage,
} from '../lib/videoGenResolutions';
@@ -129,6 +128,7 @@ export function useVideoGenForm({
prompt, setPrompt,
remixModelFallback, setRemixModelFallback,
remixSourceModel, setRemixSourceModel,
+ batchSize, setBatchSize,
seed, setSeed,
selectedLoras, setSelectedLoras,
selectedUniverse, setSelectedUniverse,
@@ -683,7 +683,7 @@ export function useVideoGenForm({
const handleResolutionChange = (w, h) => {
setWidth(w); setHeight(h); sizeManuallySetRef.current = true;
};
- const handleRandomSeed = () => setSeed(randomSeed());
+ const handleRandomSeed = () => setSeed('');
// Switching model drops the sampler overrides — steps/guidanceScale are
// per-model defaults, and carrying one model's numbers onto another is
// usually wrong.
@@ -1188,7 +1188,8 @@ export function useVideoGenForm({
if (p.fps) setFps(p.fps);
if (p.steps != null) setSteps(String(p.steps));
if (p.guidanceScale != null) setGuidanceScale(String(p.guidanceScale));
- if (p.seed != null) setSeed(String(p.seed));
+ setBatchSize(p.batchSize ?? 1);
+ setSeed(p.seed == null ? '' : String(p.seed));
if (p.tiling) setTiling(p.tiling);
// Conditioning promise + strength. Both are echoed only when they applied, so
// absence means "the defaults" and must CLEAR whatever the form last held —
@@ -1298,7 +1299,7 @@ export function useVideoGenForm({
displaySleepEnabled,
prompt, negativePrompt, stylePreset, selectedUniverse,
width, height, mode, sourceImageFile, sourceImageUpload,
- numFrames, fps, steps, guidanceScale, seed,
+ numFrames, fps, steps, guidanceScale, seed, batchSize,
currentModel, models, modelId, tiling, textEncoderId, speedProfileId, draftDecode,
disableAudio, noMusic, imageStrength, i2vReferenceMode,
keyframesActive, keyframes, loraFamily, selectedLoras,
@@ -1346,6 +1347,7 @@ export function useVideoGenForm({
imageStrength, setImageStrength,
i2vReferenceMode, setI2vReferenceMode,
referenceModeSupported, effectiveImageStrength,
+ batchSize, setBatchSize,
seed, setSeed, handleRandomSeed,
tiling, setTiling,
textEncoderId, setTextEncoderId, textEncoderOptions,
diff --git a/client/src/hooks/useVideoGenSubmitFlow.test.jsx b/client/src/hooks/useVideoGenSubmitFlow.test.jsx
index ded43c6575..80674f1041 100644
--- a/client/src/hooks/useVideoGenSubmitFlow.test.jsx
+++ b/client/src/hooks/useVideoGenSubmitFlow.test.jsx
@@ -55,3 +55,13 @@ describe('useVideoGenSubmitFlow', () => {
});
});
});
+
+it('submits batch size and seed zero only to a capable, unchained local runtime', () => {
+ const state = { ...submissionState('Example shot'), currentModel: { supportsWarmBatch: true }, batchSize: 3, seed: 0 };
+ const { result, rerender } = renderHook(({ value }) => useVideoGenSubmitFlow(value), { initialProps: { value: state } });
+ expect(result.current.buildGeneratePayload()).toMatchObject({ batchSize: 3, seed: 0 });
+ for (const overrides of [{ currentModel: {} }, { chainingActive: true, chunks: 2 }, { isGrok: true }, { remoteSubmissionFields: { mediaProviderPeerId: 'peer' } }]) {
+ rerender({ value: { ...state, ...overrides } });
+ expect(result.current.buildGeneratePayload()).not.toHaveProperty('batchSize');
+ }
+});
diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.js
index 4fe58d42b0..589e0d06a9 100644
--- a/client/src/lib/videoGenSubmission.js
+++ b/client/src/lib/videoGenSubmission.js
@@ -49,7 +49,7 @@ export function buildVideoGenSubmission({
displaySleepEnabled,
prompt, negativePrompt, stylePreset, selectedUniverse,
width, height, mode, sourceImageFile, sourceImageUpload,
- numFrames, fps, steps, guidanceScale, seed,
+ numFrames, fps, steps, guidanceScale, seed, batchSize = 1,
currentModel, models, modelId, tiling, textEncoderId, speedProfileId, draftDecode,
disableAudio, noMusic, imageStrength, i2vReferenceMode,
keyframesActive, keyframes, loraFamily, selectedLoras,
@@ -141,7 +141,7 @@ export function buildVideoGenSubmission({
fps,
steps: steps || '',
guidanceScale: guidanceScale || '',
- seed: seed || '',
+ seed: seed ?? '',
...remoteSubmissionFields,
};
}
@@ -159,7 +159,8 @@ export function buildVideoGenSubmission({
fps,
steps: steps || '',
guidanceScale: guidanceScale || '',
- seed: seed || '',
+ seed: seed ?? '',
+ ...(currentModel?.supportsWarmBatch && !chainingActive && batchSize > 1 ? { batchSize } : {}),
tiling: currentModel?.supportsTiling === false ? 'auto' : tiling,
textEncoderId: normalizeTextEncoderForModel(textEncoderId, currentModel) === STOCK_TEXT_ENCODER_ID
? undefined
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index f002612efb..b84c59000c 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -228,6 +228,7 @@ export default function VideoGen() {
speedProfileId, setSpeedProfileId,
draftDecode, setDraftDecode,
+ batchSize, setBatchSize,
seed, setSeed, handleRandomSeed, tiling, setTiling,
textEncoderId, setTextEncoderId, textEncoderOptions,
disableAudio, setDisableAudio, noMusic, setNoMusic,
@@ -1047,6 +1048,9 @@ export default function VideoGen() {
// A federated render answers to the PEER’s readiness, not to this machine’s
// runtime gates — none of the local probes below describe the hardware it
// will actually run on.
+ const effectiveBatchSize = !isGrok && !isFal && !isReactor && !remoteTarget.isRemote
+ && currentModel?.supportsWarmBatch && !chainingActive ? batchSize : 1;
+
const canEnqueue = prompt.trim() && !remixHandoffPending && !promptOverLimit && (remoteTarget.isRemote
? remoteBlocked === null
: (isGrok || isFal || isReactor || (!notConnected && !extendModeBlocked
@@ -1747,6 +1751,7 @@ export default function VideoGen() {
chunkPrompts={chunkPrompts} onChunkPromptChange={setChunkPromptAt} chainingActive={chainingActive}
contextFrames={contextFrames} onContextFramesChange={setContextFrames}
fps={fps} onFpsChange={setFps}
+ batchSize={batchSize} onBatchSizeChange={setBatchSize}
seed={seed} onSeedChange={setSeed} onRandomSeed={handleRandomSeed}
steps={steps} onStepsChange={setSteps}
guidanceScale={guidanceScale} onGuidanceScaleChange={setGuidanceScale}
@@ -1795,7 +1800,7 @@ export default function VideoGen() {
: undefined
}
>
- <Sparkles className="w-4 h-4" /> Generate
+ <Sparkles className="w-4 h-4" /> {effectiveBatchSize > 1 ? `Generate ${effectiveBatchSize} videos` : 'Generate'}
</button>
)}
<button
@@ -1808,7 +1813,7 @@ export default function VideoGen() {
: weightsGateBlocked ? 'Finish required model downloads before queueing'
: 'Complete the required inputs before queueing'}
>
- <ListPlus className="w-4 h-4" /> Add to queue
+ <ListPlus className="w-4 h-4" /> {effectiveBatchSize > 1 ? `Add ${effectiveBatchSize} videos to queue` : 'Add to queue'}
</button>
{progressPct != null && <span className="text-xs text-port-accent">{progressPct}%</span>}
{(generating || error) && (
diff --git a/docs/README.md b/docs/README.md
index 7ea6eae8a5..16a3519c03 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -46,7 +46,7 @@ Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system]
Knowledge: [brain-system](./features/brain-system.md) · [untrusted messages and GitHub automation](./features/messages-security.md)
-Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [Eidoverse Worlds integration](./features/eidoverse.md) · [OpenWorld historical reference](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md)
+Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [Eidoverse Worlds integration](./features/eidoverse.md) · [OpenWorld historical reference](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md) · [video-render-batches](./features/video-render-batches.md)
Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md)
diff --git a/docs/features/video-render-batches.md b/docs/features/video-render-batches.md
new file mode 100644
index 0000000000..9d8e66bb12
--- /dev/null
+++ b/docs/features/video-render-batches.md
@@ -0,0 +1,31 @@
+# Warm video render batches
+
+In Video Gen, **Advanced → Renders in batch** selects 1–20 separate videos using
+one prompt, model and set of conditioning inputs. **Generate** and **Add to queue**
+show the requested count. The default is one render.
+
+- Leave **Seed** blank, or click its dice button, for an independent random seed
+ on every render.
+- Enter a seed for consecutive seeds: a batch of three starting at `0` renders
+ with `0`, `1`, and `2`. Seeds must remain within the unsigned 32-bit range;
+ an overflowing batch is rejected before it is queued.
+- A batch owns one local queue slot until it finishes or is canceled. Each
+ finished video is saved to history with its actual seed. Canceling or failing
+ a later render preserves the earlier finished videos.
+
+Warm batching currently supports the **MiniMax H3 MLX** runtime. One Python
+process loads its pipeline and adapters once, retains its model weights and
+modulation cache, and reuses the request's prompt embeddings in memory. Each
+video is rendered and saved before the next starts; decoded outputs are released
+between renders. This reuse does not depend on the optional disk prompt cache.
+
+Other runtimes, cloud providers and federated targets do not offer this control.
+In particular, LTX's two-stage pipeline fuses an adapter into its transformer and
+unloads components between stages; looping that pipeline with retained weights
+would change subsequent renders. Support requires a runtime-specific contract,
+not merely launching the existing command repeatedly.
+
+Batches produce independent clips, so they cannot be combined with chained
+chunks or a scene-delivery tag. Batch records carry additive `batchId`,
+`batchIndex` (zero-based) and `batchSize` metadata. Their durations do not train
+single-render ETA estimates because startup is shared across the batch.
diff --git a/scripts/generate_minimax_h3.py b/scripts/generate_minimax_h3.py
index a03fa73cc0..ebee08d76e 100644
--- a/scripts/generate_minimax_h3.py
+++ b/scripts/generate_minimax_h3.py
@@ -99,6 +99,7 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--prompt-embedding-cache-dir",
help="directory holding reusable prompt embeddings, keyed by prompt text and "
"conditioning-image content (omit to recompute on every render)")
+ parser.add_argument("--batch-seeds", help="JSON array of per-render seeds; one resident pipeline")
return parser.parse_args()
@@ -1020,8 +1021,79 @@ def validate_args(args: argparse.Namespace) -> None:
raise SystemExit(f"--draft-decoder-id must be a bare directory-safe name; got {args.draft_decoder_id!r}.")
+def render_outputs(pipe, args, images, save_mp4, batch_seeds=None):
+ """Render one at a time, retaining weights and only this request's conditioning.
+
+ The pipeline already keeps its DiT, VAEs and modulation cache. Cache the
+ encoder's return in memory even when the optional disk cache is unavailable.
+ The closed-over prompt and images never change inside this workflow.
+ """
+ preview = _install_h3_stepwise_preview(pipe, args)
+ encode = pipe.text_encoder.encode
+ encoded = None
+
+ def encode_once(*values, **kwargs):
+ nonlocal encoded
+ if encoded is None:
+ encoded = encode(*values, **kwargs)
+ return encoded
+
+ if batch_seeds is not None:
+ pipe.text_encoder.encode = encode_once
+ try:
+ base_output = Path(args.output)
+ for index, seed in enumerate(batch_seeds or [args.seed]):
+ output = base_output if index == 0 else base_output.with_name(f"{base_output.stem}-{index + 1}{base_output.suffix}")
+ if batch_seeds is not None:
+ print(f"STATUS:Rendering video {index + 1}/{len(batch_seeds)} (seed {seed})", file=sys.stderr, flush=True)
+ print("STAGE:inference", file=sys.stderr, flush=True)
+ progress = ProgressWriter(preview)
+ with heartbeat("minimax-h3-inference"), redirect_stdout(progress):
+ result = pipe(
+ args.prompt,
+ duration_seconds=args.num_frames / FPS,
+ num_inference_steps=args.steps,
+ seed=seed,
+ images=images or None,
+ keyframe_anchors=tuple(args.anchor),
+ height=args.height,
+ width=args.width,
+ drop_adaln=True,
+ )
+ progress.flush()
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ wav_path = output.with_suffix(".wav")
+ print("STAGE:mux", file=sys.stderr, flush=True)
+ try:
+ save_mp4(output, result.video, result.fps, result.audio, result.sample_rate)
+ finally:
+ wav_path.unlink(missing_ok=True)
+
+ if not output.is_file() or output.stat().st_size == 0:
+ raise RuntimeError(f"MiniMax H3 completed but did not write {output}.")
+ print(
+ f"STATUS:MiniMax H3 saved {output.name} ({result.video.shape[0]} frames with stereo audio)",
+ file=sys.stderr,
+ flush=True,
+ )
+ if batch_seeds is None:
+ emit_result(output)
+ else:
+ print(json.dumps({"video_path": str(output), "batch_index": index, "seed": seed}), flush=True)
+ del result
+ finally:
+ if batch_seeds is not None:
+ pipe.text_encoder.encode = encode
+
+
def main() -> int:
args = parse_args()
+ batch_seeds = json.loads(args.batch_seeds) if args.batch_seeds else None
+ if batch_seeds is not None and (not isinstance(batch_seeds, list)
+ or not 2 <= len(batch_seeds) <= 20
+ or any(type(seed) is not int or not 0 <= seed <= 2 ** 32 - 1 for seed in batch_seeds)):
+ raise ValueError("--batch-seeds requires 2 to 20 unsigned 32-bit integers")
validate_args(args)
# Read the keyframes first: everything below is a git probe, ~35 HF cache
# lookups and an mlx/transformers import, so an unreadable conditioning
@@ -1178,40 +1250,7 @@ def main() -> int:
[{"path": p, "scale": s} for p, s in zip(args.lora, args.lora_scale)],
)
- print("STAGE:inference", file=sys.stderr, flush=True)
- preview = _install_h3_stepwise_preview(pipe, args)
- progress = ProgressWriter(preview)
- with heartbeat("minimax-h3-inference"), redirect_stdout(progress):
- result = pipe(
- args.prompt,
- duration_seconds=args.num_frames / FPS,
- num_inference_steps=args.steps,
- seed=args.seed,
- images=images or None,
- keyframe_anchors=tuple(args.anchor),
- height=args.height,
- width=args.width,
- drop_adaln=True,
- )
- progress.flush()
-
- output = Path(args.output)
- output.parent.mkdir(parents=True, exist_ok=True)
- wav_path = output.with_suffix(".wav")
- print("STAGE:mux", file=sys.stderr, flush=True)
- try:
- save_mp4(output, result.video, result.fps, result.audio, result.sample_rate)
- finally:
- wav_path.unlink(missing_ok=True)
-
- if not output.is_file() or output.stat().st_size == 0:
- raise RuntimeError(f"MiniMax H3 completed but did not write {output}.")
- print(
- f"STATUS:MiniMax H3 saved {output.name} ({result.video.shape[0]} frames with stereo audio)",
- file=sys.stderr,
- flush=True,
- )
- emit_result(output)
+ render_outputs(pipe, args, images, save_mp4, batch_seeds)
return 0
diff --git a/scripts/generate_minimax_h3.test.js b/scripts/generate_minimax_h3.test.js
index e80ee8907d..d17ad0aef0 100644
--- a/scripts/generate_minimax_h3.test.js
+++ b/scripts/generate_minimax_h3.test.js
@@ -1223,3 +1223,43 @@ describe.skipIf(!pyBin)('generate_minimax_h3.py', () => {
});
});
});
+
+it.skipIf(!pyBin)('renders a batch on one pipeline with one encode and preserves earlier outputs on failure', () => {
+ const output = runPython(`${importRunner}
+import contextlib, io, tempfile
+from types import SimpleNamespace as NS
+runner.heartbeat = lambda *_: contextlib.nullcontext()
+runner._install_h3_stepwise_preview = lambda *_: None
+calls, encodes, saves = [], [], []
+encoder = NS(encode=lambda *a, **k: encodes.append(a) or ('embeddings', 'tags'))
+def render(prompt, **kwargs):
+ encoded = encoder.encode(prompt, kwargs['images'])
+ calls.append((kwargs['seed'], encoded))
+ if kwargs['seed'] == 2:
+ raise RuntimeError('render failed')
+ return NS(video=NS(shape=[124]), fps=24, audio=None, sample_rate=32000)
+class Pipe:
+ text_encoder = encoder
+ def __call__(self, *a, **kw): return render(*a, **kw)
+def save(path, *args):
+ saves.append(path.name)
+ path.write_bytes(b'example-video')
+with tempfile.TemporaryDirectory() as tmp:
+ args = NS(output=str(Path(tmp) / 'clip.mp4'), seed=0, prompt='Example shot', num_frames=124, steps=8, anchor=[], height=768, width=1344)
+ frames = io.StringIO()
+ with contextlib.redirect_stdout(frames):
+ try:
+ runner.render_outputs(Pipe(), args, [], save, [0, 1, 2, 3])
+ except RuntimeError as exc:
+ assert str(exc) == 'render failed'
+ results = [runner.json.loads(line) for line in frames.getvalue().splitlines()]
+ assert [r['seed'] for r in results] == [0, 1]
+ assert [r['batch_index'] for r in results] == [0, 1]
+ assert saves == ['clip.mp4', 'clip-2.mp4']
+ assert len(encodes) == 1
+ assert [seed for seed, _ in calls] == [0, 1, 2]
+ assert all(embeds is calls[0][1] for _, embeds in calls)
+print('OK')
+`);
+ expect(output.trim()).toBe('OK');
+});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 9a1be7cb1b..a8f470e143 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -49,6 +49,7 @@ import { cleanupMultipartTemp } from '../services/videoGen/prepareParams.js';
import { submitVideoGenJob } from '../services/videoGen/submitJob.js';
import { resolveReactorApiKey, mintReactorToken } from '../services/videoGen/reactor.js';
import { isVideoModeUsable, VIDEO_GEN_MODE } from '../services/videoGen/modes.js';
+import { MAX_VIDEO_BATCH_SIZE } from '../services/videoGen/batch.js';
import { VIDEO_GEN_LOCAL_ONLY_FIELDS } from '../services/videoGen/requestFields.js';
import { attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';
@@ -213,6 +214,7 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({
[VIDEO_GEN_LOCAL_ONLY_FIELDS.FPS]: optionalNum(1, 60, 'fps'),
[VIDEO_GEN_LOCAL_ONLY_FIELDS.STEPS]: optionalNum(1, 200, 'steps'),
[VIDEO_GEN_LOCAL_ONLY_FIELDS.GUIDANCE_SCALE]: optionalNum(0, 30, 'guidanceScale'),
+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.BATCH_SIZE]: optionalInt(1, MAX_VIDEO_BATCH_SIZE, 'batchSize'),
[VIDEO_GEN_LOCAL_ONLY_FIELDS.SEED]: optionalNum(0, Number.MAX_SAFE_INTEGER, 'seed'),
[VIDEO_GEN_LOCAL_ONLY_FIELDS.IMAGE_STRENGTH]: optionalNum(0, 1, 'imageStrength'),
// What the conditioning image PROMISES (#4874) — 'anchor' (default) pins it as
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index bb03b4b826..4fc122147d 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -904,6 +904,7 @@ describe('videoGen routes', () => {
'fps',
'steps',
'guidanceScale',
+ 'batchSize',
'seed',
'imageStrength',
// Not in the it.each table above: a non-default value is only legal on
@@ -2970,4 +2971,26 @@ describe('videoGen routes', () => {
});
});
+
+ describe('warm video batch submission', () => {
+ it('queues one coerced batch with seed zero and rejects unsupported or overflowing requests', async () => {
+ const models = vi.mocked(videoGenService.listVideoModels);
+ models.mockReturnValue([
+ { id: 'example-h3', name: 'Example H3', runtime: 'minimax_h3', defaultFrames: 124, frameOptions: [124], fpsOptions: [24] },
+ { id: 'example-ltx', runtime: 'ltx2' },
+ ]);
+ const response = await request(app).post('/api/video-gen/').send({
+ prompt: 'Example shot', modelId: 'example-h3', batchSize: '3', seed: '0',
+ });
+ expect(response.status).toBe(200);
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledTimes(1);
+ expect(mediaJobQueue.enqueueJob.mock.calls[0][0].params).toMatchObject({ batchSize: 3, seed: 0 });
+ for (const overrides of [{ batchSize: 1.5 }, { batchSize: 21 }, { seed: 2 ** 32 - 1 }, { modelId: 'example-ltx' }, { backend: 'fal' }, { chunks: 2 }, { mediaProviderPeerId: 'peer' }]) {
+ const rejected = await request(app).post('/api/video-gen/').send({ prompt: 'Example shot', modelId: 'example-h3', batchSize: 3, ...overrides });
+ expect(rejected.status).toBe(400);
+ }
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledTimes(1);
+ });
+ });
+
});
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
index 1ba3476587..69986e5dfc 100644
--- a/server/services/mediaJobQueue/sanitizeJob.js
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -8,7 +8,7 @@ import { mediaJobExecutionLane } from '../../lib/generationModes.js';
const PARAM_ALLOWLIST = new Set([
'prompt', 'negativePrompt', 'modelId', 'model', 'effort',
'width', 'height', 'numFrames', 'fps', 'steps', 'guidanceScale',
- 'seed', 'tiling', 'disableAudio', 'mode', 'imageStrength',
+ 'batchSize', 'seed', 'tiling', 'disableAudio', 'mode', 'imageStrength',
'i2vReferenceMode',
// Sampler/decoder knobs the retry editor re-offers. 'draftDecode' (#5423) is
// the preview-fidelity decode REQUEST the job was submitted with — projected
diff --git a/server/services/videoGen/batch.js b/server/services/videoGen/batch.js
new file mode 100644
index 0000000000..2ff1eaef8c
--- /dev/null
+++ b/server/services/videoGen/batch.js
@@ -0,0 +1,39 @@
+import { randomInt, randomUUID } from 'node:crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+
+export const MAX_VIDEO_BATCH_SIZE = 20;
+const MAX_SEED = 2 ** 32 - 1;
+
+// Only runtimes whose pipeline retains reusable weights without stage-specific
+// in-place fusion may promise warm batching. Never infer this from a model name.
+export const supportsWarmVideoBatch = (model) => model?.runtime === 'minimax_h3';
+
+export function validateVideoBatch(params, model) {
+ const count = Number(params.batchSize ?? 1);
+ if (!Number.isInteger(count) || count < 1 || count > MAX_VIDEO_BATCH_SIZE) {
+ throw new ServerError(`Batch size must be an integer from 1 to ${MAX_VIDEO_BATCH_SIZE}.`, { status: 400, code: 'VIDEO_BATCH_INVALID' });
+ }
+ if (count === 1) return;
+ if (!supportsWarmVideoBatch(model) || (params.backend && params.backend !== 'local') || params.mediaProviderPeerId) {
+ throw new ServerError('Warm video batches require a local MiniMax H3 MLX model.', { status: 400, code: 'VIDEO_BATCH_UNSUPPORTED' });
+ }
+ if (Number(params.chunks ?? 1) > 1 || params.musicVideo || params.fableLoom) {
+ throw new ServerError('A render batch produces separate videos. Use a single render for chained clips or scene delivery.', { status: 400, code: 'VIDEO_BATCH_CONFLICT' });
+ }
+ if (params.seed != null && params.seed !== '') {
+ const seed = Number(params.seed);
+ if (!Number.isSafeInteger(seed) || seed < 0 || seed + count - 1 > MAX_SEED) {
+ throw new ServerError(`The batch seeds must stay between 0 and ${MAX_SEED}. Lower the starting seed or batch size.`, { status: 400, code: 'VIDEO_BATCH_SEED_RANGE' });
+ }
+ }
+}
+
+export function planVideoBatch({ jobId, batchSize, seed }) {
+ const random = seed == null || seed === '';
+ return Array.from({ length: batchSize }, (_, index) => ({
+ id: index === 0 ? jobId : randomUUID(),
+ filename: index === 0 ? `${jobId}.mp4` : `${jobId}-${index + 1}.mp4`,
+ seed: random ? randomInt(0, MAX_SEED + 1) : Number(seed) + index,
+ index,
+ }));
+}
diff --git a/server/services/videoGen/batch.test.js b/server/services/videoGen/batch.test.js
new file mode 100644
index 0000000000..c1a8d76b6a
--- /dev/null
+++ b/server/services/videoGen/batch.test.js
@@ -0,0 +1,29 @@
+import { describe, expect, it, vi } from 'vitest';
+import { randomInt } from 'node:crypto';
+import { planVideoBatch, validateVideoBatch } from './batch.js';
+
+vi.mock('node:crypto', async (original) => ({ ...await original(), randomInt: vi.fn() }));
+const model = { runtime: 'minimax_h3' };
+
+describe('warm video batch request contract', () => {
+ it('draws separately for every random render and preserves zero as an incrementing seed', () => {
+ vi.mocked(randomInt).mockReturnValueOnce(85).mockReturnValueOnce(2).mockReturnValueOnce(99);
+ expect(planVideoBatch({ jobId: 'job', batchSize: 3 }).map((item) => item.seed)).toEqual([85, 2, 99]);
+ expect(randomInt).toHaveBeenCalledTimes(3);
+ expect(planVideoBatch({ jobId: 'job', batchSize: 3, seed: 0 }).map((item) => item.seed)).toEqual([0, 1, 2]);
+ expect(randomInt).toHaveBeenCalledTimes(3);
+ });
+
+ it('rejects invalid counts, overflowing seeds and unsupported dispatch before rendering', () => {
+ for (const batchSize of [0, -1, 1.5, 21, NaN]) {
+ expect(() => validateVideoBatch({ batchSize }, model)).toThrow(/Batch size/);
+ }
+ expect(() => validateVideoBatch({ batchSize: 2, seed: 2 ** 32 - 1 }, model)).toThrow(/batch seeds/);
+ expect(() => validateVideoBatch({ batchSize: 2, seed: 2 ** 32 - 2 }, model)).not.toThrow();
+ for (const fields of [{ backend: 'fal' }, { mediaProviderPeerId: 'peer' }, { chunks: 2 }, { fableLoom: {} }, { musicVideo: {} }]) {
+ expect(() => validateVideoBatch({ batchSize: 2, ...fields }, model)).toThrow();
+ }
+ expect(() => validateVideoBatch({ batchSize: 2 }, { runtime: 'ltx25' })).toThrow(/require a local/);
+ expect(() => validateVideoBatch({}, { runtime: 'ltx25' })).not.toThrow();
+ });
+});
diff --git a/server/services/videoGen/chainedVideo.js b/server/services/videoGen/chainedVideo.js
index 7291b5347b..c9b07556f4 100644
--- a/server/services/videoGen/chainedVideo.js
+++ b/server/services/videoGen/chainedVideo.js
@@ -62,6 +62,9 @@ import { generateVideo, resolveVideoModel, defaultVideoModelId } from './generat
// `prompt`. It is destructured out of `rest` on purpose so the per-chunk
// generateVideo() calls below never receive the whole list.
export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames, jobId: outerJobId, ...rest }) {
+ if (Number(chunks) > 1 && Number(rest.batchSize) > 1) {
+ throw new ServerError('A render batch cannot be combined with chained clips.', { status: 400, code: 'VIDEO_BATCH_CONFLICT' });
+ }
const totalChunks = Number(chunks) || 1;
if (totalChunks === 1) {
return generateVideo({ jobId: outerJobId, ...rest });
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index 72729d6043..69a7e1c5a5 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -1,3 +1,4 @@
+import { planVideoBatch, supportsWarmVideoBatch, validateVideoBatch } from './batch.js';
import { normalizeVideoFailure } from '../../lib/videoFailure.js';
/**
* Video Gen — local render runner (mlx_video on macOS, diffusers on Windows).
@@ -124,6 +125,7 @@ export const VIDEO_MODELS = Object.fromEntries(getVideoModels().map((m) => [m.id
// the client renders no picker instead of a one-entry select.
const decorateVideoModel = (m) => (m ? {
...m,
+ supportsWarmBatch: supportsWarmVideoBatch(m),
lastFrameAnchored: modelAnchorsLastFrame(m),
runtimeLoraCapable: byovRuntimeLoraCapable(m.runtime),
textEncoderOptions: publicVideoTextEncoderOptions(m),
@@ -150,7 +152,7 @@ export const listVideoModels = () => getVideoModels().map(decorateVideoModel);
export const defaultVideoModelId = (capabilities) => getDefaultVideoModelId(capabilities);
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = null, draftDecode = null, visualConditioning = null, hidden = false, displaySleep = null, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, batchSize = 1, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = null, draftDecode = null, visualConditioning = null, hidden = false, displaySleep = null, jobId: providedJobId = null }) {
uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -160,6 +162,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const { modelId: selectedModelId, model } = await resolveVideoModelSelection(modelId, { resolveModel: resolveVideoModel });
modelId = selectedModelId;
+ validateVideoBatch({ batchSize, seed }, model);
if (!model) throw new ServerError(`Unknown video model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
if (!isHardwareCompatible(model.hardwareCompatibility)) {
throw new ServerError(
@@ -410,7 +413,8 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
: 64;
const w = Math.floor(Number(width) / resolutionStep) * resolutionStep;
const h = Math.floor(Number(height) / resolutionStep) * resolutionStep;
- const actualSeed = seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);
+ const batch = batchSize > 1 ? planVideoBatch({ jobId, batchSize, seed }) : null;
+ const actualSeed = batch ? batch[0].seed : seed != null && seed !== '' ? Number(seed) : Math.floor(Math.random() * 2147483647);
// User-facing speed profile (#4875). Resolved BEFORE the sampler so it can
// drive steps/guidance/stage-2 together — a half-applied schedule would make
// the profile's speed claim false. `null` whenever the request is
@@ -695,6 +699,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const createdAt = new Date().toISOString();
const meta = {
id: jobId,
+ ...(batch ? { batchId: jobId, batchSize, batchIndex: 0 } : {}),
prompt,
negativePrompt,
modelId,
@@ -870,6 +875,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
ffmpegPath: ffmpeg,
ffprobePath: ffprobe,
}));
+ if (batch) args.push('--batch-seeds', JSON.stringify(batch.map((item) => item.seed)));
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to build video gen args';
@@ -884,6 +890,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
await spawnAndWatchVideo({
jobId,
+ batch,
// Keeps this render's ETA samples in its own cost bucket — a speed profile
// changes the slope, not just the step count.
speedProfileId: speedProfile?.id ?? null,
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.js
index a7537f5e04..eb14492e97 100644
--- a/server/services/videoGen/generateVideoHelpers.js
+++ b/server/services/videoGen/generateVideoHelpers.js
@@ -544,11 +544,12 @@ export function bufferChildExit(proc) {
* @param {object} ctx.meta - the history-entry metadata built up-front
* @param {number} ctx.actualSeed
* @param {(mutator: (h: Array) => Array) => Promise<Array>} ctx.mutateHistory - serialized read-modify-write on the shared history file (mutateVideoHistory)
+ * @param {boolean} [ctx.terminal=true] - False persists a batch member without completing its queue job.
* @param {number} [ctx.startedAtMs] - Date.now() captured just before the child
* spawned. Defaults to `job.renderStartedAtMs`, which generateVideo stamps.
*/
-export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory, startedAtMs = job?.renderStartedAtMs }) {
- job.status = 'complete';
+export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory, startedAtMs = job?.renderStartedAtMs, terminal = true }) {
+ if (terminal) job.status = 'complete';
await optimizeForStreaming(outputPath);
const thumbnail = await generateThumbnail(outputPath, jobId);
// Serialized append through the shared history tail so a concurrent write
@@ -592,7 +593,9 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,
return history;
});
console.log(`✅ Video generated [${jobId.slice(0, 8)}]: ${filename}`);
- broadcastSse(job, { type: 'complete', result: { filename, seed: actualSeed, thumbnail, path: `/data/videos/${filename}` } });
- videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });
+ if (terminal) {
+ broadcastSse(job, { type: 'complete', result: { filename, seed: actualSeed, thumbnail, path: `/data/videos/${filename}` } });
+ videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });
+ }
return thumbnail;
}
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 43b488ec56..9c139903c0 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -5792,3 +5792,63 @@ describe('generateVideo — MiniMax H3 draft decode (#5423)', () => {
expect(meta.draftDecode).toBeUndefined();
});
});
+
+describe('resident video batches', () => {
+ it.each([
+ { exitCode: 0, outputs: 2, complete: true },
+ { exitCode: 1, outputs: 1, complete: false },
+ { exitCode: 0, outputs: 1, complete: false },
+ { exitCode: null, signal: 'SIGTERM', outputs: 1, complete: false },
+ ])('persists finished outputs and ends the queue job once ($exitCode, $signal, $outputs outputs)', async ({ exitCode, signal = null, outputs, complete }) => {
+ const { EventEmitter } = await import('node:events');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const { atomicWrite } = await import('../../lib/fileUtils.js');
+ const { planVideoBatch } = await import('./batch.js');
+ const { videoJobState } = await import('./jobState.js');
+ const proc = Object.assign(new EventEmitter(), {
+ pid: 12345, exitCode: null, signalCode: null, killed: false,
+ stdout: new EventEmitter(), stderr: new EventEmitter(), kill: vi.fn(),
+ });
+ vi.mocked(spawnDetached).mockResolvedValueOnce(proc);
+ vi.mocked(atomicWrite).mockClear();
+ const jobId = randomUUID();
+ const batch = planVideoBatch({ jobId, batchSize: 2, seed: 0 });
+ const completed = vi.fn();
+ const failed = vi.fn();
+ videoGenEvents.on('completed', completed);
+ videoGenEvents.on('failed', failed);
+ settingsState.acceptedModelTerms = [H3_TERMS];
+ await generateVideo({
+ jobId, prompt: 'Example shot', batchSize: 2, seed: 0,
+ modelId: 'minimax_h3_8bit', width: 1344, height: 768,
+ numFrames: 124, fps: 24, displaySleep: false,
+ });
+ const job = videoJobState.jobs.get(jobId);
+ const args = vi.mocked(spawnDetached).mock.calls.at(-1)[1];
+ expect(JSON.parse(args[args.indexOf('--batch-seeds') + 1])).toEqual([0, 1]);
+ if (complete) vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ for (const item of batch.slice(0, outputs)) {
+ proc.stdout.emit('data', Buffer.from(JSON.stringify({ video_path: join(MOCK_PATHS.videos, item.filename), batch_index: item.index, seed: item.seed }) + '\n'));
+ if (complete && item.index === 0) {
+ await vi.advanceTimersByTimeAsync(40_001);
+ vi.useRealTimers();
+ expect(proc.kill).not.toHaveBeenCalled();
+ }
+ }
+ await vi.waitFor(() => expect(atomicWrite).toHaveBeenCalledTimes(outputs));
+ expect(job.status).toBe('running');
+ expect(completed).not.toHaveBeenCalled();
+ proc.exitCode = exitCode;
+ proc.signalCode = signal;
+ proc.emit('close', exitCode, signal);
+ await vi.waitFor(() => expect(complete ? completed : failed).toHaveBeenCalledTimes(1));
+ expect(complete ? failed : completed).not.toHaveBeenCalled();
+ const saved = vi.mocked(atomicWrite).mock.calls.at(-1)[1];
+ expect(saved.filter((item) => item.batchId === jobId)).toHaveLength(outputs);
+ expect(saved[0].seed).toBe(outputs - 1);
+ expect(saved[0].id).toMatch(/^[a-f0-9-]{36}$/);
+ const terminal = (complete ? completed : failed).mock.calls[0][0];
+ expect(terminal.results.map((item) => item.seed)).toEqual(complete ? [0, 1] : [0]);
+ expect(proc.kill).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/videoGen/prepareParams.js b/server/services/videoGen/prepareParams.js
index e96350a5c1..c9de94672f 100644
--- a/server/services/videoGen/prepareParams.js
+++ b/server/services/videoGen/prepareParams.js
@@ -69,6 +69,7 @@ import {
// module mock local.js wholesale, and a mocked rule table would assert nothing.
import { videoModeContractError, videoChainUnsupportedError, videoReferenceModeError } from './modeContract.js';
import { resolveByovRuntimeLoraCapable, videoLoraUnsupportedError } from './runtimes.js';
+import { validateVideoBatch } from './batch.js';
import { audioDurationToFrames } from './audioDuration.js';
// Retries reuse persisted worker parameters instead of passing through the
@@ -102,6 +103,7 @@ export async function validateVideoRetryParams(params = {}) {
&& !supportsVideoTextEncoder(model, params.textEncoderId)) {
throw videoTextEncoderUnsupportedError(model, params.textEncoderId);
}
+ validateVideoBatch(params, model);
const mode = params.mode || (params.sourceImagePath ? 'image' : 'text');
const modeError = videoModeContractError({
model,
@@ -314,6 +316,7 @@ export async function prepareVideoGenParams({ body, uploads, localOnlyParamKeys
capabilities,
effectiveModel.hardwareRequirements,
);
+ validateVideoBatch({ ...body, backend }, effectiveModel);
// Validate modelId before staging (when supplied). Without this the queue
// would happily accept a typo'd modelId and fail asynchronously inside
// the worker — leaving a persisted, doomed queue entry.
diff --git a/server/services/videoGen/requestFields.js b/server/services/videoGen/requestFields.js
index ef8acb395c..255105519e 100644
--- a/server/services/videoGen/requestFields.js
+++ b/server/services/videoGen/requestFields.js
@@ -7,6 +7,7 @@ export const VIDEO_GEN_LOCAL_ONLY_FIELDS = Object.freeze({
STEPS: 'steps',
GUIDANCE_SCALE: 'guidanceScale',
SEED: 'seed',
+ BATCH_SIZE: 'batchSize',
IMAGE_STRENGTH: 'imageStrength',
I2V_REFERENCE_MODE: 'i2vReferenceMode',
TILING: 'tiling',
diff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.js
index 07a1ef0671..25bea4ed5c 100644
--- a/server/services/videoGen/spawnWatch.js
+++ b/server/services/videoGen/spawnWatch.js
@@ -50,6 +50,7 @@ const MUXING_DONE_RE = /\[Decoding video \+ audio \+ muxing\]\s+done in/i;
export async function spawnAndWatchVideo({
jobId,
+ batch = null,
speedProfileId = null,
cleanupTempFiles,
stepwiseDir,
@@ -256,6 +257,40 @@ export async function spawnAndWatchVideo({
// Returns true for a recognized progress/status/noise line (suppress raw
// logging), false for an unhandled line worth raw-logging.
const handleLine = makeVideoGenLineHandler({ job, jobId, pythonNoiseRe: PYTHON_NOISE_RE });
+ const batchResults = [];
+ let outputTail = Promise.resolve();
+ let batchError = null;
+ let receivedOutputs = 0;
+ const stopFailedBatch = (err) => {
+ batchError ||= err;
+ try { proc.kill('SIGTERM'); } catch (killError) {
+ console.error(`❌ Video batch could not stop [${jobId.slice(0, 8)}]: ${killError.message}`);
+ }
+ };
+ const acceptBatchOutput = (parsed) => {
+ const item = batch[receivedOutputs];
+ const itemFilename = item?.filename;
+ const itemPath = itemFilename && join(PATHS.videos, itemFilename);
+ if (!item || parsed.batch_index !== item.index || parsed.seed !== item.seed || parsed.video_path !== itemPath) {
+ stopFailedBatch(new Error('Video batch returned an unexpected output or seed.'));
+ return;
+ }
+ receivedOutputs += 1;
+ outputTail = outputTail.then(async () => {
+ const thumbnail = await finalizeGeneratedVideo({
+ job, jobId: item.id, outputPath: itemPath, filename: itemFilename,
+ meta: { ...meta, id: item.id, filename: itemFilename, seed: item.seed, batchIndex: item.index },
+ actualSeed: item.seed, mutateHistory: mutateVideoHistory,
+ // Batch timings include shared startup and cannot train single-render ETAs.
+ startedAtMs: null, terminal: false,
+ });
+ batchResults.push({ filename: itemFilename, seed: item.seed, thumbnail, path: `/data/videos/${itemFilename}` });
+ const message = `Saved ${batchResults.length}/${batch.length} videos`;
+ broadcastSse(job, { type: 'status', message });
+ videoGenEvents.emit('status', { generationId: jobId, message });
+ }).catch(stopFailedBatch);
+ if (receivedOutputs === batch.length) armCompletionWatchdog();
+ };
// Per-stream line readers carry the partial trailing line across chunk
// boundaries and decode through a StringDecoder, so a marker (or multibyte
@@ -268,6 +303,10 @@ export async function spawnAndWatchVideo({
// for the result metadata; otherwise raw-log so we can debug failures.
try {
const parsed = JSON.parse(line);
+ if (parsed.video_path && batch) {
+ acceptBatchOutput(parsed);
+ return;
+ }
if (parsed.video_path) {
job.resultJson = parsed;
// The result JSON is the strongest "work is done" signal — arm the
@@ -278,7 +317,7 @@ export async function spawnAndWatchVideo({
} catch { /* not JSON */ }
// Some runtimes don't print the result JSON but do log the final
// decode+mux line right before they should exit — treat it the same way.
- if (MUXING_DONE_RE.test(line)) armCompletionWatchdog();
+ if (!batch && MUXING_DONE_RE.test(line)) armCompletionWatchdog();
console.log(`🐍-out [${jobId.slice(0, 8)}] ${line}`);
});
const stderrReader = createLineReader((raw) => {
@@ -348,7 +387,10 @@ export async function spawnAndWatchVideo({
// output file is already on disk and non-empty: the render wrote its
// result, but the child hung during teardown. A kill with no output on
// disk still fails loudly below.
- const watchdogSuccess = isWatchdogSuccess({ completionWatchdogFired, signal, outputPath });
+ await outputTail;
+ if (batchError) throw batchError;
+ const watchdogSuccess = (!batch || batchResults.length === batch.length)
+ && isWatchdogSuccess({ completionWatchdogFired, signal, outputPath });
if (code !== 0 && !watchdogSuccess) {
job.status = 'error';
@@ -377,14 +419,23 @@ export async function spawnAndWatchVideo({
const diagnostic = failure?.summary || failure?.cause;
reason = `Exit code ${code}${diagnostic ? `: ${diagnostic}` : ''}`;
}
+ if (batch) reason += ` (${batchResults.length}/${batch.length} videos saved to history)`;
console.log(`❌ Video generation failed [${jobId.slice(0, 8)}]: ${reason}`);
broadcastSse(job, { type: 'error', error: `Generation failed: ${reason}` });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: missingPyModule ? normalizeVideoFailure(reason) : failure });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: missingPyModule ? normalizeVideoFailure(reason) : failure, ...(batch ? { results: batchResults } : {}) });
} else {
if (watchdogSuccess) {
console.log(`⚠️ video child force-killed (completion teardown hang) — output is intact [${jobId.slice(0, 8)}]`);
}
- await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory: mutateVideoHistory });
+ if (batch) {
+ if (batchResults.length !== batch.length) throw new Error(`Video batch stopped after ${batchResults.length}/${batch.length} outputs.`);
+ job.status = 'complete';
+ const result = { ...batchResults[0], results: batchResults };
+ broadcastSse(job, { type: 'complete', result });
+ videoGenEvents.emit('completed', { generationId: jobId, ...result });
+ } else {
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory: mutateVideoHistory });
+ }
}
} catch (err) {
// Finalize/teardown threw — fail the job loudly instead of crashing the
@@ -393,7 +444,7 @@ export async function spawnAndWatchVideo({
job.status = 'error';
console.error(`❌ Video close handler failed [${jobId.slice(0, 8)}]: ${err.message}`);
broadcastSse(job, { type: 'error', error: `Generation failed: ${err.message}` });
- videoGenEvents.emit('failed', { generationId: jobId, error: err.message, failure: normalizeVideoFailure(err, { prompts: [meta?.prompt, meta?.negativePrompt] }) });
+ videoGenEvents.emit('failed', { generationId: jobId, error: err.message, failure: normalizeVideoFailure(err, { prompts: [meta?.prompt, meta?.negativePrompt] }), ...(batch ? { results: batchResults } : {}) });
} finally {
// A prompt-encode relaunch returns before this finalizer, deliberately
// leaving the display asleep while its replacement owns the GPU.
@@ -592,7 +643,7 @@ export async function spawnAndWatchVideo({
// has never measured a render on this model — an explicit "no estimate"
// sentinel the UI must render as "unknown", never as 0 or a guess. Stamped
// on the job so every progress frame can carry it alongside step progress.
- const etaEstimate = estimateRenderMs({
+ const etaEstimate = batch ? null : estimateRenderMs({
history: await loadHistory(),
modelId,
width: w,
diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.js
index 6f1d761515..2d9fc33330 100644
--- a/server/services/videoGen/submitJob.js
+++ b/server/services/videoGen/submitJob.js
@@ -54,6 +54,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
['IC-LoRA references', body.icReferenceVideoIds?.length || body.icReferenceImageFiles?.length],
['LoRA weights', body.loraFilenames?.length],
['chained chunks', body.chunks > 1],
+ ['warm render batches', body.batchSize > 1],
['the Grok backend', body.backend === 'grok'],
['a FableLoom scene tag', body.fableLoom],
// Inspire is a per-runtime capability the caller cannot prove for a peer.
@@ -273,6 +274,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
steps: body.steps,
guidanceScale: body.guidanceScale,
seed: body.seed,
+ ...(body.batchSize > 1 ? { batchSize: body.batchSize } : {}),
tiling: body.tiling || 'auto',
// Default-valued delivery controls stay absent from persisted params so a
// resumed form cannot restore a knob that never changed the render.