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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: enable LTX block streaming to cut transformer memory on tight machines (#6499)
[._.]/ Adam Eivy3ce29e4098ff
diff --git a/client/src/components/videoGen/AdvancedParamsPanel.jsx b/client/src/components/videoGen/AdvancedParamsPanel.jsxindex f9eaad7a82..5f0167ac18 100644--- a/client/src/components/videoGen/AdvancedParamsPanel.jsx+++ b/client/src/components/videoGen/AdvancedParamsPanel.jsx@@ -18,6 +18,7 @@ import {} from '../../lib/videoGenParams.js';import { VIDEO_TILING_OPTIONS } from '../../lib/videoTilingOptions';import { isLtx2FamilyRuntime } from '../../lib/runnerFamilies';+import { DEFAULT_VIDEO_STREAMING_MODE, VIDEO_STREAMING_MODE_OPTIONS } from '../../lib/videoStreamingMode.js';import {I2V_REFERENCE_MODE_OPTIONS, DEFAULT_I2V_REFERENCE_MODE,normalizeI2vReferenceMode, runtimeSupportsI2vReferenceMode,@@ -39,6 +40,7 @@ export default function AdvancedParamsPanel({guidanceScale, onGuidanceScaleChange,speedProfileId = DEFAULT_SPEED_PROFILE_ID, onSpeedProfileChange,draftDecode = DEFAULT_DRAFT_DECODE_ID, onDraftDecodeChange, draftDecodeLocked = false,+ streamingMode = DEFAULT_VIDEO_STREAMING_MODE, onStreamingModeChange,imageStrength, onImageStrengthChange,i2vReferenceMode = DEFAULT_I2V_REFERENCE_MODE, onI2vReferenceModeChange,effectiveImageStrength = null,@@ -322,6 +324,28 @@ export default function AdvancedParamsPanel({</FormField>)}+ {/* Block streaming (#6499) — LTX-2/2.5 MLX only, every other runtime+ ignores the flag by construction. Auto initially streams on a+ tight-memory machine; the render bridge inspects the pinned+ pipeline and this machine's physical RAM, so the client offers no+ per-model capability table for it. */}+ {isLtx2FamilyRuntime(currentModel?.runtime) && (+ <FormField label="Memory" labelClassName="block text-xs font-medium text-gray-400 mb-1">+ <select+ value={streamingMode}+ onChange={(e) => onStreamingModeChange?.(e.target.value)}+ className={inputCls}+ >+ {VIDEO_STREAMING_MODE_OPTIONS.map((option) => (+ <option key={option.value} value={option.value}>{option.label}</option>+ ))}+ </select>+ <p className="mt-1 text-xs text-gray-500">+ {VIDEO_STREAMING_MODE_OPTIONS.find((o) => o.value === streamingMode)?.description || ''}+ </p>+ </FormField>+ )}+{showSpeedProfiles && (<FormField label="Speed" labelClassName="block text-xs font-medium text-gray-400 mb-1"><selectdiff --git a/client/src/hooks/useVideoGenFieldState.js b/client/src/hooks/useVideoGenFieldState.jsindex e14bf5059e..4af6375f67 100644--- a/client/src/hooks/useVideoGenFieldState.js+++ b/client/src/hooks/useVideoGenFieldState.js@@ -8,6 +8,7 @@ import {DEFAULT_SPEED_PROFILE_ID,STOCK_TEXT_ENCODER_ID,} from '../lib/videoGenParams.js';+import { DEFAULT_VIDEO_STREAMING_MODE } from '../lib/videoStreamingMode.js';/*** Owns the mutable fields and lifecycle refs for the VideoGen form.@@ -56,6 +57,7 @@ export function useVideoGenFieldState({const [textEncoderId, setTextEncoderId] = useState(STOCK_TEXT_ENCODER_ID);const [speedProfileId, setSpeedProfileId] = useState(DEFAULT_SPEED_PROFILE_ID);const [draftDecode, setDraftDecode] = useState(DEFAULT_DRAFT_DECODE_ID);+ const [streamingMode, setStreamingMode] = useState(DEFAULT_VIDEO_STREAMING_MODE);const [disableAudio, setDisableAudio] = useState(false);const [selectedLoras, setSelectedLoras] = useState([]);const [noMusic, setNoMusic] = useState(false);@@ -126,6 +128,7 @@ export function useVideoGenFieldState({sizeManuallySetRef,speedProfileId, setSpeedProfileId,draftDecode, setDraftDecode,+ streamingMode, setStreamingMode,staleModelToastRef,steps, setSteps,stylePreset, setStylePreset,diff --git a/client/src/hooks/useVideoGenForm.js b/client/src/hooks/useVideoGenForm.jsindex 0dd2d01a20..7a27650aaf 100644--- a/client/src/hooks/useVideoGenForm.js+++ b/client/src/hooks/useVideoGenForm.js@@ -23,6 +23,7 @@ import {DEFAULT_DRAFT_DECODE_ID, draftDecodeOptionsForModel,resolveDraftDecodeForModel, draftDecodeFromRecord,} from '../lib/videoGenParams.js';+import { videoStreamingModeFromRecord } from '../lib/videoStreamingMode.js';import { useVideoGenFieldState } from './useVideoGenFieldState.js';import { useVideoGenSubmitFlow } from './useVideoGenSubmitFlow.js';import { useVideoGenValidation } from './useVideoGenValidation.js';@@ -135,6 +136,7 @@ export function useVideoGenForm({sizeManuallySetRef,speedProfileId, setSpeedProfileId,draftDecode, setDraftDecode,+ streamingMode, setStreamingMode,staleModelToastRef,steps, setSteps,stylePreset, setStylePreset,@@ -1082,6 +1084,7 @@ export function useVideoGenForm({setTextEncoderId(textEncoderIdFromRecord(item.textEncoderId));setSpeedProfileId(speedProfileIdFromRecord(item.speedProfileId));setDraftDecode(draftDecodeFromRecord(item.draftDecode));+ setStreamingMode(videoStreamingModeFromRecord(item.streamingMode));// disableAudio: always set explicitly (true/false) so the toggle reliably// matches the remixed render. Skipping the false branch would leave the// toggle stuck ON when the user remixes a clip that had audio enabled.@@ -1201,6 +1204,7 @@ export function useVideoGenForm({setTextEncoderId(textEncoderIdFromRecord(p.textEncoderId));setSpeedProfileId(speedProfileIdFromRecord(p.speedProfileId));setDraftDecode(draftDecodeFromRecord(p.draftDecode));+ setStreamingMode(videoStreamingModeFromRecord(p.streamingMode));if (typeof p.disableAudio === 'boolean') setDisableAudio(p.disableAudio);if (p.mode === 'grok') {// Grok job: 'grok' is the queue discriminator, not a semantic video@@ -1300,7 +1304,7 @@ export function useVideoGenForm({prompt, negativePrompt, stylePreset, selectedUniverse,width, height, mode, sourceImageFile, sourceImageUpload,numFrames, fps, steps, guidanceScale, seed, batchSize,- currentModel, models, modelId, tiling, textEncoderId, speedProfileId, draftDecode,+ currentModel, models, modelId, tiling, textEncoderId, speedProfileId, draftDecode, streamingMode,disableAudio, noMusic, imageStrength, i2vReferenceMode,keyframesActive, keyframes, loraFamily, selectedLoras,lastImageFile, lastImageUpload, extendFromVideoId, audioFile,@@ -1353,6 +1357,7 @@ export function useVideoGenForm({textEncoderId, setTextEncoderId, textEncoderOptions,speedProfileId, setSpeedProfileId,draftDecode, setDraftDecode, draftDecodeOptions,+ streamingMode, setStreamingMode,disableAudio, setDisableAudio,noMusic, setNoMusic,// Framesdiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex af5105970c..dacc49322f 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -95,6 +95,7 @@ grep -i "what you want to do" client/src/lib/README.md| `videoGenResolutions.js` | Shared resolution presets/default for video generation, model-specific preset/default resolvers (for native canvases such as MiniMax H3), and `snapAspectToImage()` to pick the closest-aspect preset for an I2V source. || `videoGenSubmission.js` | Builds the local, Grok, and federated video-generation request bodies from validated form state, including prompt envelopes and empty-value wire sentinels. || `videoReferenceModes.js` | Re-export of `server/lib/videoReferenceModes.js` — the i2v reference-mode vocabulary and its per-mode rules. |+| `videoStreamingMode.js` | Re-export of `server/lib/videoStreamingMode.js` — the block-streaming request vocabulary (`auto` \| `resident` \| `stream`) for LTX-2/2.5 MLX local video renders (#6499). || `videoRenderPhase.js` | Video render phase → named progress step (#5872). `resolveVideoRenderSteps({ generating, phase, progressPct, remote })` → `{ activeId, steps: [{ id, label, state: 'done'|'active'|'pending' }] }`, collapsing the runners' fine-grained `STAGE:` vocabulary (`load-transformer`, `encode-prompt`, `sampling`, `mux`, …) onto six steps a person can read — the queue's own `queued` is one of them, so a caller needs no separate flag. Family prefixes (`download-*`, `load-*`, `wan-*`, …) absorb markers a future runner adds; `videoRenderStepFor(phase, { remote })` returns `null` for a genuinely unknown one, never step 0. `remote: true` swaps in the four-step provider ladder (`REMOTE_VIDEO_RENDER_STEPS`: queued → submit → render → fetch) for a render an external API owns, where the local weight/load/encode steps describe work this machine never does. Consumed by `components/videoGen/RenderStatusCard.jsx`. || `videoTilingOptions.js` | `VIDEO_TILING_OPTIONS` (the `<select>` rows), `VIDEO_TILING_ENUM_SET` (the value-only Set), and `normalizeVideoTiling` (omit legacy/unknown values). Single source consumed by `VideoGen.jsx`, saved-video normalization, and Remix/requeue callers. Mirrors the server's `z.enum` in `server/routes/videoGen.js`. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 2e4e5be16a..2c8490a527 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -70,6 +70,7 @@ export * from './videoGenResolutions.js';export * from './videoGenSubmission.js';export * from './videoReferenceModes.js';export * from './videoRenderPhase.js';+export * from './videoStreamingMode.js';export * from './videoTilingOptions.js';export * from './wrImageDefaults.js';diff --git a/client/src/lib/videoGenSubmission.js b/client/src/lib/videoGenSubmission.jsindex 589e0d06a9..bbb08f5fbc 100644--- a/client/src/lib/videoGenSubmission.js+++ b/client/src/lib/videoGenSubmission.js@@ -15,6 +15,7 @@ import {DEFAULT_DRAFT_DECODE_ID,resolveDraftDecodeForModel,} from './videoGenParams.js';+import { isDefaultVideoStreamingMode } from './videoStreamingMode.js';// The form owns state transitions and validation. This module owns the three// request contracts the video route accepts: Grok, federated, and local.@@ -50,7 +51,7 @@ export function buildVideoGenSubmission({prompt, negativePrompt, stylePreset, selectedUniverse,width, height, mode, sourceImageFile, sourceImageUpload,numFrames, fps, steps, guidanceScale, seed, batchSize = 1,- currentModel, models, modelId, tiling, textEncoderId, speedProfileId, draftDecode,+ currentModel, models, modelId, tiling, textEncoderId, speedProfileId, draftDecode, streamingMode,disableAudio, noMusic, imageStrength, i2vReferenceMode,keyframesActive, keyframes, loraFamily, selectedLoras,lastImageFile, lastImageUpload, extendFromVideoId, audioFile,@@ -176,6 +177,15 @@ export function buildVideoGenSubmission({draftDecode: resolveDraftDecodeForModel(draftDecode, currentModel, models) === DEFAULT_DRAFT_DECODE_ID? undefined: draftDecode,+ // Block-streaming request (#6499). Sent only when it is both a real+ // choice (this model's runtime is LTX-2/2.5 MLX — every other runtime+ // ignores the flag by construction, so sending it there would just be a+ // stale value the server logs and drops) and a non-default one — a+ // model switch away from LTX2 or back to Auto both leave the payload+ // absent, so an unswapped render stays byte-identical.+ streamingMode: (isLtx2FamilyRuntime(currentModel?.runtime) && !isDefaultVideoStreamingMode(streamingMode))+ ? streamingMode+ : undefined,disableAudio: effectiveDisableAudio ? 'true' : 'false',// Only meaningful on a runtime the GPU-watchdog mitigation applies to —// absent otherwise so an unrelated model's render never carries a stalediff --git a/client/src/lib/videoGenSubmission.test.js b/client/src/lib/videoGenSubmission.test.jsnew file mode 100644index 0000000000..74c0795e01--- /dev/null+++ b/client/src/lib/videoGenSubmission.test.js@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';+import { buildVideoGenSubmission } from './videoGenSubmission.js';++// #6499 — block streaming is a request-only field sent to the LOCAL backend,+// and only when it is both a real choice (the current model actually runs on+// an LTX-2/2.5 MLX runtime) and a non-default one ('auto' — the bridge's own+// default). Every other field the local payload needs is filled with the+// minimal values that keep the shared prompt/mode helpers from throwing.+const baseArgs = (overrides = {}) => ({+ isGrok: false, isFal: false, isReactor: false, remoteSubmissionFields: null,+ prompt: 'a fox running through a forest',+ negativePrompt: '',+ width: 768, height: 512, mode: 'text',+ numFrames: 121, fps: 24, steps: '', guidanceScale: '', seed: '', batchSize: 1,+ models: [],+ tiling: 'auto', textEncoderId: '', speedProfileId: '', draftDecode: '',+ disableAudio: false, noMusic: false, imageStrength: '', i2vReferenceMode: 'anchor',+ keyframesActive: false, keyframes: [], loraFamily: null, selectedLoras: [],+ icModeActive: false, icImageKind: false, icReferenceImageFiles: [], icStrength: 1, icSkipStage2: false,+ chainingActive: false, chunks: 1, chunkPrompts: [], contextFrames: 0,+ ...overrides,+});++describe('buildVideoGenSubmission — block streaming request (#6499)', () => {+ it('sends a non-default mode when the current model runs an LTX-2/2.5 MLX runtime', () => {+ const payload = buildVideoGenSubmission(baseArgs({+ currentModel: { runtime: 'ltx25' },+ streamingMode: 'stream',+ }));+ expect(payload.backend).toBe('local');+ expect(payload.streamingMode).toBe('stream');+ });++ it('omits the field for the default (auto) mode, even on an LTX-2/2.5 model', () => {+ const payload = buildVideoGenSubmission(baseArgs({+ currentModel: { runtime: 'ltx2' },+ streamingMode: 'auto',+ }));+ expect(payload.streamingMode).toBeUndefined();+ });++ it('omits the field entirely when the current model does not run an LTX-2/2.5 MLX runtime', () => {+ const payload = buildVideoGenSubmission(baseArgs({+ currentModel: { runtime: 'mlx_video' },+ streamingMode: 'stream',+ }));+ expect(payload.streamingMode).toBeUndefined();+ });++ it('omits the field when no model is selected yet', () => {+ const payload = buildVideoGenSubmission(baseArgs({+ currentModel: null,+ streamingMode: 'stream',+ }));+ expect(payload.streamingMode).toBeUndefined();+ });+});diff --git a/client/src/lib/videoStreamingMode.js b/client/src/lib/videoStreamingMode.jsnew file mode 100644index 0000000000..8ce878a621--- /dev/null+++ b/client/src/lib/videoStreamingMode.js@@ -0,0 +1,13 @@+/**+ * Re-export of `server/lib/videoStreamingMode.js` — the block-streaming mode+ * vocabulary for LTX-2/2.5 MLX local video renders (#6499).+ */+export {+ DEFAULT_VIDEO_STREAMING_MODE,+ VIDEO_STREAMING_MODES,+ VIDEO_STREAMING_MODE_OPTIONS,+ isDefaultVideoStreamingMode,+ isKnownVideoStreamingMode,+ videoStreamingModeFromRecord,+ videoStreamingModeLabel,+} from '../../../server/lib/videoStreamingMode.js';diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 7278d1e1cc..d3935d2b33 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,+ streamingMode, setStreamingMode,batchSize, setBatchSize,seed, setSeed, handleRandomSeed, tiling, setTiling,textEncoderId, setTextEncoderId, textEncoderOptions,@@ -1782,6 +1783,7 @@ export default function VideoGen() {speedProfileId={speedProfileId} onSpeedProfileChange={setSpeedProfileId}draftDecode={draftDecode} onDraftDecodeChange={setDraftDecode}draftDecodeLocked={deliveryModelSelected}+ streamingMode={streamingMode} onStreamingModeChange={setStreamingMode}imageStrength={imageStrength} onImageStrengthChange={setImageStrength}i2vReferenceMode={i2vReferenceMode} onI2vReferenceModeChange={setI2vReferenceMode}effectiveImageStrength={effectiveImageStrength}diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pyindex 0216b1613e..ceef11df96 100644--- a/scripts/generate_ltx2.py+++ b/scripts/generate_ltx2.py@@ -720,6 +720,14 @@ def parse_args() -> argparse.Namespace:"reasserted before every render. Omit to derive a conservative ""ceiling from physical memory. PORTOS_MLX_CACHE_LIMIT_MB sets the ""same knob ambiently; this flag wins over it.")+ p.add_argument("--streaming-mode", choices=STREAMING_MODE_CHOICES, default="auto",+ help="Block-streaming policy for the pipeline's transformer (#6499): "+ "'resident' always materializes it (pre-#6499 behavior), 'stream' "+ "always streams blocks from disk — and REFUSES before loading any "+ "weights on a mode whose pinned pipeline has no streaming parameter "+ "(Extend at this pin) — and 'auto' (default) streams on a machine at "+ "or below the auto-stream RAM ceiling and stays resident above it or "+ "when physical memory can't be read.")return p.parse_args()@@ -1467,6 +1475,8 @@ def _gemma_kwargs(args: argparse.Namespace) -> dict:def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:"""T2V/I2V path that honors CFG via the dgrauet two-stage pipeline."""TwoStagePipeline = _resolve_pipeline("TI2VidTwoStagesPipeline", "TwoStagePipeline")+ streaming_policy = configure_streaming_policy(args, TwoStagePipeline, "two-stage")+ streaming_kwargs = {"low_ram_streaming": streaming_policy["active"]} if streaming_policy["supports"] else {}emit_status(f"Loading two-stage pipeline ({args.model})…")emit_stage(1, 0, 1, "Loading model")pipe = TwoStagePipeline(@@ -1474,9 +1484,11 @@ def run_two_stage(args: argparse.Namespace, image: str | None = None) -> str:dev_transformer=args.dev_transformer or "transformer-dev.safetensors",distilled_lora=args.distilled_lora or DISTILLED_LORA_LEGACY,distilled_lora_strength=args.lora_strength,+ **streaming_kwargs,**_gemma_kwargs(args),)_prefer_distilled_lora(pipe, args.distilled_lora, args.require_adapter)+ _refuse_if_streaming_distilled_adapter_missing(pipe, streaming_policy["active"])_apply_user_loras(pipe, args.user_lora_specs)bind_output_fps(pipe, args.fps)emit_stage(1, 1, 1, "Loaded")@@ -1507,9 +1519,11 @@ def run_text(args: argparse.Namespace) -> str:if args.cfg_scale is not None:return run_two_stage(args)OneStagePipeline = _resolve_pipeline("TI2VidOneStagePipeline", "TextToVideoPipeline")+ streaming_policy = configure_streaming_policy(args, OneStagePipeline, "one-stage")+ streaming_kwargs = {"low_ram_streaming": streaming_policy["active"]} if streaming_policy["supports"] else {}emit_status(f"Loading T2V pipeline ({args.model})…")emit_stage(1, 0, 1, "Loading model")- pipe = OneStagePipeline(model_dir=args.model, **_gemma_kwargs(args))+ pipe = OneStagePipeline(model_dir=args.model, **streaming_kwargs, **_gemma_kwargs(args))_apply_user_loras(pipe, args.user_lora_specs)bind_output_fps(pipe, args.fps)emit_stage(1, 1, 1, "Loaded")@@ -1529,9 +1543,11 @@ def run_image(args: argparse.Namespace) -> str:if args.cfg_scale is not None:return run_two_stage(args, image=args.image)OneStagePipeline = _resolve_pipeline("TI2VidOneStagePipeline", "ImageToVideoPipeline")+ streaming_policy = configure_streaming_policy(args, OneStagePipeline, "one-stage")+ streaming_kwargs = {"low_ram_streaming": streaming_policy["active"]} if streaming_policy["supports"] else {}emit_status(f"Loading I2V pipeline ({args.model})…")emit_stage(1, 0, 1, "Loading model")- pipe = OneStagePipeline(model_dir=args.model, **_gemma_kwargs(args))+ pipe = OneStagePipeline(model_dir=args.model, **streaming_kwargs, **_gemma_kwargs(args))_apply_user_loras(pipe, args.user_lora_specs)bind_output_fps(pipe, args.fps)emit_stage(1, 1, 1, "Loaded")@@ -1611,6 +1627,8 @@ def run_fflf(args: argparse.Namespace) -> str:# repo renames them.dev_transformer = args.dev_transformer or "transformer-dev.safetensors"distilled_lora = args.distilled_lora or DISTILLED_LORA_LEGACY+ streaming_policy = configure_streaming_policy(args, KeyframeInterpolationPipeline, "keyframe-interpolation")+ streaming_kwargs = {"low_ram_streaming": streaming_policy["active"]} if streaming_policy["supports"] else {}emit_status(f"Loading Keyframe pipeline ({args.model}, dev+lora)…")emit_stage(1, 0, 1, "Loading model")pipe = KeyframeInterpolationPipeline(@@ -1618,9 +1636,11 @@ def run_fflf(args: argparse.Namespace) -> str:dev_transformer=dev_transformer,distilled_lora=distilled_lora,distilled_lora_strength=args.lora_strength,+ **streaming_kwargs,**_gemma_kwargs(args),)_prefer_distilled_lora(pipe, args.distilled_lora)+ _refuse_if_streaming_distilled_adapter_missing(pipe, streaming_policy["active"])_apply_user_loras(pipe, args.user_lora_specs)emit_stage(1, 1, 1, "Loaded")emit_status(f"Interpolating between {len(keyframe_images)} keyframes at indices {keyframe_indices}…")@@ -1656,6 +1676,12 @@ def run_extend(args: argparse.Namespace) -> str:)if not args.extend_from_video:raise SystemExit("--extend-from-video is required for extend mode")+ # RetakePipeline/ExtendPipeline has no streaming parameter at the pins this+ # bridge targets. configure_streaming_policy() still runs — it emits an+ # 'auto' resident explanation and, for an explicit --streaming-mode stream+ # request, refuses HERE, before ExtendPipeline (or its weights) is+ # constructed at all.+ configure_streaming_policy(args, ExtendPipeline, "extend")emit_status(f"Loading Extend pipeline ({args.model})…")emit_stage(1, 0, 1, "Loading model")pipe = ExtendPipeline(model_dir=args.model, **_gemma_kwargs(args))@@ -1714,10 +1740,13 @@ def run_a2v(args: argparse.Namespace) -> str:AudioToVideoPipeline = _resolve_pipeline("A2VidPipelineTwoStage", "AudioToVideoPipeline")if not args.audio:raise SystemExit("--audio is required for a2v mode")+ streaming_policy = configure_streaming_policy(args, AudioToVideoPipeline, "a2v")+ streaming_kwargs = {"low_ram_streaming": streaming_policy["active"]} if streaming_policy["supports"] else {}emit_status(f"Loading A2V pipeline ({args.model})…")emit_stage(1, 0, 1, "Loading model")- pipe = AudioToVideoPipeline(model_dir=args.model, **_gemma_kwargs(args))+ pipe = AudioToVideoPipeline(model_dir=args.model, **streaming_kwargs, **_gemma_kwargs(args))_prefer_distilled_lora(pipe, args.distilled_lora)+ _refuse_if_streaming_distilled_adapter_missing(pipe, streaming_policy["active"])_apply_user_loras(pipe, args.user_lora_specs)emit_stage(1, 1, 1, "Loaded")emit_status(f"Generating A2V from {Path(args.audio).name}…")@@ -1810,6 +1839,8 @@ def run_ic_lora(args: argparse.Namespace) -> str:if args.ic_attention_strength is not None and not (0.0 <= args.ic_attention_strength <= 1.0):raise SystemExit("--ic-attention-strength must be between 0.0 and 1.0")+ streaming_policy = configure_streaming_policy(args, ICLoraPipeline, "ic-lora")+ streaming_kwargs = {"low_ram_streaming": streaming_policy["active"]} if streaming_policy["supports"] else {}emit_status(f"Loading IC-LoRA pipeline ({args.model}, {ic_mode})…")emit_stage(1, 0, 1, "Loading model")pipe = ICLoraPipeline(@@ -1819,6 +1850,7 @@ def run_ic_lora(args: argparse.Namespace) -> str:# which weights the reference conditioning). Upstream's CLI defaults the# same way.lora_paths=[(args.ic_lora_path, 1.0)],+ **streaming_kwargs,**_gemma_kwargs(args),)# User LoRAs go through _pending_loras (fused at DiT load), NOT lora_paths —@@ -2029,7 +2061,16 @@ def reassert_mlx_cache_policy() -> bool:single largest allocation of that mode). What a pipeline does INSIDE one call— a stage-2 transformer reload — is out of this wrapper's reach; the capsimply resumes at the next boundary.++ When block streaming (#6499) is active for this render, the pipeline's own+ construction already zeroed the allocator cache (BasePipeline.__init__ sets+ it before any module loads) — reasserting the physical-memory-derived+ ceiling here would silently undo that zero-cache policy at the very next+ boundary, defeating the reason streaming was requested. Keep it pinned at+ zero for a streaming render instead of falling back to the resident ceiling."""+ if _STREAMING_POLICY.get("active"):+ return apply_mlx_cache_policy({"limitMb": 0, "source": "streaming"})return apply_mlx_cache_policy(_MLX_CACHE_POLICY)@@ -2050,6 +2091,161 @@ def configure_mlx_cache(args: argparse.Namespace) -> dict:return _MLX_CACHE_POLICY+# --------------------------------------------------------------------------+# Block streaming (#6499) — mmaps the transformer's safetensors and streams+# blocks in per-forward instead of materializing all 48 in unified memory+# (ltx-2-mlx's `low_ram_streaming` pipeline constructor kwarg; adopted+# clean-room from Phosphene commits 3f63e773 + e12fc6a1). Cuts transformer+# peak RSS from ~10-12 GB (q8) / ~22 GB (bf16) to well under 1 GB, at the+# cost of ~48 extra Metal sync points per forward.+#+# Whether a given render MODE's pinned pipeline constructor even exposes the+# parameter is answered by _accepts_kwarg against the ACTUAL resolved class —+# never assumed from the mode name — because RetakePipeline (extend mode) has+# none at the pins this bridge targets while every other mode's pipeline does.+# --------------------------------------------------------------------------++STREAMING_MODE_CHOICES = ("auto", "resident", "stream")++# 'auto' streams on a machine at or below this much physical RAM, and stays+# resident above it (or when physical memory can't be read). Block streaming+# adds real per-forward overhead, so it is only worth the cost automatically+# on a box tight enough that a ~10-12x smaller transformer footprint matters.+STREAMING_AUTO_RAM_CEILING_BYTES = 24 * 1024 ** 3 # 24 GiB++_STREAMING_POLICY: dict = {}+_STREAMING_PIPELINE_LABEL: str | None = None+++def resolve_streaming_policy(requested_mode: str, physical_bytes, pipeline_supports_streaming: bool) -> dict:+ """Effective per-pipeline block-streaming policy. Pure — no MLX, no I/O.++ Mirrors resolve_mlx_cache_policy's shape: an explicit request either wins+ or is reported as refused, 'auto' derives from what THIS pipeline's+ pinned constructor exposes and how much physical RAM this machine has.+ Never raises — configure_streaming_policy decides whether an explicit+ 'stream' request this pipeline cannot honor should exit the process.++ Returns ``{"requestedMode": str, "active": bool, "supports": bool,+ "reason": str | None}``. `reason` explains every case where `active` is+ not simply "the caller asked for it": the pipeline lacks the parameter,+ physical memory could not be read, or this machine sits above the auto+ ceiling.+ """+ if requested_mode == "resident":+ return {"requestedMode": "resident", "active": False, "supports": pipeline_supports_streaming, "reason": None}+ if not pipeline_supports_streaming:+ return {+ "requestedMode": requested_mode, "active": False, "supports": False,+ "reason": "the selected pipeline's pinned constructor has no streaming parameter",+ }+ if requested_mode == "stream":+ return {"requestedMode": "stream", "active": True, "supports": True, "reason": None}+ # auto+ if physical_bytes is None:+ return {+ "requestedMode": "auto", "active": False, "supports": True,+ "reason": "physical memory unknown — remaining resident",+ }+ if physical_bytes <= STREAMING_AUTO_RAM_CEILING_BYTES:+ return {"requestedMode": "auto", "active": True, "supports": True, "reason": None}+ ceiling_gib = STREAMING_AUTO_RAM_CEILING_BYTES // (1024 ** 3)+ return {+ "requestedMode": "auto", "active": False, "supports": True,+ "reason": f"physical memory is above the {ceiling_gib} GiB auto-stream ceiling",+ }+++def configure_streaming_policy(args: argparse.Namespace, pipeline_cls, pipeline_label: str) -> dict:+ """Resolve + install this render's streaming policy for `pipeline_cls`.++ Called once per run_* right where the pipeline class was picked — support+ depends on which class the mode routed to. Inspects the ACTUAL resolved+ constructor via _accepts_kwarg rather than assuming from the mode name, so+ an older pin that predates `low_ram_streaming` degrades the same way a+ newer one without it would.++ An explicit `--streaming-mode stream` the pipeline cannot honor exits+ HERE, before any weights load — never silently downgrading to a resident+ render and reporting a memory ceiling this run did not keep.+ """+ global _STREAMING_POLICY, _STREAMING_PIPELINE_LABEL+ supports = _accepts_kwarg(pipeline_cls.__init__, "low_ram_streaming")+ policy = resolve_streaming_policy(args.streaming_mode, physical_memory_bytes(), supports)+ if args.streaming_mode == "stream" and not policy["active"]:+ raise SystemExit(+ f"--streaming-mode stream was requested but the {pipeline_label} pipeline "+ f"cannot honor it at this pin ({policy['reason']}). Refusing before loading "+ "weights rather than silently rendering resident and claiming a memory "+ "ceiling this run did not keep."+ )+ _STREAMING_POLICY = policy+ _STREAMING_PIPELINE_LABEL = pipeline_label+ if policy["active"]:+ emit_status("Block streaming enabled — transformer blocks stream from disk")+ elif policy["reason"] and args.streaming_mode != "resident":+ emit_status(f"Block streaming not used: {policy['reason']}")+ return policy+++def _refuse_if_streaming_distilled_adapter_missing(pipe, active: bool) -> None:+ """Preflight the streaming Stage 1 -> 2 distilled-adapter swap.++ ``TI2VidTwoStagesPipeline._swap_to_distilled_streamer`` (the streaming+ variant of the Stage 1 -> Stage 2 transition used by two-stage/fflf/a2v)+ only discovers a missing file when it RUNS — after Stage 1 has already+ denoised, the exact "costly render" this guard exists to avoid (#6499+ acceptance: reject an unsupported LoRA-adapter combination before a+ costly render). At the default LoRA strength it needs a pre-fused+ ``transformer-distilled*.safetensors``; at any other strength it needs+ the distilled LoRA safetensors itself. Callers pass the pipe AFTER+ `_prefer_distilled_lora` has set `pipe._distilled_lora`, so this reads the+ adapter this render will actually try to use.+ """+ if not active:+ return+ model_dir = Path(pipe.model_dir)+ strength = getattr(pipe, "_distilled_lora_strength", 1.0)+ if abs(strength - 1.0) <= 1e-6:+ if not list(model_dir.glob("transformer-distilled*.safetensors")):+ raise SystemExit(+ f"Block streaming needs a pre-fused transformer-distilled*.safetensors in "+ f"{model_dir} at the default LoRA strength, and none was found. Refusing "+ "before Stage 1 renders rather than failing at the Stage 1→2 swap."+ )+ return+ lora_path = model_dir / pipe._distilled_lora+ if not lora_path.exists():+ raise SystemExit(+ f"Block streaming needs {lora_path} for the Stage 1→2 swap at LoRA strength "+ f"{strength:g}, and it was not found. Refusing before Stage 1 renders."+ )+++def report_streaming_policy() -> None:+ """Emit the STREAMPOLICY: report PortOS persists onto the render record.++ Called once after the render completes (main()). No-op for a process that+ never reached configure_streaming_policy — nothing to report; a resident+ render behaves exactly as it did before this setting existed. Includes+ peak MLX memory when streaming was active: the number a smaller-hardware+ claim should be backed by, not an assumption about what streaming saves+ (#6499 acceptance: "a representative small-memory smoke render must+ report peak memory and successful output before claiming expanded+ hardware support").+ """+ if not _STREAMING_POLICY:+ return+ report = {"pipeline": _STREAMING_PIPELINE_LABEL, **_STREAMING_POLICY}+ if _STREAMING_POLICY.get("active"):+ try:+ import mlx.core as mx+ report["peakMb"] = round(mx.get_peak_memory() / (1024 * 1024))+ except Exception:+ pass+ print(f"STREAMPOLICY:{json.dumps(report)}", file=sys.stderr, flush=True)++def main() -> NoReturn:args = parse_args()validate_text_encoder_args(args)@@ -2102,6 +2298,11 @@ def main() -> NoReturn:# left silently absent, which would read back as "the profile applied".speed_profile_begin(args)saved_path = runner(args)+ # Block-streaming report (#6499) — after the render so a captured peak+ # memory reading covers the whole render (denoise + decode), not just+ # pipeline construction. No-op for a process whose mode never resolved a+ # streaming policy.+ report_streaming_policy()if args.teacache and not _SPEED_PROFILE_REPORT.get("teacache") \and "teacache" not in _SPEED_PROFILE_REPORT.get("degraded", []):speed_profile_degrade(diff --git a/scripts/generate_ltx2.test.js b/scripts/generate_ltx2.test.jsindex 10d4b52d50..8db57c0a24 100644--- a/scripts/generate_ltx2.test.js+++ b/scripts/generate_ltx2.test.js@@ -1324,3 +1324,352 @@ describe.skipIf(!pyBin)('generate_ltx2.py MLX allocator-cache policy', () => {});});});++describe.skipIf(!pyBin)('generate_ltx2.py block streaming (#6499)', () => {+ const GB = 1024 * 1024 * 1024;+ const runJson = (body) => JSON.parse(runPython(`${importRunner}\n${body.join('\n')}`));++ // Pipeline stand-ins for _accepts_kwarg's inspection. A bare **kwargs+ // catch-all must NOT count as support — mirrors _accepts_kwarg's own+ // contract (checked separately by that function's own tests above), so a+ // real pin whose wrapper merely swallows the kwarg without forwarding it+ // is not misreported as capable.+ const STREAMING_PIPELINE = [+ 'class StreamingPipe:',+ ' def __init__(self, model_dir, low_ram_streaming=False, **kw):',+ ' self.model_dir = model_dir',+ ];+ const RESIDENT_ONLY_PIPELINE = [+ 'class ResidentOnlyPipe:', // e.g. RetakePipeline at the pins this bridge targets+ ' def __init__(self, model_dir, **kw):',+ ' self.model_dir = model_dir',+ ];++ // ── resolve_streaming_policy: pure, no MLX/IO ───────────────────────────+ it('resident always resolves inactive, whatever the pipeline supports', () => {+ const result = runJson([+ 'import json',+ `print(json.dumps({`,+ ` "supported": runner.resolve_streaming_policy("resident", 8 * ${GB}, True),`,+ ` "unsupported": runner.resolve_streaming_policy("resident", 8 * ${GB}, False),`,+ `}))`,+ ]);+ expect(result.supported).toEqual({ requestedMode: 'resident', active: false, supports: true, reason: null });+ expect(result.unsupported).toEqual({ requestedMode: 'resident', active: false, supports: false, reason: null });+ });++ it('an explicit stream request resolves active on a supported pipeline', () => {+ const result = runJson([+ 'import json',+ `print(json.dumps(runner.resolve_streaming_policy("stream", 8 * ${GB}, True)))`,+ ]);+ expect(result).toEqual({ requestedMode: 'stream', active: true, supports: true, reason: null });+ });++ it('an explicit stream request resolves inactive with a reason on an unsupported pipeline', () => {+ const result = runJson([+ 'import json',+ `print(json.dumps(runner.resolve_streaming_policy("stream", 8 * ${GB}, False)))`,+ ]);+ expect(result.active).toBe(false);+ expect(result.supports).toBe(false);+ expect(result.reason).toMatch(/no streaming parameter/);+ });++ it.each([+ ['at the ceiling', 24 * GB, true],+ ['well below the ceiling', 4 * GB, true],+ ['just above the ceiling', 24 * GB + 1, false],+ ['well above the ceiling', 128 * GB, false],+ ])('auto on a supported pipeline resolves %s', (_label, bytes, expectedActive) => {+ const result = runJson([+ 'import json',+ `print(json.dumps(runner.resolve_streaming_policy("auto", ${bytes}, True)))`,+ ]);+ expect(result.requestedMode).toBe('auto');+ expect(result.active).toBe(expectedActive);+ expect(result.reason === null).toBe(expectedActive);+ });++ it('auto stays resident (not fatal) when physical memory is unknown', () => {+ const result = runJson([+ 'import json',+ 'print(json.dumps(runner.resolve_streaming_policy("auto", None, True)))',+ ]);+ expect(result).toEqual({+ requestedMode: 'auto', active: false, supports: true,+ reason: 'physical memory unknown — remaining resident',+ });+ });++ it('auto stays resident (not fatal) on an unsupported pipeline', () => {+ const result = runJson([+ 'import json',+ `print(json.dumps(runner.resolve_streaming_policy("auto", 8 * ${GB}, False)))`,+ ]);+ expect(result.active).toBe(false);+ expect(result.reason).toMatch(/no streaming parameter/);+ });++ // ── configure_streaming_policy: installs the policy, refuses when needed ──+ it('refuses an explicit stream request BEFORE any pipeline is constructed', () => {+ const output = runPython(`${importRunner}\n${[+ ...RESIDENT_ONLY_PIPELINE,+ 'from types import SimpleNamespace',+ 'runner.physical_memory_bytes = lambda: 8 * 1024 ** 3',+ 'args = SimpleNamespace(streaming_mode="stream")',+ 'try:',+ ' runner.configure_streaming_policy(args, ResidentOnlyPipe, "extend")',+ 'except SystemExit as exc:',+ ' print(str(exc))',+ 'else:',+ ' raise AssertionError("an unsupportable stream request was accepted")',+ ].join('\n')}`);+ expect(output).toMatch(/--streaming-mode stream was requested/);+ expect(output).toMatch(/extend pipeline/);+ expect(output).toMatch(/before loading weights/);+ });++ it('degrades an auto request to resident with a STATUS explanation on an unsupported pipeline', () => {+ const result = runJson([+ ...RESIDENT_ONLY_PIPELINE,+ 'import contextlib, io, json',+ 'from types import SimpleNamespace',+ 'runner.physical_memory_bytes = lambda: 8 * 1024 ** 3',+ 'args = SimpleNamespace(streaming_mode="auto")',+ 'err = io.StringIO()',+ 'with contextlib.redirect_stderr(err):',+ ' policy = runner.configure_streaming_policy(args, ResidentOnlyPipe, "extend")',+ 'print(json.dumps({"policy": policy, "stderr": err.getvalue()}))',+ ]);+ expect(result.policy.active).toBe(false);+ expect(result.policy.supports).toBe(false);+ expect(result.stderr).toMatch(/^STATUS:Block streaming not used:/);+ });++ it('reports an enabled STATUS line and installs the policy for the reassert path', () => {+ const result = runJson([+ ...STREAMING_PIPELINE,+ 'import contextlib, io, json',+ 'from types import SimpleNamespace',+ `runner.physical_memory_bytes = lambda: 4 * ${GB}`,+ 'args = SimpleNamespace(streaming_mode="auto")',+ 'err = io.StringIO()',+ 'with contextlib.redirect_stderr(err):',+ ' policy = runner.configure_streaming_policy(args, StreamingPipe, "one-stage")',+ 'print(json.dumps({"policy": policy, "stored": runner._STREAMING_POLICY, "stderr": err.getvalue()}))',+ ]);+ expect(result.policy).toEqual({ requestedMode: 'auto', active: true, supports: true, reason: null });+ expect(result.stored).toEqual(result.policy);+ expect(result.stderr.trim()).toBe('STATUS:Block streaming enabled — transformer blocks stream from disk');+ });++ it('a plain resident request installs the policy silently (no streaming STATUS noise)', () => {+ const result = runJson([+ ...STREAMING_PIPELINE,+ 'import contextlib, io, json',+ 'from types import SimpleNamespace',+ 'runner.physical_memory_bytes = lambda: None',+ 'args = SimpleNamespace(streaming_mode="resident")',+ 'err = io.StringIO()',+ 'with contextlib.redirect_stderr(err):',+ ' policy = runner.configure_streaming_policy(args, StreamingPipe, "one-stage")',+ 'print(json.dumps({"policy": policy, "stderr": err.getvalue()}))',+ ]);+ expect(result.policy).toEqual({ requestedMode: 'resident', active: false, supports: true, reason: null });+ expect(result.stderr.trim()).toBe('');+ });++ // ── reassert_mlx_cache_policy must not undo the streamer's zero-cache ────+ it('keeps the allocator cache pinned at zero on every reassert while streaming', () => {+ const result = runJson([+ 'import sys, types, json',+ 'CALLS = []',+ 'core = types.ModuleType("mlx.core")',+ 'core.set_cache_limit = lambda n: CALLS.append(n)',+ 'pkg = types.ModuleType("mlx")',+ 'pkg.core = core',+ 'sys.modules["mlx"] = pkg',+ 'sys.modules["mlx.core"] = core',+ // A non-zero resident policy is still installed — reassert must NOT fall+ // back to it while streaming is active, or the streamer's own+ // BasePipeline.__init__ zero-cache policy is silently undone.+ 'runner._MLX_CACHE_POLICY = {"limitMb": 8192, "source": "derived"}',+ 'runner._STREAMING_POLICY = {"active": True}',+ 'runner.reassert_mlx_cache_policy()',+ 'runner.reassert_mlx_cache_policy()',+ 'print(json.dumps(CALLS))',+ ]);+ expect(result).toEqual([0, 0]);+ });++ it('reasserts the resident ceiling as before when streaming is not active', () => {+ const result = runJson([+ 'import sys, types, json',+ 'CALLS = []',+ 'core = types.ModuleType("mlx.core")',+ 'core.set_cache_limit = lambda n: CALLS.append(n)',+ 'pkg = types.ModuleType("mlx")',+ 'pkg.core = core',+ 'sys.modules["mlx"] = pkg',+ 'sys.modules["mlx.core"] = core',+ 'runner._MLX_CACHE_POLICY = {"limitMb": 8192, "source": "derived"}',+ 'runner._STREAMING_POLICY = {"active": False}',+ 'runner.reassert_mlx_cache_policy()',+ 'print(json.dumps(CALLS))',+ ]);+ expect(result).toEqual([8192 * 1024 * 1024]);+ });++ // ── LoRA-adapter preflight — refuse before Stage 1, not at the Stage 1→2+ // swap (#6499 acceptance: reject an unsupported streaming/LoRA combination+ // before a costly render) ────────────────────────────────────────────────+ it('is a no-op when streaming is not active, whatever the model dir holds', () => {+ const output = runPython(`${importRunner}\n${[+ 'import tempfile',+ 'from types import SimpleNamespace',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' pipe = SimpleNamespace(model_dir=temp, _distilled_lora="x.safetensors", _distilled_lora_strength=1.0)',+ ' runner._refuse_if_streaming_distilled_adapter_missing(pipe, False)',+ 'print("ok")',+ ].join('\n')}`);+ expect(output.trim()).toBe('ok');+ });++ it('refuses when streaming needs the pre-fused distilled transformer and none is present', () => {+ const output = runPython(`${importRunner}\n${[+ 'import tempfile',+ 'from types import SimpleNamespace',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' pipe = SimpleNamespace(model_dir=temp, _distilled_lora="x.safetensors", _distilled_lora_strength=1.0)',+ ' try:',+ ' runner._refuse_if_streaming_distilled_adapter_missing(pipe, True)',+ ' except SystemExit as exc:',+ ' print(str(exc))',+ ' else:',+ ' raise AssertionError("a missing pre-fused transformer was accepted")',+ ].join('\n')}`);+ expect(output).toMatch(/pre-fused transformer-distilled\*\.safetensors/);+ expect(output).toMatch(/before Stage 1 renders/);+ });++ it('passes when the pre-fused distilled transformer is present at default strength', () => {+ const output = runPython(`${importRunner}\n${[+ 'import tempfile',+ 'from pathlib import Path',+ 'from types import SimpleNamespace',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' (Path(temp) / "transformer-distilled-1.1.safetensors").write_text("x")',+ ' pipe = SimpleNamespace(model_dir=temp, _distilled_lora="x.safetensors", _distilled_lora_strength=1.0)',+ ' runner._refuse_if_streaming_distilled_adapter_missing(pipe, True)',+ 'print("ok")',+ ].join('\n')}`);+ expect(output.trim()).toBe('ok');+ });++ it('at a non-default LoRA strength, refuses when the distilled LoRA file is missing and passes when present', () => {+ const output = runPython(`${importRunner}\n${[+ 'import tempfile',+ 'from pathlib import Path',+ 'from types import SimpleNamespace',+ 'with tempfile.TemporaryDirectory() as temp:',+ ' pipe = SimpleNamespace(model_dir=temp, _distilled_lora="adapter.safetensors", _distilled_lora_strength=0.7)',+ ' try:',+ ' runner._refuse_if_streaming_distilled_adapter_missing(pipe, True)',+ ' except SystemExit as exc:',+ ' missing_msg = str(exc)',+ ' else:',+ ' raise AssertionError("a missing distilled LoRA was accepted")',+ ' (Path(temp) / "adapter.safetensors").write_text("x")',+ ' runner._refuse_if_streaming_distilled_adapter_missing(pipe, True)',+ ' print(missing_msg)',+ ].join('\n')}`);+ expect(output).toMatch(/LoRA strength 0\.7/);+ expect(output).toMatch(/before Stage 1 renders/);+ });++ // ── report_streaming_policy: the persisted record, incl. peak memory ────+ it('reports nothing when no render ever resolved a streaming policy', () => {+ const output = runPython(`${importRunner}\n${[+ 'runner._STREAMING_POLICY = {}',+ 'runner._STREAMING_PIPELINE_LABEL = None',+ 'runner.report_streaming_policy()',+ 'print("done")',+ ].join('\n')}`);+ expect(output.trim()).toBe('done');+ });++ // report_streaming_policy prints on the same STDERR channel as SPEEDPROFILE:+ // / DRAFTDECODE: (see generateVideoHelpers.js), so these capture stderr the+ // same way the "reports the effective policy" MLX-cache test above does.+ it('reports the resident case with no peak-memory reading', () => {+ const result = runJson([+ 'import contextlib, io, json',+ 'runner._STREAMING_POLICY = {"requestedMode": "auto", "active": False, "supports": True, "reason": "physical memory is above the 24 GiB auto-stream ceiling"}',+ 'runner._STREAMING_PIPELINE_LABEL = "one-stage"',+ 'err = io.StringIO()',+ 'with contextlib.redirect_stderr(err):',+ ' runner.report_streaming_policy()',+ 'print(json.dumps({"stderr": err.getvalue()}))',+ ]);+ const report = JSON.parse(result.stderr.trim().replace(/^STREAMPOLICY:/, ''));+ expect(report).toEqual({+ pipeline: 'one-stage', requestedMode: 'auto', active: false, supports: true,+ reason: 'physical memory is above the 24 GiB auto-stream ceiling',+ });+ expect(report.peakMb).toBeUndefined();+ });++ it('reports peak MLX memory when streaming was active — the number a smaller-hardware claim is backed by', () => {+ const result = runJson([+ 'import sys, types, contextlib, io, json',+ 'core = types.ModuleType("mlx.core")',+ 'core.get_peak_memory = lambda: 512 * 1024 * 1024',+ 'pkg = types.ModuleType("mlx")',+ 'pkg.core = core',+ 'sys.modules["mlx"] = pkg',+ 'sys.modules["mlx.core"] = core',+ 'runner._STREAMING_POLICY = {"requestedMode": "stream", "active": True, "supports": True, "reason": None}',+ 'runner._STREAMING_PIPELINE_LABEL = "ic-lora"',+ 'err = io.StringIO()',+ 'with contextlib.redirect_stderr(err):',+ ' runner.report_streaming_policy()',+ 'print(json.dumps({"stderr": err.getvalue()}))',+ ]);+ const report = JSON.parse(result.stderr.trim().replace(/^STREAMPOLICY:/, ''));+ expect(report.pipeline).toBe('ic-lora');+ expect(report.active).toBe(true);+ expect(report.peakMb).toBe(512);+ });++ it('reports without a peak-memory reading when MLX is unavailable, rather than failing the report', () => {+ const result = runJson([+ 'import sys, contextlib, io, json',+ 'sys.modules["mlx"] = None',+ 'sys.modules.pop("mlx.core", None)',+ 'runner._STREAMING_POLICY = {"requestedMode": "stream", "active": True, "supports": True, "reason": None}',+ 'runner._STREAMING_PIPELINE_LABEL = "ic-lora"',+ 'err = io.StringIO()',+ 'with contextlib.redirect_stderr(err):',+ ' runner.report_streaming_policy()',+ 'print(json.dumps({"stderr": err.getvalue()}))',+ ]);+ const report = JSON.parse(result.stderr.trim().replace(/^STREAMPOLICY:/, ''));+ expect(report.active).toBe(true);+ expect(report.peakMb).toBeUndefined();+ });++ it('parses --streaming-mode and defaults it to auto', () => {+ const out = runPython(`${importRunner}\n${[+ 'import sys',+ 'base = ["generate_ltx2.py", "--mode", "text", "--prompt", "p", "--output", "/tmp/o.mp4", "--model", "m"]',+ 'sys.argv = base',+ 'print(runner.parse_args().streaming_mode)',+ 'sys.argv = base + ["--streaming-mode", "stream"]',+ 'print(runner.parse_args().streaming_mode)',+ 'sys.argv = base + ["--streaming-mode", "resident"]',+ 'print(runner.parse_args().streaming_mode)',+ ].join('\n')}`);+ expect(out.trim().split(/\r?\n/).map((l) => l.trimEnd())).toEqual(['auto', 'stream', 'resident']);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex c9ef66f540..89c6f0073c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -183,6 +183,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `videoModeProfiles.js` | The shipped `supportedModes` fact per video runtime (#3737), so "which modes does this model support?" has one answer on the registry entry instead of 25+ runtime comparisons. `VIDEO_RUNTIME_MODES` maps each runtime to the semantic modes its helper can actually render, including `minimax_h3_ref2va` as a2v-only; `VIDEO_BASE_MODES` remains the non-audio fallback for an unknown runtime. `resolveVideoSupportedModes(entry)` and `applyVideoSupportedModes(list)` provide the read-time decoration used by `mediaModels.js#getVideoModels`. || `videoDurationProfiles.js` | Pure pinned duration/frame contracts shared by model-registry upgrades and migrations. LTX-2.5 A2V follows the full uploaded audio, rounds up to its 8n+1 temporal grid, and tops out at 1017 frames under the API's single-pass boundary. || `videoReferenceModes.js` | The i2v reference-mode contract (#4874) — what a supplied conditioning image PROMISES. `I2V_REFERENCE_MODES` (`anchor` \| `inspire`) + `I2V_REFERENCE_MODE_OPTIONS` (the label + the promise sentence the UI prints), `I2V_REFERENCE_MODE_RUNTIMES` (only `ltx25` can honor `inspire` — it needs per-image conditioning strength), `INSPIRE_DEFAULT_IMAGE_STRENGTH`, plus `normalizeI2vReferenceMode` / `isDefaultI2vReferenceMode` / `isKnownI2vReferenceMode` / `runtimeSupportsI2vReferenceMode` / `i2vReferenceModeLabel` / `resolveI2vReferenceStrength` and the one rule `i2vReferenceModeViolation({ model, mode, referenceMode, hasFirstImage })` → `{ code, message }` or null. Pure (no `ServerError`) because it is MIRRORED to `client/src/lib/videoReferenceModes.js`; `videoGen/modeContract.js#videoReferenceModeError` wraps it for the route + render boundaries. |+| `videoStreamingMode.js` | Block-streaming request vocabulary for LTX-2/2.5 MLX local video renders (#6499) — `VIDEO_STREAMING_MODES` (`auto` \| `resident` \| `stream`), `DEFAULT_VIDEO_STREAMING_MODE` (`'auto'`), `VIDEO_STREAMING_MODE_OPTIONS` (label + description for the picker), `isDefaultVideoStreamingMode` / `isKnownVideoStreamingMode` / `videoStreamingModeLabel` / `videoStreamingModeFromRecord`. This module carries only the REQUEST-side enum — `scripts/generate_ltx2.py#resolve_streaming_policy()` inspects the pinned pipeline's actual constructor and this machine's physical RAM to decide whether `auto` streams, and an explicit `stream` request the pinned pipeline cannot honor (Extend) is a refusal there, not a downgrade here. Pure, mirrored to `client/src/lib/videoStreamingMode.js`. || `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. || `pi.js` | Pi command identity, headless/TUI arguments, and positional prompt delivery. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `clampEffortToLadder` (that clamp over an explicit ladder; the client's own `resolveCliEffort` runs its published-field ladder through it), `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 045ff6cf3e..9f23ac0383 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -183,6 +183,7 @@ export * from './videoSpeedProfiles.js';export * from './videoModeProfiles.js';export * from './videoDurationProfiles.js';export * from './videoReferenceModes.js';+export * from './videoStreamingMode.js';export * from './videoTextEncoders.js';export * from './promptFencing.js';export * from './promptPartials.js';diff --git a/server/lib/videoStreamingMode.js b/server/lib/videoStreamingMode.jsnew file mode 100644index 0000000000..e9ae78fed0--- /dev/null+++ b/server/lib/videoStreamingMode.js@@ -0,0 +1,72 @@+/**+ * Block-streaming mode vocabulary for LTX-2/2.5 MLX local video renders (#6499).+ *+ * "Block streaming" mmaps the transformer's safetensors and streams blocks in+ * per-forward instead of materializing all 48 in unified memory — the roughly+ * 10-12x transformer-RSS cut ltx-2-mlx exposes as the `low_ram_streaming`+ * pipeline constructor kwarg (adopted clean-room from Phosphene commits+ * 3f63e773 + e12fc6a1). Whether a given render MODE's pinned pipeline+ * constructor even declares that parameter can only be answered by+ * `scripts/generate_ltx2.py` inspecting the live class at request time —+ * RetakePipeline (extend mode) has none at the pins this bridge targets, every+ * other mode's pipeline does. This module carries only the REQUEST-side+ * vocabulary PortOS threads through unexamined; the bridge owns capability+ * inspection and the actual RAM-based auto decision (it runs on whichever+ * machine is EXECUTING the render, never the submitter's, so a federated peer+ * decides for its own hardware).+ *+ * `'auto'` (and absence) is the shipped default — `resolve_streaming_policy()`+ * in the Python bridge turns it into streaming on a machine at or below the+ * bridge's known-tight-memory ceiling, and resident above it or when physical+ * memory can't be read. `resident` and `stream` are explicit overrides. Unlike+ * draft-decode / speed-profile, an explicit `stream` request the pinned+ * pipeline cannot honor is a REFUSAL (the bridge exits before loading weights)+ * rather than a silent downgrade — this module does not decide that; it only+ * carries the enum.+ *+ * Pure (no ServerError, no Node builtin) — mirrored to+ * `client/src/lib/videoStreamingMode.js` so the picker and the request builder+ * share one vocabulary.+ */++export const VIDEO_STREAMING_MODES = Object.freeze(['auto', 'resident', 'stream']);++export const DEFAULT_VIDEO_STREAMING_MODE = 'auto';++// Label + one-line description for the picker. Order matches VIDEO_STREAMING_MODES.+export const VIDEO_STREAMING_MODE_OPTIONS = Object.freeze([+ Object.freeze({+ value: 'auto',+ label: 'Auto',+ description: 'Stream transformer blocks from disk on a machine tight enough that it matters; render resident otherwise.',+ }),+ Object.freeze({+ value: 'resident',+ label: 'Resident',+ description: 'Load the full transformer into memory — the behavior every render had before this setting existed.',+ }),+ Object.freeze({+ value: 'stream',+ label: 'Stream',+ description: 'Always stream transformer blocks from disk. Refused before any weights load on a mode whose pinned pipeline has no streaming parameter (Extend).',+ }),+]);++/** Absence and the shipped default request the same thing. */+export const isDefaultVideoStreamingMode = (mode) => (+ mode == null || mode === '' || mode === DEFAULT_VIDEO_STREAMING_MODE+);++export const isKnownVideoStreamingMode = (mode) => VIDEO_STREAMING_MODES.includes(mode);++export const videoStreamingModeLabel = (mode) => (+ VIDEO_STREAMING_MODE_OPTIONS.find((o) => o.value === mode)?.label || 'Auto'+);++// Read a mode out of a persisted record (a history entry, a resumed job's+// params). History records only a NON-default mode (see generateVideo.js), so+// a missing/unknown field means Auto — and must CLEAR a leftover selection+// rather than carry it into a render the user asked to reproduce.+export const videoStreamingModeFromRecord = (value) => (+ isKnownVideoStreamingMode(value) ? value : DEFAULT_VIDEO_STREAMING_MODE+);diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex a8f470e143..83452b4220 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -59,6 +59,7 @@ import {} from '../lib/icLoraWeights.js';import { publicTextEncoderOption } from '../lib/videoTextEncoders.js';import { DRAFT_DECODE_IDS } from '../lib/videoDraftDecoders.js';+import { VIDEO_STREAMING_MODES } from '../lib/videoStreamingMode.js';import { repairModelCache, repairCachedFile, summarizeVerify } from '../lib/hfCache.js';import {modelDownloadTargets, textEncoderDownloadTarget, textEncoderDownloadTargets,@@ -248,6 +249,15 @@ export const LOCAL_ONLY_VIDEO_PARAMS = Object.freeze({// either: an unsupported model, an old runner checkout, a missing download or// a delivery render all fall back to the full decoder with the reason logged.[VIDEO_GEN_LOCAL_ONLY_FIELDS.DRAFT_DECODE]: z.enum(DRAFT_DECODE_IDS).optional(),+ // Block-streaming request for LTX-2/2.5 MLX renders (#6499). Unlike+ // draftDecode/speedProfileId this is NOT a "degrade, never reject" knob:+ // scripts/generate_ltx2.py#resolve_streaming_policy() refuses an explicit+ // 'stream' request before loading weights when the mode's pinned pipeline+ // has no streaming parameter (Extend), so this stays a validated pass-+ // through rather than a route-level 400 — the bridge, which can inspect+ // the live pin, owns accept/refuse. Absence and 'auto' are the same+ // request (the bridge's own default).+ [VIDEO_GEN_LOCAL_ONLY_FIELDS.STREAMING_MODE]: z.enum(VIDEO_STREAMING_MODES).optional(),});const generateBodySchema = z.object({@@ -928,6 +938,10 @@ const ACTIVE_JOB_PARAM_FIELDS = [// picked, so a reloading page restores the control instead of snapping back// to Full.'draftDecode',+ // Block-streaming request (#6499) — a closed enum with no path, safe to+ // echo so a reloading page restores the picker instead of snapping back to+ // Auto.+ 'streamingMode','audioStartSec',// Grok jobs (#2859 phase 2): the semantic t2v/i2v mode ('mode' holds the// 'grok' discriminator for them) and the clip duration — both plaindiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 4fc122147d..fb98347a7a 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -919,6 +919,11 @@ describe('videoGen routes', () => {'textEncoderId','speedProfileId','draftDecode',+ // Not in the it.each table above: the route deliberately DROPS the+ // 'auto' default from persisted params, same reason as draftDecode's+ // full-decode default — the generic round-trip can't cover it. Its+ // own case is below.+ 'streamingMode',]);const { getSettings } = await import('../services/settings.js');getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });@@ -965,6 +970,35 @@ describe('videoGen routes', () => {expect(r.status).toBe(400);});+ // Same contract for block streaming (#6499): grok has no such knob, so+ // naming one keeps the render local — and 'auto' (the bridge's own+ // default) is dropped from persisted params so an unswapped render's job+ // params stay byte-identical to a request that never sent the field.+ it('keeps streamingMode on the local path under a grok pin, without persisting the auto value', async () => {+ const { getSettings } = await import('../services/settings.js');+ getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox', streamingMode: 'auto' });+ expect(r.status).toBe(200);+ const [call] = mediaJobQueue.enqueueJob.mock.calls;+ expect(call[0].params.mode).not.toBe('grok');+ expect(call[0].params.streamingMode).toBeUndefined();+ });++ it('persists a non-default streamingMode on the local path', async () => {+ const { getSettings } = await import('../services/settings.js');+ getSettings.mockResolvedValueOnce({ imageGen: grokReady, videoGen: { mode: 'grok' } });+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox', streamingMode: 'stream' });+ expect(r.status).toBe(200);+ const [call] = mediaJobQueue.enqueueJob.mock.calls;+ expect(call[0].params.streamingMode).toBe('stream');+ });++ // A closed enum — the render bridge, not this route, decides whether the+ // resolved mode's pinned pipeline can honor 'stream' (#6499).+ it.each(['fast', 'STREAM', ''])('rejects the streamingMode value %p', async (streamingMode) => {+ const r = await request(app).post('/api/video-gen/').send({ prompt: 'a fox', streamingMode });+ expect(r.status).toBe(400);+ });it('keeps textEncoderId on the local path under a grok pin, without persisting the stock value', async () => {const { getSettings } = await import('../services/settings.js');diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.jsindex bc68c797c8..fde447fd02 100644--- a/server/services/videoGen/generateVideo.js+++ b/server/services/videoGen/generateVideo.js@@ -76,6 +76,7 @@ import {draftDecodeDeclineReason,resolveVideoDraftDecoder,} from '../../lib/videoDraftDecoders.js';+import { isDefaultVideoStreamingMode } from '../../lib/videoStreamingMode.js';// Re-export the extracted runtime + history surface so existing deep imports// (`from '../videoGen/local.js'`) keep resolving every symbol they used to.export * from './runtimes.js';@@ -152,7 +153,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, 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 }) {+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, streamingMode = 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@@ -772,6 +773,13 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m// declined request never sets it, a record can never claim a draft decode// the render did not perform....(draftDecoder ? { draftDecode: draftDecoder.id } : {}),+ // Block-streaming request (#6499). Recorded as the REQUESTED mode, same+ // convention as speedProfileId/draftDecode above — 'auto' and absence are+ // the same request, so a quality-default render's history row stays+ // byte-identical to one from before this setting existed. What the+ // bridge ACTUALLY did (active/reason/peakMb) is stamped separately by+ // finalizeGeneratedVideo from the child's STREAMPOLICY: report.+ ...(isDefaultVideoStreamingMode(streamingMode) ? {} : { streamingMode }),// IC-LoRA remix settings, stamped so the lightbox Remix flow can round-trip// them. The reference clip is recorded by BASENAME (not the absolute// staging path) — history is user-facing and a durable upload path is both@@ -872,6 +880,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', micSkipStage2,speedProfile,draftDecoder,+ streamingMode,ffmpegPath: ffmpeg,ffprobePath: ffprobe,}));diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.jsindex 4690a5cb5d..46667a06d3 100644--- a/server/services/videoGen/generateVideoHelpers.js+++ b/server/services/videoGen/generateVideoHelpers.js@@ -194,6 +194,27 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {return false;}}+ // What the runner ACTUALLY resolved for block streaming (STREAMPOLICY:<json>+ // — see scripts/generate_ltx2.py#resolve_streaming_policy /+ // report_streaming_policy). `meta.streamingMode` on the history record is+ // the REQUEST; this is the outcome — whether the pinned pipeline even had+ // the parameter, whether physical memory put 'auto' over the streaming+ // threshold, and (when active) the render's peak MLX memory, so a claim+ // that a smaller machine can now render a given model is backed by a+ // number from an actual render. Stamped on the job so finalizeGeneratedVideo+ // persists it.+ if (line.startsWith('STREAMPOLICY:')) {+ try {+ const applied = JSON.parse(line.slice('STREAMPOLICY:'.length));+ job.streamingPolicy = applied;+ console.log(`📦 block streaming [${jobId.slice(0, 8)}] ${applied?.pipeline || '?'} — ${applied?.active ? `streaming${applied?.peakMb != null ? ` (peak ${applied.peakMb} MB)` : ''}` : `resident${applied?.reason ? ` (${applied.reason})` : ''}`}`);+ return true;+ } catch {+ // Malformed payload — fall through to raw-logging so the broken line+ // is visible rather than silently swallowed (same as RUNTIME: above).+ return false;+ }+ }// Heartbeat for the queue's idle watchdog (see imageGen/local.js).videoGenEvents.emit('activity', { generationId: jobId });if (line.startsWith('STATUS:')) {@@ -598,6 +619,12 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,// reads back as a full decode instead of claiming a draft one. Absent on// every full-decode render and on runners that don't report one....(job.draftDecode ? { draftDecodeApplied: job.draftDecode } : {}),+ // What block streaming actually resolved to at render time (#6499).+ // `meta.streamingMode` above is the REQUEST; this is the outcome —+ // whether the pinned pipeline had the parameter, the RAM-based 'auto'+ // decision, and (when active) the render's peak MLX memory. Absent on+ // a resident-by-default render and on runners that don't report one.+ ...(job.streamingPolicy ? { streamingPolicyApplied: job.streamingPolicy } : {}),});return history;});diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 75dfed439d..75d9593d5b 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -652,6 +652,48 @@ describe('stitchVideos — history provenance', () => {expect(stitched).not.toHaveProperty('draftDecodeApplied');});});++ // Block streaming (#6499). Same shape as draft-decode above: the REQUEST is+ // chain-wide (every chunk is submitted with the same streamingMode), but the+ // OUTCOME is decided per child process — a mode that streamed on one chunk's+ // machine state and stayed resident on another's would misreport the clip.+ describe('streaming-policy outcome', () => {+ const applied = (active) => ({+ streamingMode: 'stream',+ streamingPolicyApplied: { pipeline: 'one-stage', requestedMode: 'stream', active, supports: true, reason: null },+ });++ it('inherits the request and a unanimous outcome', async () => {+ const stitched = await stitchHistory(applied(true), applied(true));++ expect(stitched.streamingMode).toBe('stream');+ expect(stitched.streamingPolicyApplied).toEqual(applied(true).streamingPolicyApplied);+ });++ it('inherits a unanimous resident outcome even when peakMb readings differ', async () => {+ const stitched = await stitchHistory(+ { ...applied(true), streamingPolicyApplied: { ...applied(true).streamingPolicyApplied, peakMb: 400 } },+ { ...applied(true), streamingPolicyApplied: { ...applied(true).streamingPolicyApplied, peakMb: 420 } },+ );++ // Unanimity is on the `active` verdict, not deep equality.+ expect(stitched.streamingPolicyApplied.active).toBe(true);+ });++ it('keeps the request but omits the outcome when the chunks disagree', async () => {+ const stitched = await stitchHistory(applied(true), applied(false));++ expect(stitched.streamingMode).toBe('stream');+ expect(stitched).not.toHaveProperty('streamingPolicyApplied');+ });++ it('stamps no outcome on a chain that never reported one', async () => {+ const stitched = await stitchHistory({ streamingMode: 'stream' }, { streamingMode: 'stream' });++ expect(stitched.streamingMode).toBe('stream');+ expect(stitched).not.toHaveProperty('streamingPolicyApplied');+ });+ });});describe('extractLastFrame — anchor selection', () => {@@ -5514,6 +5556,90 @@ describe('generateVideo — LTX-2.5 speed profile (#4875)', () => {});});+// #6499 — block streaming for the LTX-2/2.5 MLX runtimes. Three things must+// hold end to end: a non-default request reaches the helper argv; the+// default ('auto', which is also absence) leaves argv byte-identical to a+// render from before this setting existed; and history stamps the REQUESTED+// mode the same way speedProfileId/draftDecode do.+describe('generateVideo — LTX-2/2.5 block streaming (#6499)', () => {+ const renderArgs = async ({ jobId, modelId = 'ltx25_mlx_q8', ...rest }) => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const spawnMock = vi.mocked(spawnDetached);+ spawnMock.mockClear();+ await generateVideo({+ jobId,+ pythonPath: '/usr/bin/python3',+ modelId,+ prompt: 'a quiet street at dusk',+ width: 512, height: 512, numFrames: 25, fps: 24,+ ...rest,+ });+ const call = spawnMock.mock.calls.find(+ ([bin, args]) => (isLtx25Python(bin) || isLtx2Python(bin))+ && Array.isArray(args) && args.includes('--mode'),+ );+ expect(call).toBeTruthy();+ return call[1];+ };++ it('threads an explicit request into the helper argv', async () => {+ const args = await renderArgs({ jobId: 'stream-explicit', mode: 'text', streamingMode: 'stream' });+ expect(args[args.indexOf('--streaming-mode') + 1]).toBe('stream');+ });++ it('threads an explicit resident request too — not just the non-default "stream" value', async () => {+ const args = await renderArgs({ jobId: 'stream-resident', mode: 'text', streamingMode: 'resident' });+ expect(args[args.indexOf('--streaming-mode') + 1]).toBe('resident');+ });++ // DEFAULT PRESERVATION: 'auto' (and absence) is the bridge's own default.+ it.each([+ ['omitted', 'omitted', undefined],+ ['the explicit default mode', 'explicit', 'auto'],+ ])('leaves a render with %s byte-identical to the pre-feature argv', async (_name, label, streamingMode) => {+ const strip = (a) => a.map((v) => String(v).replace(/stream-[a-z-]+\.mp4$/, '<job>.mp4'));+ const baseline = strip(await renderArgs({ jobId: `stream-base-${label}`, mode: 'text', seed: 7 }));+ const args = strip(await renderArgs({ jobId: `stream-default-${label}`, mode: 'text', seed: 7, streamingMode }));+ expect(args).toEqual(baseline);+ expect(args).not.toContain('--streaming-mode');+ });++ describe('history metadata', () => {+ const metaFor = async (jobId, extra) => {+ let started = null;+ const onStarted = (e) => { if (e.generationId === jobId) started = e; };+ videoGenEvents.on('started', onStarted);+ await generateVideo({+ jobId,+ pythonPath: '/usr/bin/python3',+ modelId: 'ltx25_mlx_q8',+ prompt: 'a quiet street at dusk',+ width: 512, height: 512, numFrames: 25, fps: 24,+ mode: 'text',+ ...extra,+ });+ videoGenEvents.off('started', onStarted);+ expect(started).toBeTruthy();+ return started;+ };++ it('stamps the REQUESTED mode', async () => {+ const meta = await metaFor('stream-meta-explicit', { streamingMode: 'stream' });+ expect(meta.streamingMode).toBe('stream');+ });++ it('stamps nothing on a default render', async () => {+ const meta = await metaFor('stream-meta-default', {});+ expect(meta.streamingMode).toBeUndefined();+ });++ it('stamps nothing for the explicit default mode either', async () => {+ const meta = await metaFor('stream-meta-auto', { streamingMode: 'auto' });+ expect(meta.streamingMode).toBeUndefined();+ });+ });+});+// #4875 — the chunk entries of a chain are written `hidden: true`, so the// STITCHED record is the only one the user ever sees. Without inheriting the// profile there, a chained render's lightbox shows no "Speed profile" row atdiff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.jsindex afca704569..f80807778a 100644--- a/server/services/videoGen/renderArgs.js+++ b/server/services/videoGen/renderArgs.js@@ -13,6 +13,7 @@ import { ServerError } from '../../lib/errorHandler.js';import {isDefaultI2vReferenceMode, normalizeI2vReferenceMode,} from '../../lib/videoReferenceModes.js';+import { isDefaultVideoStreamingMode } from '../../lib/videoStreamingMode.js';import { extendLatentFrames } from '../../lib/videoContinuity.js';import { videoLoraLayoutIssue } from '../../lib/safetensors.js';import { formatLoraEffect, loraEffectIssue } from '../../lib/loraEffect.js';@@ -330,7 +331,7 @@ export const ltx25TextEncoderArgs = (textEncoder) => {return args;};-const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile }) => {+const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile, streamingMode }) => {assertByovRuntimeInstalled(model.runtime);// Map PortOS UI modes to the helper's subcommand. Native extend on ltx2// routes to ExtendPipeline.extend_from_video — conditions on the entire@@ -455,6 +456,14 @@ const buildLtx2Args = ({ model, ltxModelPath, prompt, negativePrompt, width, heiif (Array.isArray(loras) && loras.length > 0) {args.push('--user-loras', JSON.stringify(loras.map((l) => ({ path: l.path, strength: l.strength }))));}+ // Block-streaming request (#6499). Emitted ONLY when it is NOT the default —+ // 'auto' (absence) is the bridge's own default, so an unswapped render's+ // argv stays byte-identical to one from before this setting existed. The+ // bridge, not this builder, decides whether the resolved MODE's pinned+ // pipeline can honor it — see scripts/generate_ltx2.py#resolve_streaming_policy.+ if (!isDefaultVideoStreamingMode(streamingMode)) {+ args.push('--streaming-mode', streamingMode);+ }// Two-stage T2V experiment passes an explicit stage-2 step count; omitted// otherwise so the pipeline keeps its own default.if (stage2Steps != null) args.push('--stage2-steps', String(stage2Steps));@@ -1010,7 +1019,7 @@ export const buildMiniMaxH3Ref2vaArgs = ({return { bin: process.execPath, args };};-export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, ref2vaModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile, draftDecoder, ffmpegPath, ffprobePath }) => {+export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, ref2vaModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile, draftDecoder, streamingMode, ffmpegPath, ffprobePath }) => {// Reference-mode promise (#4874) — checked HERE rather than inside// buildLtx2Args because every runtime reaches this function and only one can// honor a loose reference. A wan22/mlx_video/H3 render that fell through to its@@ -1028,7 +1037,7 @@ export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequire// runtime. Existing notapalindrome models default to runtime: 'mlx_video'// (or undefined in legacy registries — see backfillRuntime in mediaModels.js).if (isLtx2FamilyRuntime(model.runtime)) {- return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile });+ return buildLtx2Args({ model, ltxModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, disableAudio, outputPath, previewDir, textEncoderRepo, textEncoder, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile, streamingMode });}// IC-LoRA remix modes are an LTX-2 primitive (ICLoraPipeline) — no other// runtime has an equivalent. The route guards this too, but a non-routediff --git a/server/services/videoGen/requestFields.js b/server/services/videoGen/requestFields.jsindex 255105519e..3045997d19 100644--- a/server/services/videoGen/requestFields.js+++ b/server/services/videoGen/requestFields.js@@ -14,6 +14,10 @@ export const VIDEO_GEN_LOCAL_ONLY_FIELDS = Object.freeze({TEXT_ENCODER_ID: 'textEncoderId',SPEED_PROFILE_ID: 'speedProfileId',DRAFT_DECODE: 'draftDecode',+ // Block-streaming request (#6499) — an LTX-2/2.5 MLX-only knob, so it makes+ // no sense on a Grok/fal/reactor render and stays local-only for the same+ // reason speedProfileId/draftDecode do.+ STREAMING_MODE: 'streamingMode',});export const VIDEO_GEN_LOCAL_ONLY_FIELD_NAMES = Object.freeze(diff --git a/server/services/videoGen/stitchVideos.js b/server/services/videoGen/stitchVideos.jsindex a9c8fbc5e8..6d15991a54 100644--- a/server/services/videoGen/stitchVideos.js+++ b/server/services/videoGen/stitchVideos.js@@ -40,6 +40,19 @@ const unanimousDraftDecodeOutcome = (videos) => {: {};};+// Fold the per-chunk STREAMPOLICY: reports into one claim, or none (#6499).+// Unanimity is on the `active` verdict — every chunk streamed, or every chunk+// stayed resident — rather than deep equality, so a peakMb reading that+// differs slightly between chunks doesn't defeat a chain that otherwise+// agrees on WHETHER it streamed.+const unanimousStreamingPolicyOutcome = (videos) => {+ const first = videos[0]?.streamingPolicyApplied;+ if (first === undefined) return {};+ return videos.every((v) => v?.streamingPolicyApplied?.active === first.active)+ ? { streamingPolicyApplied: first }+ : {};+};+export async function stitchVideos(videoIds, opts = {}) {const {id = randomUUID(),@@ -249,6 +262,11 @@ export async function stitchVideos(videoIds, opts = {}) {// the stitched record could never say the clip was decoded at preview// fidelity, and a Remix would quietly revert to Full.'draftDecode',+ // Block-streaming REQUEST (#6499) — same reasoning as draftDecode above:+ // every chunk is submitted with the same streamingMode, and the chunks+ // are hidden, so without inheriting it the stitched record could never+ // show which mode the chain was rendered with.+ 'streamingMode',].flatMap((key) => videos[0][key] === undefined ? [] : [[key, videos[0][key]]])),// The draft-decode OUTCOME is decided per child process — the runner falls// back to the full decoder on any load failure — so unlike the request@@ -258,6 +276,7 @@ export async function stitchVideos(videoIds, opts = {}) {// over a clip whose later chunks decoded differently would be exactly the// false fidelity claim this field exists to prevent....unanimousDraftDecodeOutcome(videos),+ ...unanimousStreamingPolicyOutcome(videos),// Inherit applied LoRAs from the first constituent clip (a chunk chain// shares one LoRA set across all chunks), so the visible stitched entry// round-trips LoRAs on Remix the same way a single render does — mirrorsdiff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.jsindex 2d9fc33330..459a672fa1 100644--- a/server/services/videoGen/submitJob.js+++ b/server/services/videoGen/submitJob.js@@ -8,6 +8,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { buildFederatedMediaRequest } from '../../lib/federatedMediaRequest.js';import { asFableLoomRenderSettings } from '../../lib/fableLoomProduction.js';import { isFullDecode } from '../../lib/videoDraftDecoders.js';+import { isDefaultVideoStreamingMode } from '../../lib/videoStreamingMode.js';import { isDefaultI2vReferenceMode } from '../../lib/videoReferenceModes.js';import { isDefaultSpeedProfile } from '../../lib/videoSpeedProfiles.js';import { isStockTextEncoder } from '../../lib/videoTextEncoders.js';@@ -281,6 +282,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {...(isStockTextEncoder(body.textEncoderId) ? {} : { textEncoderId: body.textEncoderId }),...(isDefaultSpeedProfile(body.speedProfileId) ? {} : { speedProfileId: body.speedProfileId }),...(isFullDecode(body.draftDecode) ? {} : { draftDecode: body.draftDecode }),+ ...(isDefaultVideoStreamingMode(body.streamingMode) ? {} : { streamingMode: body.streamingMode }),disableAudio: body.disableAudio === true || body.disableAudio === 'true',// Absent means "use the settings.videoGen.displaySleep default" — only// forward it when the form actually sent an explicit choice.